title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
986,145
1,619
2009-06-12T11:18:27Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
Arguments are [passed by assignment](http://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference). The rationale behind this is twofold: 1. the parameter passed in is actually a *reference* to an object (but the reference is passed by value) 2. some data types are m...
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
986,335
16
2009-06-12T12:16:45Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
You got some really good answers here. ``` x = [ 2, 4, 4, 5, 5 ] print x # 2, 4, 4, 5, 5 def go( li ) : li = [ 5, 6, 7, 8 ] # re-assigning what li POINTS TO, does not # change the value of the ORIGINAL variable x go( x ) print x # 2, 4, 4, 5, 5 [ STILL! ] raw_input( 'press any key to continue' ) ```
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
986,339
110
2009-06-12T12:17:48Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
Think of stuff being passed **by assignment** instead of by reference/by value. That way, it is allways clear, what is happening as long as you understand what happens during normal assignment. So, when passing a list to a function/method, the list is assigned to the parameter name. Appending to the list will result i...
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
986,495
190
2009-06-12T12:55:41Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
It is neither pass-by-value or pass-by-reference - it is call-by-object. See this, by Fredrik Lundh: <http://effbot.org/zone/call-by-object.htm> Here is a significant quote: > "...variables [names] are *not* objects; they cannot be denoted by other variables or referred to by objects." In your example, when the `Ch...
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
3,127,336
29
2010-06-27T12:33:45Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
(edit - Blair has updated his enormously popular answer so that it is now accurate) I think it is important to note that the current post with the most votes (by Blair Conrad), while being correct with respect to its result, is misleading and is borderline incorrect based on its definitions. While there are many langu...
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
6,963,425
23
2011-08-05T22:52:00Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
A simple trick I normally use is to just wrap it in a list: ``` def Change(self, var): var[0] = 'Changed' variable = ['Original'] self.Change(variable) print variable[0] ``` (Yeah I know this can be inconvenient, but sometimes it is simple enough to do this.)
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
8,140,747
345
2011-11-15T17:45:28Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
The problem comes from a misunderstanding of what variables are in Python. If you're used to most traditional languages, you have a mental model of what happens in the following sequence: ``` a = 1 a = 2 ``` You believe that `a` is a memory location that stores the value `1`, then is updated to store the value `2`. T...
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
12,440,140
43
2012-09-15T18:53:57Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
Technically, **Python always uses pass by reference values**. I am going to repeat [my other answer](http://stackoverflow.com/a/12438316/1346705) to support my statement. Python always uses pass-by-reference values. There isn't any exception. Any variable assignment means copying the reference value. No exception. Any...
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
15,697,476
35
2013-03-29T04:41:44Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
Effbot (aka Fredrik Lundh) has described Python's variable passing style as call-by-object: <http://effbot.org/zone/call-by-object.htm> Objects are allocated on the heap and pointers to them can be passed around anywhere. * When you make an assignment such as `x = 1000`, a dictionary entry is created that maps the st...
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
21,684,541
10
2014-02-10T17:57:39Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
As you can state you need to have a mutable object, but let me suggest you to check over the global variables as they can help you or even solve this kind of issue! <http://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python> example: ``` >>> def x(y): ... global z ...
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
21,700,609
15
2014-02-11T11:29:07Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
The key to understanding parameter passing is to stop thinking about "variables". **There are no variables in Python.** 1. Python has names and objects. 2. Assignment binds a name to an object. 3. Passing an argument into a function also binds a name (the parameter name of the function) to an object. That is all ther...
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
25,670,170
170
2014-09-04T16:05:35Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
I found the other answers rather long and complicated, so I created this simple diagram to explain the way Python treats variables and parameters. [![enter image description here](http://i.stack.imgur.com/FdaCu.png)](http://i.stack.imgur.com/FdaCu.png)
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
25,810,863
9
2014-09-12T14:40:18Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
A lot of insights in answers here, but i think an additional point is not clearly mentioned here explicitly. Quoting from python documentation <https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python> "In Python, variables that are only referenced inside a function ar...
How do I pass a variable by reference?
986,006
1,460
2009-06-12T10:23:51Z
29,293,411
10
2015-03-27T04:38:18Z
[ "python", "reference", "pass-by-reference", "argument-passing" ]
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' ``` class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def ...
Python’s pass-by-assignment scheme isn’t quite the same as C++’s reference parameters option, but it turns out to be very similar to the argument-passing model of the C language (and others) in practice: * Immutable arguments are effectively passed “**by value**.” Objects such as integers and strings are pas...
What does this line mean in Python?
986,087
9
2009-06-12T10:57:21Z
986,128
24
2009-06-12T11:12:23Z
[ "c#", "python", "windows", "cpu", "cpuid" ]
Which CPU information this code is trying to retrieve. This code is part of a larger package. I am not a Python programmer, and I want to convert this code to C#. ``` from ctypes import c_uint, create_string_buffer, CFUNCTYPE, addressof CPUID = create_string_buffer("\x53\x31\xc0\x40\x0f\xa2\x5b\xc3") cpuinfo = CFUNCTY...
It executes the following machine code: ``` push bx xor ax, ax inc ax cpuid pop bx retn ``` Basically it calls [CPUID](http://en.wikipedia.org/wiki/CPUID) instruction of the CPU in order to get information about the CPU. Since EAX=1 it gets the processor info and feature bits. The result 32-bit integer is then displa...
Encrypted file or db in python
986,403
5
2009-06-12T12:35:54Z
8,723,718
9
2012-01-04T08:02:47Z
[ "python", "sqlite", "encryption" ]
I have a sqlite3 db which i insert/select from in python. The app works great but i want to tweak it so no one can read from the DB without a password. How can i do this in python? note i have no idea where to start.
You can use SQLCipher. <http://sqlcipher.net/> Open Source Full Database Encryption for SQLite SQLCipher is an SQLite extension that provides transparent 256-bit AES encryption of database files. Pages are encrypted before being written to disk and are decrypted when read back. Due to the small footprint and great p...
Experiences of creating Social Network site in Django
986,594
13
2009-06-12T13:17:28Z
986,729
26
2009-06-12T13:48:18Z
[ "python", "django" ]
I plan to sneak in some Python/Django to my workdays and a possible social network site project seems like a good possibility. Django itself seems excellent, but I am skeptical about the quality of large amount of Django apps that seem to be available. I would like to hear what kind of experiences you may have had wi...
If you're interested in creating a social-network site in Django, you should definitely investigate [Pinax](http://pinaxproject.com/). This is a project that integrates a number of apps that are useful for creating this sort of site - friends, messaging, invitations, registration, etc. They're mostly very high quality.
Python thread exit code
986,616
6
2009-06-12T13:23:42Z
987,139
8
2009-06-12T15:03:59Z
[ "python", "multithreading", "exit-code" ]
Is there a way to tell if a thread has exited normally or because of an exception?
As mentioned, a wrapper around the Thread class could catch that state. Here's an example. ``` >>> from threading import Thread >>> class MyThread(Thread): def run(self): try: Thread.run(self) except Exception as self.err: pass # or raise else: self.err = None >>> mt = MyThread(t...
Using pysmbc to read files over samba
986,730
4
2009-06-12T13:48:29Z
989,430
10
2009-06-12T22:56:51Z
[ "python", "samba" ]
I am using the python-smbc library on Ubuntu to access a samba share. I can access the directory structure fine, I am however not sure how to access actual files and their content. The webpage (https://fedorahosted.org/pysmbc/) doesn't mention any thing, the code is in C/C++, with little documentation, so I am not quit...
I also have had trouble using smbfs (random system lockdowns and reboots) and needed a quick answer. I've also tried the `smbc` module but couldn't get any data with it. I went just as far as accessing the directory structure, just like you. Time was up and I had to deliver the code, so I took a shortcut: I wrote a ...
How can I change a user agent string programmatically?
987,217
4
2009-06-12T15:15:56Z
987,257
7
2009-06-12T15:22:40Z
[ "python", "user-agent" ]
I would like to write a program that changes my user agent string. How can I do this in Python?
I assume you mean a user-agent string in an HTTP request? This is just an HTTP header that gets sent along with your request. using Python's urllib2: ``` import urllib2 url = 'http://foo.com/' # add a header to define a custon User-Agent headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' } ...
adding a **kwarg to a class
987,237
3
2009-06-12T15:19:15Z
987,268
11
2009-06-12T15:24:18Z
[ "python", "django" ]
``` class StatusForm(ModelForm): bases = forms.ModelMultipleChoiceField( queryset=Base.objects.all(), #this should get overwritten widget=forms.SelectMultiple, ) class Meta: model = HiringStatus exclude = ('company', 'date') def __init__(self, *args, **kwargs): super(StatusForm, self).__init__(*arg...
That's because you're unpacking kwargs to the super constructor. Try to put this before calling super: ``` if kwargs.has_key('bases_queryset'): bases_queryset = kwargs['bases_queryset'] del kwargs['bases_queryset'] ``` but it's not an ideal solution...
adding a **kwarg to a class
987,237
3
2009-06-12T15:19:15Z
987,307
11
2009-06-12T15:29:33Z
[ "python", "django" ]
``` class StatusForm(ModelForm): bases = forms.ModelMultipleChoiceField( queryset=Base.objects.all(), #this should get overwritten widget=forms.SelectMultiple, ) class Meta: model = HiringStatus exclude = ('company', 'date') def __init__(self, *args, **kwargs): super(StatusForm, self).__init__(*arg...
As @Keeper indicates, you must not pass your "new" keyword arguments to the superclass. Best may be to do, before you call super's `__init__`: ``` bqs = kwargs.pop('bases_queryset', None) ``` and after that `__init__` call, check `if bqs is not None:` instead of using `has_key` (and use `bqs` instead of `kwargs['base...
How to know if urllib.urlretrieve succeeds?
987,876
41
2009-06-12T17:15:33Z
988,339
20
2009-06-12T18:46:04Z
[ "python", "networking", "urllib" ]
`urllib.urlretrieve` returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example: ``` urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg') ``` just returns silently, even if abc.jpg doesn't exist on google.com server, the generated `abc.jpg...
Consider using `urllib2` if it possible in your case. It is more advanced and easy to use than `urllib`. You can detect any HTTP errors easily: ``` >>> import urllib2 >>> resp = urllib2.urlopen("http://google.com/abc.jpg") Traceback (most recent call last): <<MANY LINES SKIPPED>> urllib2.HTTPError: HTTP Error 404: No...
How do I operate on the actual object, not a copy, in a python for loop?
988,155
5
2009-06-12T18:08:15Z
988,161
17
2009-06-12T18:09:35Z
[ "python" ]
let's say I have a list ``` a = [1,2,3] ``` I'd like to increment every item of that list in place. I want to do something as syntactically easy as ``` for item in a: item += 1 ``` but in that example python uses just the value of `item`, not its actual reference, so when I'm finished with that loop `a` still r...
Here ya go: ``` # Your for loop should be rewritten as follows: for index in xrange(len(a)): a[index] += 1 ``` Incidentally, item IS a reference to the `item` in `a`, but of course you can't assign a new value to an integer. For any mutable type, your code would work just fine: ``` >>> a = [[1], [2], [3], [4]] >...
How do I operate on the actual object, not a copy, in a python for loop?
988,155
5
2009-06-12T18:08:15Z
988,197
9
2009-06-12T18:19:15Z
[ "python" ]
let's say I have a list ``` a = [1,2,3] ``` I'd like to increment every item of that list in place. I want to do something as syntactically easy as ``` for item in a: item += 1 ``` but in that example python uses just the value of `item`, not its actual reference, so when I'm finished with that loop `a` still r...
Instead of your `map`-based solution, here's a list-comprehension-based solution ``` a = [item + 1 for item in a] ```
How do I operate on the actual object, not a copy, in a python for loop?
988,155
5
2009-06-12T18:08:15Z
988,218
12
2009-06-12T18:23:15Z
[ "python" ]
let's say I have a list ``` a = [1,2,3] ``` I'd like to increment every item of that list in place. I want to do something as syntactically easy as ``` for item in a: item += 1 ``` but in that example python uses just the value of `item`, not its actual reference, so when I'm finished with that loop `a` still r...
In python integers (and floats, and strings, and tuples) are immutable so you have the actual object (and not a copy), you just can't change it. What's happening is that in the line: `item += 1` you are creating a new integer (with a value of `item + 1`) and binding the name `item` to it. What you want to do, is chan...
Converting a String to Dictionary?
988,228
327
2009-06-12T18:25:02Z
988,249
16
2009-06-12T18:30:12Z
[ "python", "string", "dictionary" ]
How can I convert the `str` representation of a `dict`, such as the following string, into a `dict`? ``` s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" ``` I prefer not to use `eval`. What else can I use? The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the m...
If the string can *always* be trusted, you could use `eval` (or use `literal_eval` as suggested; it's safe no matter what the string is.) Otherwise you need a parser. A JSON parser (such as simplejson) would work if he only ever stores content that fits with the JSON scheme.
Converting a String to Dictionary?
988,228
327
2009-06-12T18:25:02Z
988,251
559
2009-06-12T18:30:45Z
[ "python", "string", "dictionary" ]
How can I convert the `str` representation of a `dict`, such as the following string, into a `dict`? ``` s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" ``` I prefer not to use `eval`. What else can I use? The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the m...
Starting in Python 2.6 you can use the built-in `ast.literal_eval`: ``` >>> import ast >>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}") {'muffin': 'lolz', 'foo': 'kitty'} ``` This is safer than using `eval`. As its own docs say: ``` >>> help(ast.literal_eval) Help on function literal_eval in module ast: ...
Converting a String to Dictionary?
988,228
327
2009-06-12T18:25:02Z
19,391,807
61
2013-10-15T21:54:27Z
[ "python", "string", "dictionary" ]
How can I convert the `str` representation of a `dict`, such as the following string, into a `dict`? ``` s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" ``` I prefer not to use `eval`. What else can I use? The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the m...
<http://docs.python.org/2/library/json.html> JSON can solve this problem though its decoder wants double quotes around keys and values. If you don't mind a replace hack... ``` import json s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" json_acceptable_string = s.replace("'", "\"") d = json.loads(json_acceptable_string) # ...
Converting a String to Dictionary?
988,228
327
2009-06-12T18:25:02Z
25,326,140
29
2014-08-15T12:07:45Z
[ "python", "string", "dictionary" ]
How can I convert the `str` representation of a `dict`, such as the following string, into a `dict`? ``` s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" ``` I prefer not to use `eval`. What else can I use? The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the m...
using `json.loads` ``` >>> import json >>> h = '{"foo":"bar", "foo2":"bar2"}' >>> type(h) <type 'str'> >>> d = json.loads(h) >>> d {u'foo': u'bar', u'foo2': u'bar2'} >>> type(d) <type 'dict'> ```
Converting a String to Dictionary?
988,228
327
2009-06-12T18:25:02Z
25,527,687
11
2014-08-27T12:50:13Z
[ "python", "string", "dictionary" ]
How can I convert the `str` representation of a `dict`, such as the following string, into a `dict`? ``` s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" ``` I prefer not to use `eval`. What else can I use? The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the m...
Use Json. the ast library consumes a lot of memory and and slower. I have a process that needs to read a text file of 156Mb. Ast with 5 minutes delay for the conversion dictionary Json and 1 minutes using 60% less memory!
Getting the first and last item in a python for loop
989,665
6
2009-06-13T00:57:36Z
989,673
10
2009-06-13T01:02:34Z
[ "python", "for-loop" ]
Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator? ``` from calendar import Calendar cal = Calendar(6) month_dates = cal.itermonthdates(year, month) for date in month_dates: if (is first item): # this is fake month_start = date i...
How about this? ``` for i, date in enumerate(month_dates): if i == 0: month_start = date month_end = date ``` `enumerate()` lets you find the first one, and the `date` variable falls out of the loop to give you the last one.
Getting the first and last item in a python for loop
989,665
6
2009-06-13T00:57:36Z
989,674
10
2009-06-13T01:02:49Z
[ "python", "for-loop" ]
Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator? ``` from calendar import Calendar cal = Calendar(6) month_dates = cal.itermonthdates(year, month) for date in month_dates: if (is first item): # this is fake month_start = date i...
I would just force it into a list at the beginning: ``` from calendar import Calendar, SUNDAY cal = Calendar(SUNDAY) month_dates = list(cal.itermonthdates(year, month)) month_start = month_dates[0] month_end = month_dates[-1] ``` Since there can only be 42 days (counting leading and tailing context), this has negli...
Getting the first and last item in a python for loop
989,665
6
2009-06-13T00:57:36Z
989,772
11
2009-06-13T02:20:45Z
[ "python", "for-loop" ]
Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator? ``` from calendar import Calendar cal = Calendar(6) month_dates = cal.itermonthdates(year, month) for date in month_dates: if (is first item): # this is fake month_start = date i...
Richie's got the right idea. Simpler: ``` month_dates = cal.itermonthdates(year, month) month_start = month_dates.next() for month_end in month_dates: pass # bletcherous ```
How do I draw out specific data from an opened url in Python using urllib2?
989,872
3
2009-06-13T03:38:04Z
989,920
11
2009-06-13T03:55:17Z
[ "python", "urllib2" ]
I'm new to Python and am playing around with making a very basic web crawler. For instance, I have made a simple function to load a page that shows the high scores for an online game. So I am able to get the source code of the html page, but I need to draw specific numbers from that page. For instance, the webpage look...
As another poster mentioned, [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) is a wonderful tool for this job. Here's the entire, ostentatiously-commented program. It could use a lot of error tolerance, but as long as you enter a valid username, it will pull all the scores from the corresponding web pag...
How to find out the arity of a method in Python
990,016
25
2009-06-13T05:07:17Z
990,022
38
2009-06-13T05:13:14Z
[ "python", "metaprogramming" ]
I'd like to find out the arity of a method in Python (the number of parameters that it receives). Right now I'm doing this: ``` def arity(obj, method): return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self class Foo: def bar(self, bla): pass arity(Foo(), "bar") # => 1 ``` I'd like ...
Module `inspect` from Python's standard library is your friend -- see [the online docs](http://docs.python.org/library/inspect.html)! `inspect.getargspec(func)` returns a tuple with four items, `args, varargs, varkw, defaults`: `len(args)` is the "primary arity", but arity can be anything from that to infinity if you h...
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux?
990,102
15
2009-06-13T06:14:47Z
990,154
8
2009-06-13T06:49:25Z
[ "python", "multithreading", "multicore", "gil", "python-stackless" ]
So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <http://blip.tv/file/2232410>. The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating system). But that this can seriously backfire on ...
Another solution is: <http://docs.python.org/library/multiprocessing.html> Note 1: This is **not** a limitation of the Python language, but of CPython implementation. Note 2: With regard to affinity, your OS shouldn't have a problem doing that itself.
How do convert unicode escape sequences to unicode characters in a python string
990,169
20
2009-06-13T06:56:27Z
992,314
24
2009-06-14T06:46:22Z
[ "python", "unicode" ]
When I tried to get the content of a tag using "unicode(head.contents[3])" i get the output similar to this: "Christensen Sk\xf6ld". I want the escape sequence to be returned as string. How to do it in python?
Assuming Python sees the name as a normal string, you'll first have to decode it to unicode: ``` >>> name 'Christensen Sk\xf6ld' >>> unicode(name, 'latin-1') u'Christensen Sk\xf6ld' ``` Another way of achieving this: ``` >>> name.decode('latin-1') u'Christensen Sk\xf6ld' ``` Note the "u" in front of the string, sig...
How to get a reference to current module's attributes in Python
990,422
78
2009-06-13T09:45:03Z
990,450
87
2009-06-13T10:01:56Z
[ "python" ]
What I'm trying to do would look like this in the command line: ``` >>> import mymodule >>> names = dir(mymodule) ``` How can I get a reference to all the names defined in `mymodule` from within `mymodule` itself? Something like this: ``` # mymodule.py names = dir(__thismodule__) ```
Just use globals() > globals() — Return a dictionary > representing the current global symbol > table. This is always the dictionary > of the current module (inside a > function or method, this is the module > where it is defined, not the module > from which it is called). <http://docs.python.org/library/functions....
How to get a reference to current module's attributes in Python
990,422
78
2009-06-13T09:45:03Z
991,115
9
2009-06-13T17:32:18Z
[ "python" ]
What I'm trying to do would look like this in the command line: ``` >>> import mymodule >>> names = dir(mymodule) ``` How can I get a reference to all the names defined in `mymodule` from within `mymodule` itself? Something like this: ``` # mymodule.py names = dir(__thismodule__) ```
Also check out the built-in [inspect](http://docs.python.org/2/library/inspect.html) module. It can be very handy.
How to get a reference to current module's attributes in Python
990,422
78
2009-06-13T09:45:03Z
991,158
102
2009-06-13T17:53:16Z
[ "python" ]
What I'm trying to do would look like this in the command line: ``` >>> import mymodule >>> names = dir(mymodule) ``` How can I get a reference to all the names defined in `mymodule` from within `mymodule` itself? Something like this: ``` # mymodule.py names = dir(__thismodule__) ```
As previously mentioned, globals gives you a dictionary as opposed to dir() which gives you a list of the names defined in the module. The way I typically see this done is like this: ``` import sys dir(sys.modules[__name__]) ```
How to leave/exit/deactivate a python virtualenv?
990,754
662
2009-06-13T14:15:36Z
990,779
1,129
2009-06-13T14:31:00Z
[ "python", "virtualenv", "virtualenvwrapper" ]
I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. ``` me@mymachine:~$ workon env1 (env1)me@mymachine:~$ workon env2 (env2)me@mymachine:~$ workon env1 (env1)me@mymachine:~$ ``` However, how do I exit all virtual machines and workon my real machine aga...
Usually, activating a virtualenv gives you a shell function named: ``` $ deactivate ``` which puts things back to normal. **Edit:** I have just looked specifically again at the code for virtualenvwrapper, and, yes, it too supports "deactivate" as the way to escape from all virtualenvs. ## **Edit:** If you are tryin...
How to leave/exit/deactivate a python virtualenv?
990,754
662
2009-06-13T14:15:36Z
27,947,686
17
2015-01-14T16:23:13Z
[ "python", "virtualenv", "virtualenvwrapper" ]
I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. ``` me@mymachine:~$ workon env1 (env1)me@mymachine:~$ workon env2 (env2)me@mymachine:~$ workon env1 (env1)me@mymachine:~$ ``` However, how do I exit all virtual machines and workon my real machine aga...
I defined an [alias](http://askubuntu.com/questions/17536/how-do-i-create-a-permanent-bash-alias) **workoff** as the opposite of workon: ``` alias workoff='deactivate' ``` Easy to remember: ``` [bobstein@host ~]$ workon django_project (django_project)[bobstein@host ~]$ workoff [bobstein@host ~]$ ```
Reclassing an instance in Python
990,758
45
2009-06-13T14:17:41Z
990,876
11
2009-06-13T15:31:03Z
[ "subclass", "python" ]
I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class. I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrid...
I'm not sure that the use of inheritance is best in this case (at least with regards to "reclassing"). It seems like you're on the right track, but it sounds like composition or aggregation would be best for this. Here's an example of what I'm thinking of (in untested, pseudo-esque code): ``` from copy import copy # ...
Reclassing an instance in Python
990,758
45
2009-06-13T14:17:41Z
991,262
14
2009-06-13T18:47:45Z
[ "subclass", "python" ]
I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class. I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrid...
Reclassing instances like this is done in [Mercurial](http://selenic.com/mercurial/) (a distributed revision control system) when extensions (plugins) want to change the object that represent the local repository. The object is called `repo` and is initially a `localrepo` instance. It is passed to each extension in tur...
Closing file opened by ConfigParser
990,867
8
2009-06-13T15:28:14Z
990,933
8
2009-06-13T16:03:27Z
[ "python", "configparser" ]
I have the following: ``` config = ConfigParser() config.read('connections.cfg') sections = config.sections() ``` How can I close the file opened with `config.read`? In my case, as new sections/data are added to the `config.cfg` file, I update my wxtree widget. However, it only updates once, and I suspect it's becau...
Use [readfp](http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser.readfp) instead of read: ``` with open('connections.cfg') as fp: config = ConfigParser() config.readfp(fp) sections = config.sections() ```
Closing file opened by ConfigParser
990,867
8
2009-06-13T15:28:14Z
16,666,375
11
2013-05-21T09:20:18Z
[ "python", "configparser" ]
I have the following: ``` config = ConfigParser() config.read('connections.cfg') sections = config.sections() ``` How can I close the file opened with `config.read`? In my case, as new sections/data are added to the `config.cfg` file, I update my wxtree widget. However, it only updates once, and I suspect it's becau...
`ConfigParser.read(filenames)` actually takes care of that for you. While coding I have encountered this issue and found myself asking myself the very same question: > *Reading basically means I also have to close this resource after I'm done with it, right?* I read the answer you got here suggesting to open the fil...
String reversal in Python
990,934
7
2009-06-13T16:03:35Z
990,940
30
2009-06-13T16:07:54Z
[ "python" ]
I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function? I am not able to convert the integer into a list so not able to apply the reverse function.
You can use the slicing operator to reverse a string: ``` s = "hello, world" s = s[::-1] print s # prints "dlrow ,olleh" ``` To convert an integer to a string, reverse it, and convert it back to an integer, you can do: ``` x = 314159 x = int(str(x)[::-1]) print x # prints 951413 ```
How to calculate a mod b in python?
991,027
53
2009-06-13T16:57:21Z
991,034
86
2009-06-13T16:59:23Z
[ "python" ]
Is there a modulo function in the python `math` library? Isn't `15 % 4`, 3? But `15 mod 4` is 1, right?
There's the `%` sign. It's not just for the remainder, it is the modulo operation.
How to calculate a mod b in python?
991,027
53
2009-06-13T16:57:21Z
991,037
8
2009-06-13T16:59:38Z
[ "python" ]
Is there a modulo function in the python `math` library? Isn't `15 % 4`, 3? But `15 mod 4` is 1, right?
Why don't you use % ? ``` print 4 % 2 # 0 ```
How to calculate a mod b in python?
991,027
53
2009-06-13T16:57:21Z
991,043
13
2009-06-13T17:00:46Z
[ "python" ]
Is there a modulo function in the python `math` library? Isn't `15 % 4`, 3? But `15 mod 4` is 1, right?
`mod = a % b` This stores the result of `a mod b` in the variable `mod`. And you are right, `15 mod 4` is 3, which is exactly what python returns: ``` >>> 15 % 4 3 ``` @Macarse: Yes, but that is true for any \= construct in python, so I should think there's no need to point that out seperately for modulo.
How to calculate a mod b in python?
991,027
53
2009-06-13T16:57:21Z
991,053
19
2009-06-13T17:06:26Z
[ "python" ]
Is there a modulo function in the python `math` library? Isn't `15 % 4`, 3? But `15 mod 4` is 1, right?
``` >>> 15 % 4 3 >>> ``` The modulo gives the remainder after integer division.
How to calculate a mod b in python?
991,027
53
2009-06-13T16:57:21Z
992,639
25
2009-06-14T10:58:40Z
[ "python" ]
Is there a modulo function in the python `math` library? Isn't `15 % 4`, 3? But `15 mod 4` is 1, right?
you can also try `divmod(x, y)` which returns a tuple `(x / y, x % y)`
Deleting files by type in Python on Windows
991,279
6
2009-06-13T19:00:23Z
991,306
15
2009-06-13T19:13:30Z
[ "python", "file" ]
I know how to delete single files, however I am lost in my implementation of how to delete all files in a directory of one type. Say the directory is \myfolder I want to delete all files that are .config files, but nothing to the other ones. How would I do this? Thanks Kindly
Use the [`glob`](http://docs.python.org/library/glob.html) module: ``` import os from glob import glob for f in glob ('myfolder/*.config'): os.unlink (f) ```
Counting repeated characters in a string in Python
991,350
21
2009-06-13T19:37:41Z
991,374
79
2009-06-13T19:51:22Z
[ "python" ]
I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter? **Update** (in reference to [Anthony's answer](http://stackoverflow.com/questions/991350/counting-repeated-characters-i...
``` import collections d = collections.defaultdict(int) for c in thestring: d[c] += 1 ``` A `collections.defaultdict` is like a `dict` (subclasses it, actually), but when an entry is sought and not found, instead of reporting it doesn't have it, it makes it and inserts it by calling the supplied 0-argument callab...
Counting repeated characters in a string in Python
991,350
21
2009-06-13T19:37:41Z
991,379
18
2009-06-13T19:54:45Z
[ "python" ]
I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter? **Update** (in reference to [Anthony's answer](http://stackoverflow.com/questions/991350/counting-repeated-characters-i...
My first idea was to do this: ``` chars = "abcdefghijklmnopqrstuvwxyz" check_string = "i am checking this string to see how many times each character appears" for char in chars: count = check_string.count(char) if count > 1: print char, count ``` This is not a good idea, however! This is going to scan the st...
Counting repeated characters in a string in Python
991,350
21
2009-06-13T19:37:41Z
991,475
12
2009-06-13T20:40:15Z
[ "python" ]
I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter? **Update** (in reference to [Anthony's answer](http://stackoverflow.com/questions/991350/counting-repeated-characters-i...
This is the shortest, most practical I can comeup with without importing extra modules. ``` text = "hello cruel world. This is a sample text" d = dict.fromkeys(text, 0) for c in text: d[c] += 1 ``` print d['a'] would output 2 And it's also fast.
Counting repeated characters in a string in Python
991,350
21
2009-06-13T19:37:41Z
993,044
17
2009-06-14T15:39:00Z
[ "python" ]
I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter? **Update** (in reference to [Anthony's answer](http://stackoverflow.com/questions/991350/counting-repeated-characters-i...
Python 2.7+ includes the [collections.Counter](http://docs.python.org/dev/py3k/library/collections.html#collections.Counter) class: ``` import collections results = collections.Counter(the_string) print(results) ```
Changing brightness of the Macbook(Pro) keyboard backlight
991,813
3
2009-06-13T23:52:27Z
991,823
8
2009-06-13T23:58:38Z
[ "python", "osx", "hardware" ]
Programaticly, how can I modify the brightness of the backlit keyboard on a Macbook or Macbook Pro using Python?
Amit Singh discusses these undocumented APIs in this [online bonus chapter](http://www.osxbook.com/book/bonus/chapter10/light/), but does so using C -- I'm not sure if a Python extension exists to do the same work from Python, perhaps as part of PyObjC (otherwise, such an extension would have to be written -- or `ctype...
Creating a doctype with lxml's etree
991,864
10
2009-06-14T00:41:05Z
1,099,484
9
2009-07-08T17:33:40Z
[ "python", "doctype", "lxml", "elementtree" ]
I want to add doctypes to my XML documents that I'm generating with LXML's etree. However I cannot figure out how to add a doctype. Hardcoding and concating the string is not an option. I was expecting something along the lines of how PI's are added in etree: ``` pi = etree.PI(...) doc.addprevious(pi) ``` But it's ...
You can create your document with a doctype to begin with: ``` # Adapted from example on http://codespeak.net/lxml/tutorial.html import lxml.etree as et import StringIO s = """<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "cheese"> <!ENTITY eacute "&#233;"> ]> <root> <a>&tasty; ...
Creating a doctype with lxml's etree
991,864
10
2009-06-14T00:41:05Z
11,298,809
20
2012-07-02T18:02:36Z
[ "python", "doctype", "lxml", "elementtree" ]
I want to add doctypes to my XML documents that I'm generating with LXML's etree. However I cannot figure out how to add a doctype. Hardcoding and concating the string is not an option. I was expecting something along the lines of how PI's are added in etree: ``` pi = etree.PI(...) doc.addprevious(pi) ``` But it's ...
This worked for me: `print etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", doctype="<!DOCTYPE TEST_FILE>")`
Why is there no GIL in the Java Virtual Machine? Why does Python need one so bad?
991,904
158
2009-06-14T01:12:55Z
991,917
212
2009-06-14T01:20:55Z
[ "java", "python", "multithreading", "jvm", "gil" ]
I'm hoping someone can provide some insight as to what's fundamentally different about the Java Virtual Machine that allows it to implement threads nicely without the need for a Global Interpreter Lock (GIL), while Python necessitates such an evil.
Python (the language) doesn't need a GIL (which is why it can perfectly be implemented on JVM [Jython] and .NET [IronPython], and those implementations multithread freely). CPython (the popular implementation) has always used a GIL for ease of coding (esp. the coding of the garbage collection mechanisms) and of integra...
Why is there no GIL in the Java Virtual Machine? Why does Python need one so bad?
991,904
158
2009-06-14T01:12:55Z
1,162,596
41
2009-07-22T01:27:17Z
[ "java", "python", "multithreading", "jvm", "gil" ]
I'm hoping someone can provide some insight as to what's fundamentally different about the Java Virtual Machine that allows it to implement threads nicely without the need for a Global Interpreter Lock (GIL), while Python necessitates such an evil.
The JVM (at least hotspot) does have a similar concept to the "GIL", it's just much finer in its lock granularity, most of this comes from the GC's in hotspot which are more advanced. In CPython it's one big lock (probably not that true, but good enough for arguments sake), in the JVM it's more spread about with diffe...
Custom Filter in Django Admin on Django 1.3 or below
991,926
66
2009-06-14T01:25:39Z
1,260,346
22
2009-08-11T13:25:48Z
[ "python", "django", "django-admin" ]
How can I add a custom filter to django admin (the filters that appear on the right side of a model dashboard)? I know its easy to include a filter based on a field of that model, but what about a "calculated" field like this: ``` class NewsItem(models.Model): headline = models.CharField(max_length=4096, blank=Fal...
you have to write a custom FilterSpec (not documentend anywhere). Look here for an example: <http://www.djangosnippets.org/snippets/1051/>
Custom Filter in Django Admin on Django 1.3 or below
991,926
66
2009-06-14T01:25:39Z
1,294,952
55
2009-08-18T16:19:35Z
[ "python", "django", "django-admin" ]
How can I add a custom filter to django admin (the filters that appear on the right side of a model dashboard)? I know its easy to include a filter based on a field of that model, but what about a "calculated" field like this: ``` class NewsItem(models.Model): headline = models.CharField(max_length=4096, blank=Fal...
Thanks to gpilotino for giving me the push into the right direction for implementing this. I noticed the question's code is using a datetime to figure out when its live . So I used the DateFieldFilterSpec and subclassed it. ``` from django.db import models from django.contrib.admin.filterspecs import FilterSpec, Choi...
Custom Filter in Django Admin on Django 1.3 or below
991,926
66
2009-06-14T01:25:39Z
6,355,234
9
2011-06-15T08:52:52Z
[ "python", "django", "django-admin" ]
How can I add a custom filter to django admin (the filters that appear on the right side of a model dashboard)? I know its easy to include a filter based on a field of that model, but what about a "calculated" field like this: ``` class NewsItem(models.Model): headline = models.CharField(max_length=4096, blank=Fal...
In current django development version there is the support for custom filters: <https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter>
Why are 008 and 009 invalid keys for Python dicts?
991,978
13
2009-06-14T02:12:20Z
991,983
10
2009-06-14T02:16:19Z
[ "python", "dictionary", "python-2.x" ]
Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example: ``` some_dict = { 001: "spam", 002: "eggs", 003: "foo", 004: "bar", 008: "anything", # Throws a SyntaxError 009: "nothing" # Throws a SyntaxError } ``` **Update**: Problem solved. I wasn't aw...
Python takes 008 and 009 as octal numbers, therefore...invalid. You can only go up to 007, then the next number would be 010 (8) then 011 (9). Try it in a Python interpreter, and you'll see what I mean.
Why are 008 and 009 invalid keys for Python dicts?
991,978
13
2009-06-14T02:12:20Z
991,984
8
2009-06-14T02:16:33Z
[ "python", "dictionary", "python-2.x" ]
Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example: ``` some_dict = { 001: "spam", 002: "eggs", 003: "foo", 004: "bar", 008: "anything", # Throws a SyntaxError 009: "nothing" # Throws a SyntaxError } ``` **Update**: Problem solved. I wasn't aw...
In Python (and many other languages), starting a number with **a leading "0"** indicates an **octal number** (base 8). Using this leading-zero notation is called an **octal literal**. Octal numbers go 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, etc. So **08 (in octal) is invalid**. If you remove the leading zeros, your code will ...
Why are 008 and 009 invalid keys for Python dicts?
991,978
13
2009-06-14T02:12:20Z
991,985
28
2009-06-14T02:16:52Z
[ "python", "dictionary", "python-2.x" ]
Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example: ``` some_dict = { 001: "spam", 002: "eggs", 003: "foo", 004: "bar", 008: "anything", # Throws a SyntaxError 009: "nothing" # Throws a SyntaxError } ``` **Update**: Problem solved. I wasn't aw...
In python and some other languages, if you start a number with a 0, the number is interpreted as being in octal (base 8), where only 0-7 are valid digits. You'll have to change your code to this: ``` some_dict = { 1: "spam", 2: "eggs", 3: "foo", 4: "bar", 8: "anything", 9: "nothing" } ``` Or ...
Why are 008 and 009 invalid keys for Python dicts?
991,978
13
2009-06-14T02:12:20Z
991,986
7
2009-06-14T02:17:12Z
[ "python", "dictionary", "python-2.x" ]
Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example: ``` some_dict = { 001: "spam", 002: "eggs", 003: "foo", 004: "bar", 008: "anything", # Throws a SyntaxError 009: "nothing" # Throws a SyntaxError } ``` **Update**: Problem solved. I wasn't aw...
@[DoxaLogos](#991983) is right. It's not that they're invalid keys - they're invalid literals. If you tried to use them in any other context, you'd get the same error.
Does running separate python processes avoid the GIL?
992,136
8
2009-06-14T04:07:08Z
992,141
16
2009-06-14T04:09:11Z
[ "python" ]
I'm curious in how the Global Interpreter Lock in python actually works. If I have a c++ application launch four separate instances of a python script will they run in parallel on separate cores, or does the GIL go even deeper then just the single process that was launched and control all python process's regardless of...
The GIL only affects threads within a single process. The `multiprocessing` module is in fact an alternative to `threading` that lets Python programs use multiple cores &c. Your scenario will easily allow use of multiple cores, too.
Why am I getting "'ResultSet' has no attribute 'findAll'" using BeautifulSoup in Python?
992,183
7
2009-06-14T04:41:27Z
992,291
18
2009-06-14T06:17:16Z
[ "python", "urllib2", "beautifulsoup" ]
So I am learning Python slowly, and am trying to make a simple function that will draw data from the high scores page of an online game. This is someone else's code that i rewrote into one function (which might be the problem), but I am getting this error. Here is the code: ``` >>> from urllib2 import urlopen >>> from...
Wow. Triptych provided a [*great* answer](http://stackoverflow.com/questions/989872/how-do-i-draw-out-specific-data-from-an-opened-url-in-python-using-urllib2/989920#989920) to a related question. We can see, [from BeautifulSoup's source code](http://code.google.com/p/google-blog-converters-appengine/source/browse/tru...
django for loop counter break
992,230
25
2009-06-14T05:15:53Z
992,243
64
2009-06-14T05:32:19Z
[ "python", "django", "for-loop" ]
This is hopefully a quick/easy one. I know a way to work around this via a custom template tag, but I was curious if there were other methods I was over looking. I've created a gallery function of sorts for my blog, and I have a gallery list page that paginates all my galleries. Now, I don't want to show all the photos...
Use: ``` {% for photos in gallery.photo_set|slice:":3" %} ```
Determining Letter Frequency Of Cipher Text
992,408
4
2009-06-14T08:07:04Z
992,417
17
2009-06-14T08:12:00Z
[ "python", "encryption", "cryptography" ]
I am trying to make a tool that finds the frequencies of letters in some type of cipher text. Lets suppose it is all lowercase a-z no numbers. The encoded message is in a txt file I am trying to build a script to help in cracking of substitution or possibly transposition ciphers. Code so far: ``` cipher = open('ciph...
``` import collections d = collections.defaultdict(int) for c in 'test': d[c] += 1 print d # defaultdict(<type 'int'>, {'s': 1, 'e': 1, 't': 2}) ``` From a file: ``` myfile = open('test.txt') for line in myfile: line = line.rstrip('\n') for c in line: d[c] += 1 ``` For the genius that is the [d...
Create zip archive for instant download
992,621
5
2009-06-14T10:42:32Z
992,628
11
2009-06-14T10:47:16Z
[ "python", "django", "zip", "archive" ]
In a web app I am working on, the user can create a zip archive of a folder full of files. Here here's the code: ``` files = torrent[0].files zipfile = z.ZipFile(zipname, 'w') output = "" for f in files: zipfile.write(settings.PYRAT_TRANSMISSION_DOWNLOAD_DIR + "/" + f.name, f.name) downloadurl = settings.PYRAT_...
Check this [Serving dynamically generated ZIP archives in Django](http://stackoverflow.com/questions/67454/serving-dynamically-generated-zip-archives-in-django)
Create zip archive for instant download
992,621
5
2009-06-14T10:42:32Z
9,829,044
7
2012-03-22T19:19:18Z
[ "python", "django", "zip", "archive" ]
In a web app I am working on, the user can create a zip archive of a folder full of files. Here here's the code: ``` files = torrent[0].files zipfile = z.ZipFile(zipname, 'w') output = "" for f in files: zipfile.write(settings.PYRAT_TRANSMISSION_DOWNLOAD_DIR + "/" + f.name, f.name) downloadurl = settings.PYRAT_...
As mandrake says, constructor of HttpResponse accepts iterable objects. Luckily, ZIP format is such that archive can be created in single pass, central directory record is located at the very end of file: ![enter image description here](http://i.stack.imgur.com/sQMBQ.jpg) (Picture from [Wikipedia](http://en.wikipedi...
Creating a range of dates in Python
993,358
125
2009-06-14T18:03:59Z
993,367
188
2009-06-14T18:06:32Z
[ "python", "datetime", "date" ]
I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this? ``` import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelt...
Marginally better... ``` base = datetime.datetime.today() date_list = [base - datetime.timedelta(days=x) for x in range(0, numdays)] ```
Creating a range of dates in Python
993,358
125
2009-06-14T18:03:59Z
993,369
24
2009-06-14T18:06:57Z
[ "python", "datetime", "date" ]
I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this? ``` import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelt...
You can write a generator function that returns date objects starting from today: ``` import datetime def date_generator(): from_date = datetime.datetime.today() while True: yield from_date from_date = from_date - datetime.timedelta(days=1) ``` This generator returns dates starting from today and going b...
Creating a range of dates in Python
993,358
125
2009-06-14T18:03:59Z
11,324,695
16
2012-07-04T07:52:08Z
[ "python", "datetime", "date" ]
I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this? ``` import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelt...
yeah, reinvent the wheel.... just search the forum and you'll get something like this: ``` from dateutil import rrule from datetime import datetime list(rrule.rrule(rrule.DAILY,count=100,dtstart=datetime.now())) ```
Creating a range of dates in Python
993,358
125
2009-06-14T18:03:59Z
23,190,286
57
2014-04-21T03:16:13Z
[ "python", "datetime", "date" ]
I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this? ``` import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelt...
Pandas is great for time series in general, and has direct support for date ranges. ``` import pandas as pd datelist = pd.date_range(pd.datetime.today(), periods=100).tolist() ``` It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in `bdate_range`. See <http...
Creating a range of dates in Python
993,358
125
2009-06-14T18:03:59Z
24,637,447
20
2014-07-08T16:50:27Z
[ "python", "datetime", "date" ]
I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this? ``` import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelt...
Get range of dates between specified start and end date (Optimized for time & space complexity): ``` import datetime start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y") end = datetime.datetime.strptime("07-07-2014", "%d-%m-%Y") date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start...
Creating a range of dates in Python
993,358
125
2009-06-14T18:03:59Z
32,616,832
13
2015-09-16T19:12:49Z
[ "python", "datetime", "date" ]
I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this? ``` import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelt...
You can also use the day ordinal to make it simpler: ``` def daterange(start_date, end_date): for ordinal in range(start_date.toordinal(), end_date.toordinal()): yield datetime.date.fromordinal(ordinal) ```
What is the equivalent of object oriented constructs in python?
994,476
9
2009-06-15T04:15:32Z
994,482
28
2009-06-15T04:24:13Z
[ "python", "oop" ]
How does python handle object oriented constructs such as **abstract**, **virtual**, **pure virtual** etc Examples and links would really be good.
An **abstract** method is one that (in the base class) raises `NotImplementedError`. An abstract class, like in C++, is any class that has one or more abstract methods. All methods in Python are virtual (i.e., all can be overridden by subclasses). A "pure virtual" method would presumably be the same thing as an abst...
How can I parse a C header file with Perl?
994,732
6
2009-06-15T06:33:14Z
994,805
9
2009-06-15T07:05:21Z
[ "python", "c", "perl", "parsing", "header-files" ]
I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back. For example I have some structure like ``` const BYTE Some_Idx[] = { 4,7,10,15,17,19,24,29, 31,32,35,45,49,51,52,54, 55,58,60,64,65,66,6...
Keeping your data lying around in a header makes it trickier to get at using other programs like Perl. Another approach you might consider is to keep this data in a database or another file and regenerate your header file as-needed, maybe even as part of your build system. The reason for this is that generating C is mu...
How can this be written on a single line?
995,234
3
2009-06-15T09:38:48Z
995,238
20
2009-06-15T09:40:24Z
[ "python", "django", "dictionary", "list-comprehension" ]
I've seen some Python list comprehensions before, but can this be done in a single line of Python? ``` errs = {} for f in form: if f.errors: errs[f.auto_id] = f.errors ```
``` errs = dict((f.auto_id, f.errors) for f in form if f.errors) ```
How can this be written on a single line?
995,234
3
2009-06-15T09:38:48Z
995,685
9
2009-06-15T11:50:21Z
[ "python", "django", "dictionary", "list-comprehension" ]
I've seen some Python list comprehensions before, but can this be done in a single line of Python? ``` errs = {} for f in form: if f.errors: errs[f.auto_id] = f.errors ```
Python 3.0 has dict comprehensions as a shorter/more readable form of the anser provided by Steef: ``` errs = {f.auto_id: f.errors for f in form if f.errors} ```
Parsing an existing config file
996,183
4
2009-06-15T13:43:23Z
996,461
11
2009-06-15T14:35:14Z
[ "python", "parsing", "config" ]
I have a config file that is in the following form: ``` protocol sample_thread { { AUTOSTART 0 } { BITMAP thread.gif } { COORDS {0 0} } { DATAFORMAT { { TYPE hl7 } { PREPROCS { { ARGS {{}} } { PROCS sample_proc } } } } } } ``` The real file may not ...
[pyparsing](http://pyparsing.wikispaces.com/Introduction) is pretty handy for quick and simple parsing like this. A bare minimum would be something like: ``` import pyparsing string = pyparsing.CharsNotIn("{} \t\r\n") group = pyparsing.Forward() group << pyparsing.Group(pyparsing.Literal("{").suppress() + ...
How can i write my own aggregate functions with sqlalchemy?
996,922
4
2009-06-15T15:59:46Z
997,467
8
2009-06-15T18:01:31Z
[ "python", "sqlite", "sqlalchemy", "aggregate-functions" ]
How can I write my own aggregate functions with SQLAlchemy? As an easy example I would like to use numpy to calculate the variance. With sqlite it would look like this: ``` import sqlite3 as sqlite import numpy as np class self_written_SQLvar(object): def __init__(self): import numpy as np self.values = [] ...
The creation of new aggregate functions is backend-dependant, and must be done directly with the API of the underlining connection. SQLAlchemy offers no facility for creating those. However after created you can just use them in SQLAlchemy normally. Example: ``` import sqlalchemy from sqlalchemy import Column, Table...
Unit testing for exceptions in Python constructor
997,244
7
2009-06-15T17:10:21Z
997,353
13
2009-06-15T17:34:49Z
[ "python", "unit-testing", "constructor" ]
I'm just a beginner in Python and programming in general, and have some questions about the unittest module. I have a class, and in the `__init__` method I am doing some assertions to check for bad arguments. I would like to create a unittest which checks for such AssertionError when creating new instances. In the un...
> In the unittest module, one can test (with `assertRaises`) for specific exception when a callable is called, but obviously that will apply to methods of the class. What is the proper way to run such test for the constructor? The constructor is itself a callable: ``` self.assertRaises(AssertionError, MyClass, arg1, ...
What does %s mean in Python?
997,797
78
2009-06-15T19:05:10Z
997,807
85
2009-06-15T19:06:11Z
[ "python" ]
What does %s mean in Python? And what does the following bit of code do? For instance... ``` if len(sys.argv) < 2: sys.exit('Usage: %s database-name' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was not found!' % sys.argv[1]) ```
It is a string formatting syntax (which it borrows from C). Please see ["Formatting Strings"](http://www.diveintopython.net/native_data_types/formatting_strings.html): > Python supports formatting values into > strings. Although this can include > very complicated expressions, the most > basic usage is to insert valu...
What does %s mean in Python?
997,797
78
2009-06-15T19:05:10Z
997,819
7
2009-06-15T19:09:30Z
[ "python" ]
What does %s mean in Python? And what does the following bit of code do? For instance... ``` if len(sys.argv) < 2: sys.exit('Usage: %s database-name' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was not found!' % sys.argv[1]) ```
'%s' indicates a conversion type of 'string' when using python's string formatting capabilities. More specifically, '%s' converts a specified value to a string using the str() function. Compare this with the '%r' conversion type that uses the repr() function for value conversion. Take a look at the following: <http://...
What does %s mean in Python?
997,797
78
2009-06-15T19:05:10Z
998,157
48
2009-06-15T20:17:14Z
[ "python" ]
What does %s mean in Python? And what does the following bit of code do? For instance... ``` if len(sys.argv) < 2: sys.exit('Usage: %s database-name' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was not found!' % sys.argv[1]) ```
Andrew's answer is good. And just to help you out a bit more, here's how you use multiple formatting in one string ``` "Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike". ``` If you are using ints instead of string, use %d instead of %s. ``` "My name is %s and i'm %d" % ('john', 12) #My nam...
Django ImportError at / no matter what I do
998,702
3
2009-06-15T22:17:10Z
998,933
12
2009-06-15T23:19:57Z
[ "python", "django" ]
So I've just started playing around with Django and I decided to give it a try on my server. So I installed Django and created a new project, following the basics outlined in the tutorial on Djangoproject.com Unfortunatly, no matter what I do, I can't get views to work: I constantly get ``` ImportError at / No modul...
Your `urls.py` is wrong; you should consider reading [this](http://docs.djangoproject.com/en/dev/intro/tutorial03/#intro-tutorial03) and [this](http://docs.djangoproject.com/en/dev/topics/http/urls/#topics-http-urls). You don't include a function; you include a module. You name a function, `mecore.views.index`. You on...
Handle either a list or single integer as an argument
998,938
21
2009-06-15T23:23:35Z
998,949
9
2009-06-15T23:28:10Z
[ "python", "list", "function", "integer" ]
A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly. This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intel...
I would do just this: ``` def select_rows(to_select): # For a list for row in range(0, table.numRows()): if _table.item(row, 1).text() in to_select: table.selectRow(row) ``` and expect that the argument will always be a list - even if its just a list of one element. Remember: > It is eas...
Handle either a list or single integer as an argument
998,938
21
2009-06-15T23:23:35Z
998,965
10
2009-06-15T23:31:14Z
[ "python", "list", "function", "integer" ]
A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly. This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intel...
You could redefine your function to take any number of arguments, like this: ``` def select_rows(*arguments): for row in range(0, table.numRows()): if _table.item(row, 1).text() in arguments: table.selectRow(row) ``` Then you can pass a single argument like this: ``` select_rows('abc') ``` m...
Handle either a list or single integer as an argument
998,938
21
2009-06-15T23:23:35Z
999,278
13
2009-06-16T01:52:38Z
[ "python", "list", "function", "integer" ]
A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly. This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intel...
Actually I agree with Andrew Hare above, just pass a list with a single element. But if you really must accept a non-list, how about just turning it into a list in that case? ``` def select_rows(to_select): if type(to_select) is not list: to_select = [ to_select ] for row in range(0, table.numRows()): ...
Is &#x10; a valid character in XML?
998,950
9
2009-06-15T23:28:31Z
999,048
12
2009-06-15T23:59:20Z
[ "python", "xml" ]
On this data: ``` <row Id="37501" PostId="135577" Text="...uses though.&#x10;"/> ``` I'm getting an error with the Python sax parser: ``` xml.sax._exceptions.SAXParseException: comments.xml:29776:332: reference to invalid character number ``` I trimmed the example; 332 points to "&#x10;". Is the parser correct in ...
As others have stated, you probably meant `&#10;`. The reason why `&#x10;` (0x10 = 10h = 16) is invalid is that it's explicitly excluded by the XML 1.0 standard: (<http://www.w3.org/TR/xml/#NT-Char>) ``` Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] ```
run django with xampp on windows
1,000,444
11
2009-06-16T09:32:33Z
1,001,029
37
2009-06-16T11:56:55Z
[ "python", "django", "xampp" ]
can i run django (Python framework) site with xampp on windows? Please guide me.
[XAMPP](http://www.apachefriends.org/en/xampp.html) for windows contains: Apache, MySQL, PHP + PEAR, Perl, `mod_php`, `mod_perl`, `mod_ssl`, OpenSSL, phpMyAdmin, Webalizer, Mercury Mail Transport System for Win32 and NetWare Systems v3.32, Ming, JpGraph, FileZilla FTP Server, mcrypt, eAccelerator, SQLite, and WEB-DAV +...
How to keep a Python script output window open?
1,000,900
108
2009-06-16T11:31:16Z
1,000,912
18
2009-06-16T11:33:39Z
[ "python", "windows" ]
I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?
Start the script from already open cmd window or at the end of script add something like this, in Python 2: ``` raw_input("Press enter to exit ;)") ``` Or, in Python 3: ``` input("Press enter to exit ;)") ```
How to keep a Python script output window open?
1,000,900
108
2009-06-16T11:31:16Z
1,000,968
96
2009-06-16T11:43:55Z
[ "python", "windows" ]
I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?
You have a few options: 1. Run the program from an already-open terminal. Open a command prompt and type: ``` python myscript.py ``` For that to work you need the python executable in your path. Just check on [how to edit environment variables](http://superuser.com/questions/284342/what-are-path-and-othe...