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
Call a function with argument list in python
817,087
104
2009-05-03T13:43:33Z
817,296
187
2009-05-03T15:17:44Z
[ "python", "function" ]
I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this: ``` def wrapper(func, args): func(args) def func1(x): print(x) def func2(x, y, z): return x+y+z wrapper(func1, [x]) wrapper(func2, [x, y, z]) ``` In this case firs...
To expand a little on the other answers: In the line: ``` def wrapper(func, *args): ``` The \* next to `args` means "take the rest of the parameters given and put them in a list called `args`". In the line: ``` func(*args) ``` The \* next to `args` here means "take this list called args and 'unwrap' it into t...
Call a function with argument list in python
817,087
104
2009-05-03T13:43:33Z
817,834
7
2009-05-03T19:48:20Z
[ "python", "function" ]
I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this: ``` def wrapper(func, args): func(args) def func1(x): print(x) def func2(x, y, z): return x+y+z wrapper(func1, [x]) wrapper(func2, [x, y, z]) ``` In this case firs...
The literal answer to your question (to do exactly what you asked, changing only the wrapper, not the functions or the function calls) is simply to alter the line ``` func(args) ``` to read ``` func(*args) ``` This tells Python to take the list given (in this case, `args`) and pass its contents to the function as p...
Call a function with argument list in python
817,087
104
2009-05-03T13:43:33Z
817,968
13
2009-05-03T20:50:24Z
[ "python", "function" ]
I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this: ``` def wrapper(func, args): func(args) def func1(x): print(x) def func2(x, y, z): return x+y+z wrapper(func1, [x]) wrapper(func2, [x, y, z]) ``` In this case firs...
The simpliest way to wrap a function ``` func(*args, **kwargs) ``` ... is to manually write a wrapper that would call *func()* inside itself: ``` def wrapper(*args, **kwargs): # do something before try: return func(*a, **kwargs) finally: # do something after ``...
Delete digits in Python (Regex)
817,122
6
2009-05-03T13:59:17Z
817,140
7
2009-05-03T14:04:05Z
[ "python", "regex", "digits" ]
I'm trying to delete all digits from a string. However the next code deletes as well digits contained in any word, and obviously I don't want that. I've been trying many regular expressions with no success. Thanks! --- ``` s = "This must not b3 delet3d, but the number at the end yes 134411" s = re.sub("\d+", "", s) ...
Add a space before the \d+. ``` >>> s = "This must not b3 delet3d, but the number at the end yes 134411" >>> s = re.sub(" \d+", " ", s) >>> s 'This must not b3 delet3d, but the number at the end yes ' ``` Edit: After looking at the comments, I decided to form a more complete answer. I think this accounts for all the ...
Delete digits in Python (Regex)
817,122
6
2009-05-03T13:59:17Z
817,164
11
2009-05-03T14:12:44Z
[ "python", "regex", "digits" ]
I'm trying to delete all digits from a string. However the next code deletes as well digits contained in any word, and obviously I don't want that. I've been trying many regular expressions with no success. Thanks! --- ``` s = "This must not b3 delet3d, but the number at the end yes 134411" s = re.sub("\d+", "", s) ...
Try this: ``` "\b\d+\b" ``` That'll match only those digits that are not part of another word.
Overriding the save method in Django ModelForm
817,284
48
2009-05-03T15:12:00Z
817,364
115
2009-05-03T15:54:10Z
[ "python", "django", "django-forms", "django-admin" ]
I'm having trouble overriding a `ModelForm` save method. This is the error I'm receiving: ``` Exception Type: TypeError Exception Value: save() got an unexpected keyword argument 'commit' ``` My intentions are to have a form submit many values for 3 fields, to then create an object for each combination of th...
In your `save` you have to have the argument `commit`. If anything overrides your form, or wants to modify what it's saving, it will do `save(commit=False)`, modify the output, and then save it itself. Also, your ModelForm should return the model it's saving. Usually a ModelForm's `save` will look something like: ```...
Update Facebooks Status using Python
817,431
3
2009-05-03T16:25:43Z
817,443
12
2009-05-03T16:31:21Z
[ "python", "facebook" ]
Is there an easy way to update my Facebook status ("What's on your mind?" box) using Python code ?
Check out [PyFacebook](http://github.com/sciyoshi/pyfacebook/tree/master) which has a [tutorial](http://wiki.developers.facebook.com/index.php/PyFacebook%5FTutorial), from... Facebook! Blatantly ripped from the documentation on that page and untested, you'd probably do something like this: ``` import facebook fb = fa...
Python's random: What happens if I don't use seed(someValue)?
817,705
17
2009-05-03T18:44:19Z
817,742
17
2009-05-03T19:04:15Z
[ "python", "random", "seed" ]
a)In this case does the random number generator uses the system's clock (making the seed change) on each run? b)Is the seed used to generate the pseudo-random values of expovariate(lambda)?
"Use the Source, Luke!"...;-). Studying <http://svn.python.org/view/python/trunk/Lib/random.py?revision=68378&view=markup> will rapidly reassure you;-). What happens when seed isn't set (that's the "i is None" case): ``` if a is None: try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedErro...
Unique session id in python
817,882
33
2009-05-03T20:11:02Z
817,892
21
2009-05-03T20:14:37Z
[ "python", "session" ]
How do I generate a unique session id in Python?
You can use the [uuid library](http://docs.python.org/library/uuid.html) like so: ``` import uuid my_id = uuid.uuid1() # or uuid.uuid4() ```
Unique session id in python
817,882
33
2009-05-03T20:11:02Z
818,040
18
2009-05-03T21:19:46Z
[ "python", "session" ]
How do I generate a unique session id in Python?
``` import os, base64 def generate_session(): return base64.b64encode(os.urandom(16)) ```
Unique session id in python
817,882
33
2009-05-03T20:11:02Z
6,092,448
70
2011-05-23T03:07:22Z
[ "python", "session" ]
How do I generate a unique session id in Python?
I hate to say this, but none of the other solutions posted here are correct with regards to being a "secure session ID." ``` # pip install M2Crypto import base64, M2Crypto def generate_session_id(num_bytes = 16): return base64.b64encode(M2Crypto.m2.rand_bytes(num_bytes)) ``` Neither `uuid()` or `os.urandom()` are...
Creating dictionaries with pre-defined keys
817,884
3
2009-05-03T20:12:18Z
817,893
7
2009-05-03T20:14:56Z
[ "python", "dictionary" ]
In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created?
You can easily extend any built in type. This is how you'd do it with a dict: ``` >>> class MyClass(dict): ... def __init__(self, *args, **kwargs): ... self['mykey'] = 'myvalue' ... self['mykey2'] = 'myvalue2' ... >>> x = MyClass() >>> x['mykey'] 'myvalue' >>> x {'mykey2': 'myvalue2', 'myke...
Letting users upload Python scripts for execution
818,402
12
2009-05-04T00:20:54Z
818,417
8
2009-05-04T00:34:51Z
[ "python", "cgi" ]
I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with other AI's in an online web game I wrote in Python. I e...
I am in no way associated with this site and I'm only linking it because it tries to achieve what you are getting after: jailing of python. The site is [code pad](http://codepad.org/about). According to the about page it is ran under [geordi](http://www.xs4all.nl/~weegen/eelis/geordi/) and traps all sys calls with ptr...
Letting users upload Python scripts for execution
818,402
12
2009-05-04T00:20:54Z
818,430
8
2009-05-04T00:44:33Z
[ "python", "cgi" ]
I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with other AI's in an online web game I wrote in Python. I e...
Using PyPy you can create a python sandbox. The sandbox is a separate and supposedly secure python environment where you can execute their scripts. More info here <http://codespeak.net/pypy/dist/pypy/doc/sandbox.html> "In theory it's impossible to do anything bad or read a random file on the machine from this prompt....
Shouldn't __metaclass__ force the use of a metaclass in Python?
818,483
6
2009-05-04T01:18:10Z
818,502
13
2009-05-04T01:29:25Z
[ "python", "oop", "python-3.x", "metaclass" ]
I've been trying to learn about metaclasses in Python. I get the main idea, but I can't seem to activate the mechanism. As I understand it, you can specify M to be as the metaclass when constructing a class K by setting `__metaclass__` to M at the global or class level. To test this out, I wrote the following program: ...
In Python 3 (which you are using) metaclasses are specified by a keyword parameter in the class definition: ``` class ClassMeta(metaclass=M): pass ``` Specifying a `__metaclass__` class property or global variable is old syntax from Python 2.x and not longer supported. See also ["What's new in Python 3"](http://doc...
Is it possible to implement a Python for range loop without an iterator variable?
818,828
115
2009-05-04T05:06:46Z
818,836
58
2009-05-04T05:14:35Z
[ "python", "loops", "for-loop", "range" ]
Is is possible to do this; ``` for i in range(some_number): #do something ``` without the i? If you just want to do something x amount of times and don't need the iterator.
Off the top of my head, no. I think the best you could do is something like this: ``` def loop(f,n): for i in xrange(n): f() loop(lambda: <insert expression here>, 5) ``` But I think you can just live with the extra `i` variable. Here is the option to use the `_` variable, which in reality, is just another var...
Is it possible to implement a Python for range loop without an iterator variable?
818,828
115
2009-05-04T05:06:46Z
818,849
36
2009-05-04T05:20:11Z
[ "python", "loops", "for-loop", "range" ]
Is is possible to do this; ``` for i in range(some_number): #do something ``` without the i? If you just want to do something x amount of times and don't need the iterator.
The general idiom for assigning to a value that isn't used is to name it `_`. ``` for _ in range(times): do_stuff() ```
Is it possible to implement a Python for range loop without an iterator variable?
818,828
115
2009-05-04T05:06:46Z
818,888
46
2009-05-04T05:39:39Z
[ "python", "loops", "for-loop", "range" ]
Is is possible to do this; ``` for i in range(some_number): #do something ``` without the i? If you just want to do something x amount of times and don't need the iterator.
You may be looking for ``` for _ in itertools.repeat(None, times): ... ``` this is THE fastest way to iterate `times` times in Python.
Is it possible to implement a Python for range loop without an iterator variable?
818,828
115
2009-05-04T05:06:46Z
818,903
17
2009-05-04T05:44:00Z
[ "python", "loops", "for-loop", "range" ]
Is is possible to do this; ``` for i in range(some_number): #do something ``` without the i? If you just want to do something x amount of times and don't need the iterator.
What everyone suggesting you to use \_ isn't saying is that \_ is frequently used as a shortcut to one of the [gettext](http://docs.python.org/library/gettext.html) functions, so if you want your software to be available in more than one language then you're best off avoiding using it for other purposes. ``` import ge...
Is it possible to implement a Python for range loop without an iterator variable?
818,828
115
2009-05-04T05:06:46Z
829,729
9
2009-05-06T14:00:39Z
[ "python", "loops", "for-loop", "range" ]
Is is possible to do this; ``` for i in range(some_number): #do something ``` without the i? If you just want to do something x amount of times and don't need the iterator.
Here's a random idea that utilizes (abuses?) the [data model](http://docs.python.org/reference/datamodel.html#object.%5F%5Fnonzero%5F%5F). ``` class Counter(object): def __init__(self, val): self.val = val def __nonzero__(self): self.val -= 1 return self.val >= 0 x = Counter(5) while x: # Do someth...
How to convert strings numbers to integers in a list?
818,949
9
2009-05-04T06:09:00Z
818,956
41
2009-05-04T06:11:33Z
[ "python", "string", "integer", "numbers" ]
I have a list say: ``` ['batting average', '306', 'ERA', '1710'] ``` How can I convert the intended numbers without touching the strings? Thank you for the help.
``` changed_list = [int(f) if f.isdigit() else f for f in original_list] ```
Python, who is calling my python module
819,217
3
2009-05-04T08:08:10Z
819,240
9
2009-05-04T08:15:38Z
[ "python", "cgi" ]
I have one Python module that can be called by a CGI script (passing it information from a form) or from the command line (passing it options and arguments from the command line). Is there a way to establish if the module has been called from the CGI script or from the command line ??
This will do it: ``` import os if os.environ.has_key('REQUEST_METHOD'): # You're being run as a CGI script. else: # You're being run from the command line. ```
How can I check if an ip is in a network in python
819,355
55
2009-05-04T08:59:20Z
819,420
23
2009-05-04T09:21:29Z
[ "python", "networking", "ip-address" ]
Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python? Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.
[This article](http://code.activestate.com/recipes/66517/) shows you can do it with [`socket`](http://docs.python.org/library/socket.html) and [`struct`](http://docs.python.org/library/struct.html) modules without too much extra effort. I added a little to the article as follows: ``` import socket,struct def makeMask...
How can I check if an ip is in a network in python
819,355
55
2009-05-04T08:59:20Z
820,124
83
2009-05-04T13:35:13Z
[ "python", "networking", "ip-address" ]
Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python? Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.
I like to use [netaddr](http://pypi.python.org/pypi/netaddr) for that: ``` from netaddr import CIDR, IP if IP("192.168.0.1") in CIDR("192.168.0.0/24"): print "Yay!" ``` As arno\_v pointed out in the comments, new version of netaddr does it like this: ``` from netaddr import IPNetwork, IPAddress if IPAddress("19...
How can I check if an ip is in a network in python
819,355
55
2009-05-04T08:59:20Z
1,004,527
51
2009-06-17T00:15:35Z
[ "python", "networking", "ip-address" ]
Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python? Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.
Using [ipaddress](http://code.google.com/p/ipaddress-py/) ([in the stdlib since 3.3](http://docs.python.org/3.3/library/ipaddress.html), [at PyPi for 2.6/2.7](https://pypi.python.org/pypi/ipaddress)): ``` >>> import ipaddress >>> ipaddress.ip_address('192.168.0.1') in ipaddress.ip_network('192.168.0.0/24') True ``` -...
How can I check if an ip is in a network in python
819,355
55
2009-05-04T08:59:20Z
4,464,961
7
2010-12-16T20:16:55Z
[ "python", "networking", "ip-address" ]
Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python? Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.
This code is working for me on Linux x86. I haven't really given any thought to endianess issues, but I have tested it against the "ipaddr" module using over 200K IP addresses tested against 8 different network strings, and the results of ipaddr are the same as this code. ``` def addressInNetwork(ip, net): import s...
rules for slugs and unicode
820,496
10
2009-05-04T15:04:38Z
824,829
8
2009-05-05T13:21:26Z
[ "python", "google-app-engine", "url", "unicode", "friendly-url" ]
After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles. url encoding is very restrictive. See <http://www.blooberry.com/indexdot/html/topics/urlencoding.htm> So, for example how do folks deal with for title slugs for things like "...
Nearly-complete transliteration table (for latin, greek and cyrillic character sets) can be found in [slughifi library](http://trac.django-fr.org/browser/site/trunk/project/links/slughifi.py?rev=47). It is geared towards Django, but can be easily modified to fit general needs (I use it with Werkzeug-based app on AppEng...
python, __slots__, and "attribute is read-only"
820,671
15
2009-05-04T15:50:36Z
820,710
7
2009-05-04T16:02:54Z
[ "python", "exception", "descriptor", "readonlyattribute" ]
I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows: ``` class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = MyClass() # create one a.m = "?...
`__slots__` works with instance variables, whereas what you have there is a class variable. This is how you should be doing it: ``` class MyClass( object ) : __slots__ = ( "m", ) def __init__(self): self.m = None a = MyClass() a.m = "?" # No error ```
python, __slots__, and "attribute is read-only"
820,671
15
2009-05-04T15:50:36Z
820,730
34
2009-05-04T16:07:51Z
[ "python", "exception", "descriptor", "readonlyattribute" ]
I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows: ``` class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = MyClass() # create one a.m = "?...
When you declare instance variables using `__slots__`, Python creates a [descriptor object](http://www.python.org/doc/2.5.1/ref/descriptors.html#descriptors) as a class variable with the same name. In your case, this descriptor is overwritten by the class variable `m` that you are defining at the following line: ``` ...
python, __slots__, and "attribute is read-only"
820,671
15
2009-05-04T15:50:36Z
821,773
13
2009-05-04T20:05:24Z
[ "python", "exception", "descriptor", "readonlyattribute" ]
I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows: ``` class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = MyClass() # create one a.m = "?...
You are completely misusing `__slots__`. It prevents the creation of `__dict__` for the instances. This only makes sense if you run into memory problems with many small objects, because getting rid of `__dict__` can reduce the footprint. This is a hardcore optimization that is not needed in 99.9% of all cases. If you ...
SyntaxError in finally (Django)
820,778
4
2009-05-04T16:20:23Z
820,799
13
2009-05-04T16:25:56Z
[ "python", "django" ]
I'm using Django, and I have the following error: > Exception Type: SyntaxError > Exception Value: invalid syntax (views.py, **line 115**) My viws.py code looks like this: ``` def myview(request): try: [...] except MyExceptionClass, e: [...] finally: render_to_response('template.html', {}, context_instance = Requ...
What version of python are you using? Prior to 2.5 you can't have both an except clause and a finally clause in the same try block. You can work around this by nesting try blocks. ``` def myview(request): try: try: [...] except MyExceptionClass, e: [...] finally: ...
Where can I find some "hello world"-simple Beautiful Soup examples?
821,173
7
2009-05-04T17:53:51Z
821,238
14
2009-05-04T18:09:56Z
[ "python", "beautifulsoup" ]
I'd like to do a very simple replacement using Beautiful Soup. Let's say I want to visit all A tags in a page and append "?foo" to their href. Can someone post or link to an example of how to do something simple like that?
``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(''' <html> <head><title>Testing</title></head> <body> <a href="http://foo.com/">foo</a> <a href="http://bar.com/bar">Bar</a> </body> </html>''') for link in soup.findAll('a'): # find all links link['href'] = link['href'] + '?foo' ...
what python feature is illustrated in this code?
821,855
5
2009-05-04T20:21:03Z
821,926
22
2009-05-04T20:33:48Z
[ "python", "language-features" ]
I read Storm ORM's tutorial at <https://storm.canonical.com/Tutorial>, and I stumbled upon the following piece of code : ``` store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie") ``` I'm not sure that the second argument of the **find** method will be evaluated to True/False. I think it will be...
`Person.name` has a overloaded `__eq__` method that returns not a boolean value but an object that stores both sides of the expression; that object can be examined by the `find()` method to obtain the attribute and value that it will use for filtering. I would describe this as a type of lazy evaluation pattern. In Sto...
what python feature is illustrated in this code?
821,855
5
2009-05-04T20:21:03Z
821,941
8
2009-05-04T20:36:00Z
[ "python", "language-features" ]
I read Storm ORM's tutorial at <https://storm.canonical.com/Tutorial>, and I stumbled upon the following piece of code : ``` store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie") ``` I'm not sure that the second argument of the **find** method will be evaluated to True/False. I think it will be...
The magic is in the Person.name property, which results in a type that overloads `__eq__` (&c) to return non-bools. Storm's sources are online for you to browse (and CAUTIOUSLY imitate;-) at <http://bazaar.launchpad.net/~storm/storm/trunk/files/head%3A/storm/> -- as you'll see, they don't go light on the "black magic";...
what python feature is illustrated in this code?
821,855
5
2009-05-04T20:21:03Z
822,115
9
2009-05-04T21:19:20Z
[ "python", "language-features" ]
I read Storm ORM's tutorial at <https://storm.canonical.com/Tutorial>, and I stumbled upon the following piece of code : ``` store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie") ``` I'm not sure that the second argument of the **find** method will be evaluated to True/False. I think it will be...
`Person.name` is an instance of some type with a custom `__eq__` method. While `__eq__` normally returns a boolean(ish) value, it can actually return whatever you want, including a lambda. See [Python special method names](http://docs.python.org/reference/datamodel.html#special-method-names) for more on this and relate...
Python sockets buffering
822,001
13
2009-05-04T20:50:59Z
822,057
18
2009-05-04T21:05:08Z
[ "python", "sockets", "buffering" ]
Let's say I want to read a line from a socket, using the standard `socket` module: ``` def read_line(s): ret = '' while True: c = s.recv(1) if c == '\n' or c == '': break else: ret += c return ret ``` What exactly happens in `s.recv(1)`? Will it issue a s...
The `recv()` call is handled directly by calling the C library function. It will block waiting for the socket to have data. In reality it will just let the `recv()` system call block. `file.readline()` is an efficient buffered implementation. It is not threadsafe, because it presumes it's the only one reading the fil...
Python sockets buffering
822,001
13
2009-05-04T20:50:59Z
822,788
20
2009-05-05T00:38:27Z
[ "python", "sockets", "buffering" ]
Let's say I want to read a line from a socket, using the standard `socket` module: ``` def read_line(s): ret = '' while True: c = s.recv(1) if c == '\n' or c == '': break else: ret += c return ret ``` What exactly happens in `s.recv(1)`? Will it issue a s...
If you are concerned with performance and control the socket completely (you are not passing it into a library for example) then try implementing your own buffering in Python -- Python string.find and string.split and such can be amazingly fast. ``` def linesplit(socket): buffer = socket.recv(4096) buffering =...
How do I iterate over the HTML attributes of a Beautiful Soup element?
822,571
17
2009-05-04T23:14:02Z
822,601
28
2009-05-04T23:24:13Z
[ "python", "beautifulsoup" ]
How do I iterate over the HTML attributes of a Beautiful Soup element? Like, given: ``` <foo bar="asdf" blah="123">xyz</foo> ``` I want "bar" and "blah".
``` from BeautifulSoup import BeautifulSoup page = BeautifulSoup('<foo bar="asdf" blah="123">xyz</foo>') for attr, value in page.find('foo').attrs: print attr, "=", value # Prints: # bar = asdf # blah = 123 ```
Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings?
823,030
3
2009-05-05T02:25:32Z
823,077
18
2009-05-05T02:39:37Z
[ "python" ]
I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically: I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So: ``` >>> type(myDict) <type 'dict'> >>> type(myDict[u'myKey']) <type 'dict'> >>> type(myDict[u'myKey'...
Really simple way, though I'm not sure you'd call it Pythonic: ``` newDict = eval(repr(myDict).lower()) ``` Saner way: ``` newDict = dict((k1.lower(), dict((k2.lower(), [s.lower() for s in v2]) for k2, v2 in v1.iteritems())) for k1, v1 in myDict.iteritems()) ```
Yaml merge in Python
823,196
11
2009-05-05T03:31:41Z
823,240
17
2009-05-05T03:46:17Z
[ "python", "configuration", "yaml" ]
So I'm toying around with the idea of making myself (and anyone who cares to use it of course) a little boilerplate library in Python for Pygame. I would like a system where settings for the application are provided with a yaml file. So I was thinking it would be useful if the library provided a default yaml tree and ...
You could use [PyYAML](http://pyyaml.org/) for parsing the files, and then the following function to merge two trees: ``` def merge(user, default): if isinstance(user,dict) and isinstance(default,dict): for k,v in default.iteritems(): if k not in user: user[k] = v el...
What does += mean in Python?
823,561
9
2009-05-05T06:10:26Z
823,567
22
2009-05-05T06:11:25Z
[ "python", "syntax" ]
I see code like this for example in Python: ``` if cnt > 0 and len(aStr) > 1: while cnt > 0: aStr = aStr[1:]+aStr[0] cnt += 1 ``` What does the `+=` mean?
``` a += b ``` is *in this case* the same as ``` a = a + b ``` In this case cnt += 1 means that cnt is increased by one. Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1. **Edit**: quote [Carl Meyer](http://stackoverflow.com/users/3207/carl-meyer): ``[..] the answer is misleadingly...
What does += mean in Python?
823,561
9
2009-05-05T06:10:26Z
823,583
7
2009-05-05T06:16:56Z
[ "python", "syntax" ]
I see code like this for example in Python: ``` if cnt > 0 and len(aStr) > 1: while cnt > 0: aStr = aStr[1:]+aStr[0] cnt += 1 ``` What does the `+=` mean?
Google 'python += operator' leads you to <http://docs.python.org/library/operator.html> Search for += once the page loads up for a more detailed answer.
What does += mean in Python?
823,561
9
2009-05-05T06:10:26Z
823,878
63
2009-05-05T08:28:49Z
[ "python", "syntax" ]
I see code like this for example in Python: ``` if cnt > 0 and len(aStr) > 1: while cnt > 0: aStr = aStr[1:]+aStr[0] cnt += 1 ``` What does the `+=` mean?
`a += b` is essentially the same as `a = a + b`, except that: * `+` always returns a newly allocated object, but `+=` should (but doesn't have to) modify the object in-place if it's mutable (e.g. `list` or `dict`, but `int` and `str` are immutable). * In `a = a + b`, `a` is evaluated twice. <http://docs.python.org/re...
Extract domain name from a host name
825,694
15
2009-05-05T16:17:13Z
828,380
15
2009-05-06T07:09:22Z
[ "python", "dns", "hostname" ]
Is there a programatic way to find the domain name from a given hostname? given -> www.yahoo.co.jp return -> yahoo.co.jp The approach that works but is very slow is: split on "." and remove 1 group from the left, join and query an SOA record using dnspython when a valid SOA record is returned, consider that a domain...
There's no trivial definition of which "domain name" is the parent of any particular "host name". Your current method of traversing up the tree until you see an `SOA` record is actually the most correct. Technically, what you're doing there is finding a "zone cut", and in the vast majority of cases that will correspo...
Abstract class + mixin + multiple inheritance in python
825,945
11
2009-05-05T17:10:43Z
826,118
12
2009-05-05T17:49:37Z
[ "python", "abstract-class", "multiple-inheritance", "mixins" ]
So, I think the code probably explains what I'm trying to do better than I can in words, so here goes: ``` import abc class foo(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def bar(self): pass class bar_for_foo_mixin(object): def bar(self): print "This should satisfy the ...
Shouldn't the inheritance be the other way round? In the MRO `foo` currently comes before `bar_for_foo_mixin`, and then rightfully complains. With `class myfoo(bar_for_foo_mixin, foo)` it should work. And I am not sure if your class design is the right way to do it. Since you use a mixin for implementing `bar` it migh...
Changing case (upper/lower) on adding data through Django admin site
825,955
4
2009-05-05T17:11:49Z
826,126
12
2009-05-05T17:52:51Z
[ "python", "django", "admin", "case" ]
I'm configuring the admin site of my new project, and I have a little doubt on how should I do for, on hitting 'Save' when adding data through the admin site, everything is converted to upper case... Edit: Ok I know the .upper property, and I I did a view, I would know how to do it, but I'm wondering if there is any p...
If your goal is to only have things converted to upper case when saving in the admin section, you'll want to [create a form with custom validation](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin) to make the case change: ``` class MyArticleAdminForm(forms.ModelForm): ...
Python: finding uid/gid for a given username/groupname (for os.chown)
826,082
50
2009-05-05T17:39:54Z
826,099
79
2009-05-05T17:43:19Z
[ "python" ]
What's a good way to find the uid/gid for a given username or groupname using Python? I need to set file ownership with os.chown and need the integer ids instead of the alphabetic. [Quick note]: getpwnam works great but is not available on windows, so here's some code that creates stubs to allow you to run the same co...
Use the [`pwd`](http://docs.python.org/library/pwd.html) and [`grp`](http://docs.python.org/library/grp.html) modules: ``` from pwd import getpwnam print getpwnam('someuser')[2] # or print getpwnam('someuser').pw_uid ```
How do I convert a string 2 bytes long to an integer in python
826,284
4
2009-05-05T18:28:44Z
826,305
18
2009-05-05T18:33:17Z
[ "python" ]
I have a python program I've inherited and am trying to extend. I have extracted a two byte long string into a string called pS. pS 1st byte is 0x01, the second is 0x20, decimal value == 288 I've been trying to get its value as an integer, I've used lines of the form ``` x = int(pS[0:2], 16) # this was fat fingere...
Look at the [struct](http://www.python.org/doc/2.5.2/lib/module-struct.html) module. ``` struct.unpack( "h", pS[0:2] ) ``` For a signed 2-byte value. Use "H" for unsigned.
List Comprehensions and Conditions?
826,407
7
2009-05-05T18:57:53Z
826,430
17
2009-05-05T19:02:28Z
[ "python", "list", "list-comprehension" ]
I am trying to see if I can make this code better using list comprehensions. Lets say that I have the following lists: ``` a_list = [ 'HELLO', 'FOO', 'FO1BAR', 'ROOBAR', 'SHOEBAR' ] regex_list = [lambda x: re.search(r'FOO', x, re.IGNORECASE), lambda ...
Sure, I think this should do it ``` newlist = [s for s in a_list if not any(r(s) for r in regex_list)] ``` *EDIT*: on closer inspection, I notice that your example code actually adds to the new list each string in `a_list` that doesn't match *all* the regexes - and what's more, it adds each string once for each regex...
Python: Mixing files and loops
826,493
17
2009-05-05T19:20:06Z
826,518
10
2009-05-05T19:23:58Z
[ "python", "file", "loops", "while-loop" ]
I'm writing a script that logs errors from another program and restarts the program where it left off when it encounters an error. For whatever reasons, the developers of this program didn't feel it necessary to put this functionality into their program by default. Anyways, the program takes an input file, parses it, ...
Use `for` and [enumerate](http://docs.python.org/library/functions.html#enumerate). Example: ``` for line_num, line in enumerate(file): if line_num < cut_off: print line ``` **NOTE**: This assumes you are already cleaning up your file handles, etc. Also, the [takewhile](http://docs.python.org/library/it...
Python: Mixing files and loops
826,493
17
2009-05-05T19:20:06Z
826,615
38
2009-05-05T19:47:25Z
[ "python", "file", "loops", "while-loop" ]
I'm writing a script that logs errors from another program and restarts the program where it left off when it encounters an error. For whatever reasons, the developers of this program didn't feel it necessary to put this functionality into their program by default. Anyways, the program takes an input file, parses it, ...
You get the ValueError because your code probably has `for line in original:` in addition to `original.readline()`. An easy solution which fixes the problem without making your program slower or consume more memory is changing ``` for line in original: ... ``` to ``` while True: line = original.readline() ...
Combining 2 .csv files by common column
826,812
8
2009-05-05T20:36:44Z
826,836
13
2009-05-05T20:43:30Z
[ "python", "shell", "join", "csv", "debian" ]
So I have two .csv files where the first line in file 1 is: ``` MPID,Title,Description,Model,Category ID,Category Description,Subcategory ID,Subcategory Description,Manufacturer ID,Manufacturer Description,URL,Manufacturer (Brand) URL,Image URL,AR Price,Price,Ship Price,Stock,Condition ``` The first line from file 2:...
``` sort -t , -k index1 file1 > sorted1 sort -t , -k index2 file2 > sorted2 join -t , -1 index1 -2 index2 -a 1 -a 2 sorted1 sorted2 ```
Combining 2 .csv files by common column
826,812
8
2009-05-05T20:36:44Z
826,848
8
2009-05-05T20:46:06Z
[ "python", "shell", "join", "csv", "debian" ]
So I have two .csv files where the first line in file 1 is: ``` MPID,Title,Description,Model,Category ID,Category Description,Subcategory ID,Subcategory Description,Manufacturer ID,Manufacturer Description,URL,Manufacturer (Brand) URL,Image URL,AR Price,Price,Ship Price,Stock,Condition ``` The first line from file 2:...
This is the classical "relational join" problem. You have several algorithms. * Nested Loops. You read from one file to pick a "master" record. You read the entire other file locating all "detail" records that match the master. This is a bad idea. * Sort-Merge. You sort each file into a temporary copy based on the co...
Is there a way to list all the available drive letters in python?
827,371
25
2009-05-05T23:23:47Z
827,397
40
2009-05-05T23:32:57Z
[ "python", "windows" ]
More or less what it says on the tin: is there an (easy) way in Python to list all the currently in-use drive letters in a windows system? (My google-fu seems to have let me down on this one.) Related: * [Enumerating all available drive letters in Windows](http://stackoverflow.com/questions/286534/enumerating-all-av...
``` import win32api drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] print drives ``` Adapted from: <http://www.faqts.com/knowledge_base/view.phtml/aid/4670>
Is there a way to list all the available drive letters in python?
827,371
25
2009-05-05T23:23:47Z
827,398
43
2009-05-05T23:33:19Z
[ "python", "windows" ]
More or less what it says on the tin: is there an (easy) way in Python to list all the currently in-use drive letters in a windows system? (My google-fu seems to have let me down on this one.) Related: * [Enumerating all available drive letters in Windows](http://stackoverflow.com/questions/286534/enumerating-all-av...
Without using any external libraries, if that matters to you: ``` import string from ctypes import windll def get_drives(): drives = [] bitmask = windll.kernel32.GetLogicalDrives() for letter in string.uppercase: if bitmask & 1: drives.append(letter) bitmask >>= 1 return d...
Is there a way to list all the available drive letters in python?
827,371
25
2009-05-05T23:23:47Z
827,490
8
2009-05-06T00:10:02Z
[ "python", "windows" ]
More or less what it says on the tin: is there an (easy) way in Python to list all the currently in-use drive letters in a windows system? (My google-fu seems to have let me down on this one.) Related: * [Enumerating all available drive letters in Windows](http://stackoverflow.com/questions/286534/enumerating-all-av...
The [Microsoft Script Repository](http://www.microsoft.com/technet/scriptcenter/scripts/python/default.mspx?mfr=true) includes [this recipe](http://www.microsoft.com/technet/scriptcenter/scripts/python/storage/disks/drives/stdvpy05.mspx) which might help. I don't have a windows machine to test it, though, so I'm not su...
Should my python web app use unicode for all strings?
827,415
6
2009-05-05T23:39:38Z
827,429
10
2009-05-05T23:43:40Z
[ "python", "django", "web-applications", "unicode", "pylons" ]
I see some frameworks like Django using unicode all over the place so it seems like it might be a good idea. On the other hand, it seems like a big pain to have all these extra 'u's floating around everywhere. What will be a problem if I don't do this? Are there any issues that will come up if I do do this? I'm usi...
In Python 3, all strings are Unicode. So, you can prepare for this by using `u''` strings everywhere you need to, and then when you eventually upgrade to Python 3 using the `2to3` tool all the `u`s will disappear. And you'll be in a better position because you will have already tested your code with Unicode strings. S...
Should my python web app use unicode for all strings?
827,415
6
2009-05-05T23:39:38Z
827,461
19
2009-05-05T23:55:49Z
[ "python", "django", "web-applications", "unicode", "pylons" ]
I see some frameworks like Django using unicode all over the place so it seems like it might be a good idea. On the other hand, it seems like a big pain to have all these extra 'u's floating around everywhere. What will be a problem if I don't do this? Are there any issues that will come up if I do do this? I'm usi...
You can avoid the `u''` in python 2.6 by doing: ``` from __future__ import unicode_literals ``` That will make `'string literals'` to be unicode objects, just like it is in python 3;
How do you validate a URL with a regular expression in Python?
827,557
73
2009-05-06T00:40:30Z
827,621
125
2009-05-06T01:09:19Z
[ "python", "regex", "google-app-engine" ]
I'm building an app on Google App Engine. I'm incredibly new to Python and have been beating my head against the following problem for the past 3 days. I have a class to represent an RSS Feed and in this class I have a method called setUrl. Input to this method is a URL. I'm trying to use the re python module to vali...
An easy way to parse (and validate) URL's is the `urlparse` ([py2](https://docs.python.org/2/library/urlparse.html), [py3](https://docs.python.org/3.0/library/urllib.parse.html)) module. A regex is too much work. --- There's no "validate" method because almost anything is a valid URL. There are some punctuation rule...
How do you validate a URL with a regular expression in Python?
827,557
73
2009-05-06T00:40:30Z
827,639
17
2009-05-06T01:18:04Z
[ "python", "regex", "google-app-engine" ]
I'm building an app on Google App Engine. I'm incredibly new to Python and have been beating my head against the following problem for the past 3 days. I have a class to represent an RSS Feed and in this class I have a method called setUrl. Input to this method is a URL. I'm trying to use the re python module to vali...
I admit, I find your regular expression totally incomprehensible. I wonder if you could use urlparse instead? Something like: ``` pieces = urlparse.urlparse(url) assert all([pieces.scheme, pieces.netloc]) assert set(pieces.netloc) <= set(string.letters + string.digits + '-.') # and others? assert pieces.scheme in ['h...
How do you validate a URL with a regular expression in Python?
827,557
73
2009-05-06T00:40:30Z
835,527
199
2009-05-07T15:59:04Z
[ "python", "regex", "google-app-engine" ]
I'm building an app on Google App Engine. I'm incredibly new to Python and have been beating my head against the following problem for the past 3 days. I have a class to represent an RSS Feed and in this class I have a method called setUrl. Input to this method is a URL. I'm trying to use the re python module to vali...
Here's the complete regexp to parse a URL. ``` (?:http://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\. )*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+) ){3}))(?::(?:\d+))?)(?:/(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F \d]{2}))|[;:@&=])*)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%...
How do you validate a URL with a regular expression in Python?
827,557
73
2009-05-06T00:40:30Z
7,995,979
13
2011-11-03T13:49:07Z
[ "python", "regex", "google-app-engine" ]
I'm building an app on Google App Engine. I'm incredibly new to Python and have been beating my head against the following problem for the past 3 days. I have a class to represent an RSS Feed and in this class I have a method called setUrl. Input to this method is a URL. I'm trying to use the re python module to vali...
I'm using the one used by Django and it seems pretty well: ``` def is_valid_url(url): import re regex = re.compile( r'^https?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\...
How do I constrain the SCons Command builder to run only if its dependencies have changed?
828,075
4
2009-05-06T04:53:18Z
2,512,948
11
2010-03-25T03:43:09Z
[ "python", "scons" ]
I am using the Command builder in scons to specify that a particular script needs to be invoked to produce a particular file. I would like to only run the script if it has been modified since the file was previously generated. The default behaviour of the Command builder seems to be to always run the script. How can I...
First, it looks like `code/speed.py` has no control on the output filename... Hardcoded output filenames are usually considered bad practice in scons (see yacc tool). It would read better like this: ``` speed = Command('speed_analysis.tex', [], 'python code/speed.py -o $TARGET') ``` Now, the PDF target produces a `re...
file handling in python
828,214
2
2009-05-06T05:55:17Z
828,234
17
2009-05-06T06:05:40Z
[ "python" ]
Thanks in advance. I have written a program which works for small files. But that doesn't work for files of 1 GB. Please tell me is there is any way to handle big file. Here is the code. ``` fh=open('reg.fa','r') c=fh.readlines() fh.close() s='' for i in range(0,(len(c))): s=s+c[i] lines=s.split('\n') ...
The `readlines` method reads in the **entire** file. You don't want to do that for a file that is large in relation to your physical memory size. The fix is to read the file in small chunks, and process those individually. You can, for example, do something like this: ``` for line in f.xreadlines(): ... do someth...
file handling in python
828,214
2
2009-05-06T05:55:17Z
828,652
7
2009-05-06T08:41:32Z
[ "python" ]
Thanks in advance. I have written a program which works for small files. But that doesn't work for files of 1 GB. Please tell me is there is any way to handle big file. Here is the code. ``` fh=open('reg.fa','r') c=fh.readlines() fh.close() s='' for i in range(0,(len(c))): s=s+c[i] lines=s.split('\n') ...
The script is not working because it reads all lines of the file in advance, making it nescessary to keep the whole file in memory. The easiest way to iterate over all lines in a file is ``` for line in open("test.txt", "r"): # do something with the "line" ```
Is Python2.6 stable enough for production use?
828,862
7
2009-05-06T09:44:28Z
828,881
18
2009-05-06T09:51:02Z
[ "python" ]
Or should I just stick with Python2.5 for a bit longer?
From [python.org](http://python.org/download/): > The current production versions are > Python 2.6.2 and Python 3.0.1. So, yes. Python 3.x contains some backwards incompatible changes, so [python.org](http://python.org/download/) also says: > start with Python 2.6 since more > existing third party software is > com...
Is Python2.6 stable enough for production use?
828,862
7
2009-05-06T09:44:28Z
828,894
10
2009-05-06T09:55:39Z
[ "python" ]
Or should I just stick with Python2.5 for a bit longer?
Ubuntu has switched to 2.6 in it's latest release, and has not had any significant problems. So I would say "yes, it's stable".
str.format() -> how to left-justify
829,667
7
2009-05-06T13:49:46Z
829,687
15
2009-05-06T13:53:29Z
[ "python" ]
``` >>> print 'there are {0:10} students and {1:10} teachers'.format(scnt, tcnt) there are 100 students and 20 teachers ``` What would be the code so that the output became: ``` there are 100 students and 20 teachers ``` Thanks.
``` print 'there are {0:<10} students and {1:<10} teachers'.format(scnt, tcnt) ``` While the old `%` operator uses `-` for alignment, the new `format` method uses `<` and `>`
Python convert args to kwargs
830,937
8
2009-05-06T18:14:35Z
831,164
12
2009-05-06T19:00:32Z
[ "python", "decorator" ]
I am writing a decorator that needs to call other functions prior to call of the function that it is decorating. The decorated function may have positional arguments, but the functions the decorator will call can only accept keyword arguments. Does anyone have a handy way of converting positional arguments into keyword...
Any arg that was passed positionally will be passed to \*args. And any arg passed as a keyword will be passed to \*\*kwargs. If you have positional args values and names then you can do: ``` kwargs.update(dict(zip(myfunc.func_code.co_varnames, args))) ``` to convert them all into keyword args.
Using Beautiful Soup, how do I iterate over all embedded text?
830,997
4
2009-05-06T18:26:52Z
831,544
7
2009-05-06T20:18:58Z
[ "python", "beautifulsoup" ]
Let's say I wanted to remove vowels from HTML: ``` <a href="foo">Hello there!</a>Hi! ``` becomes ``` <a href="foo">Hll thr!</a>H! ``` I figure this is a job for Beautiful Soup. How can I select the text in between tags and operate on it like this?
Suppose the variable `test_html` has the following html content: ``` <html> <head><title>Test title</title></head> <body> <p>Some paragraph</p> Useless Text <a href="http://stackoverflow.com">Some link</a>not a link <a href="http://python.org">Another link</a> </body></html> ``` Just do this: ``` from BeautifulSoup ...
Python: Finding all packages inside a package
832,004
6
2009-05-06T22:00:39Z
832,040
9
2009-05-06T22:11:51Z
[ "python", "import", "packages" ]
Given a package, how can I automatically find all its sub-packages?
You can't rely on introspection of loaded modules, because sub-packages may not have been loaded. You'll have to look at the filesystem, assuming the top level package in question is not an egg, zip file, extension module, or loaded from memory. ``` def get_subpackages(module): dir = os.path.dirname(module.__file_...
What tools do web developers use with PHP, Ruby on Rails, Python, etc?
832,017
9
2009-05-06T22:04:34Z
832,028
10
2009-05-06T22:08:24Z
[ "php", "python", "ruby" ]
A good friend just sent me the following email > My father is putting together a proposal for a local college to start a center of innovation and technology. As part of that, he’s proposing they teach web design and web development. My question is in your opinion what are the “industry standard” tools for both w...
* svn or a modern dvcs (git, mercurial or bazaar) * Generally not an IDE. Instead, TextMate on Mac, Notepad++ on Windows, or the one true editor (emacs or vim) on Linux. * MySQL and SQL in general is worth understanding as a separate item.
Launch a webpage on a Firefox (win) tab using Python
832,331
13
2009-05-06T23:52:20Z
832,338
38
2009-05-06T23:55:52Z
[ "python", "windows", "command-line" ]
I'm trying to launch a website url in a new tab using python in that way, but it didn't worked in these both ways: Method 1: ``` os.system('C:\Program Files\Mozilla Firefox\Firefox.exe -new-tab http://www.google.com/'); ``` and Method 2: ``` os.startfile('C:\Program Files\Mozilla Firefox\Firefox.exe -new-tab http:/...
You need to use the [`webbrowser`](http://docs.python.org/library/webbrowser.html) module ``` import webbrowser webbrowser.open('http://www.google.com') ``` [**edit**] If you want to open a url in a non-default browser try: ``` webbrowser.get('firefox').open_new_tab('http://www.google.com') ```
What is the best way to programmatically log into a web site in order to screen scrape? (Preferably in Python)
832,673
2
2009-05-07T02:45:59Z
832,697
8
2009-05-07T02:58:54Z
[ "python", "screen-scraping" ]
I want to be able to log into a website programmatically and periodically obtain some information from the site. What is the best tool(s) that would make this as simple as possible? I'd prefer a Python library of some type because I want to become more proficient in Python, but I'm open to any suggestions.
You can try Mechanize (<http://wwwsearch.sourceforge.net/mechanize/>) for programmatic web-browsing, and definitely use Beautiful Soup (<http://www.crummy.com/software/BeautifulSoup/>) for the scraping.
I need a sample of python unit testing sqlalchemy model with nose
833,626
22
2009-05-07T09:12:34Z
833,915
35
2009-05-07T10:35:31Z
[ "python", "unit-testing", "testing", "sqlalchemy", "nose" ]
Can someone show me how to write unit tests for sqlalchemy model I created using nose. I just need one simple example. Thanks.
You can simply create an in-memory SQLite database and bind your session to that. Example: ``` from db import session # probably a contextbound sessionmaker from db import model from sqlalchemy import create_engine def setup(): engine = create_engine('sqlite:///:memory:') session.configure(bind=engine) ...
Returning http status codes in Python CGI
833,715
15
2009-05-07T09:33:26Z
833,728
20
2009-05-07T09:35:43Z
[ "python", "http", "cgi" ]
Is it possible to send a status code other than 200 via a python cgi script (such as 301 redirect)
via cgi script? ``` print "Status:301\nLocation: http://www.google.com" ```
How to install python-igraph on Ubuntu 8.04 LTS 64-Bit?
834,076
4
2009-05-07T11:13:10Z
836,948
11
2009-05-07T20:48:20Z
[ "python", "64bit", "ubuntu-8.04", "igraph" ]
Apparently `libigraph` and `python-igraph` are the only packages on earth that can't be installed via `apt-get` or `easy_install` under Ubuntu 8.04 LTS 64-bit. Installing both from source from source on seems to go smoothly...until I try to use them. When I run python I get: ``` >>> import igraph Traceback (most rec...
How did you compile? Did you do a make install (if there was any). As for the 'library not found' error in the easy\_install version, i'd try the following: 1. '`sudo updatedb`' (to update the locate database) 2. '`locate libigraph.so.0`' (to find where this file is on your system. If you did a make install it could ...
Python dictionary: are keys() and values() always the same order?
835,092
132
2009-05-07T14:46:13Z
835,111
59
2009-05-07T14:49:34Z
[ "python" ]
It looks like the lists returned by `keys()` and `values()` methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods). For example: ``` >>> d = {'one':1, 'two': 2, 'three': 3} >>> k, v = d.keys(), d.values() >>> for i in range(len(k)): print d[k[i]]...
Yes, what you observed is indeed a guaranteed property -- keys(), values() and items() return lists in congruent order if the dict is not altered. iterkeys() &c also iterate in the same order as the corresponding lists.
Python dictionary: are keys() and values() always the same order?
835,092
132
2009-05-07T14:46:13Z
835,295
35
2009-05-07T15:20:08Z
[ "python" ]
It looks like the lists returned by `keys()` and `values()` methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods). For example: ``` >>> d = {'one':1, 'two': 2, 'three': 3} >>> k, v = d.keys(), d.values() >>> for i in range(len(k)): print d[k[i]]...
Yes it is [guaranteed in python 2.x](https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects): > If keys, values and items views are iterated over with no intervening > modifications to the dictionary, the order of items will directly > correspond.
Python dictionary: are keys() and values() always the same order?
835,092
132
2009-05-07T14:46:13Z
835,430
143
2009-05-07T15:45:47Z
[ "python" ]
It looks like the lists returned by `keys()` and `values()` methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods). For example: ``` >>> d = {'one':1, 'two': 2, 'three': 3} >>> k, v = d.keys(), d.values() >>> for i in range(len(k)): print d[k[i]]...
Found this: > If `items()`, `keys()`, `values()`, > `iteritems()`, `iterkeys()`, and > `itervalues()` are called with no > intervening modifications to the > dictionary, the lists will directly > correspond. On [2.x documentation](http://docs.python.org/library/stdtypes.html#dict.items) and [3.x documentation](https:...
Extending Python's builtin Str
835,469
14
2009-05-07T15:50:29Z
836,963
7
2009-05-07T20:51:12Z
[ "python", "oop", "inheritance", "override", "immutability" ]
I'm trying to subclass `str`, but having some difficulties due to its immutability. ``` class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): #overridden, new functionality. Return ob of type DerivedClass. Grea...
Good use for a class decorator -- roughly (untested code): ``` @do_overrides class Myst(str): def upper(self): ...&c... ``` and ``` def do_overrides(cls): done = set(dir(cls)) base = cls.__bases__[0] def wrap(f): def wrapper(*a, **k): r = f(*a, **k) if isinstance(r, base): r = cls...
How can I tell if a python variable is a string or a list?
836,387
51
2009-05-07T18:53:26Z
836,402
31
2009-05-07T18:57:40Z
[ "python", "list", "duck-typing" ]
I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example: ``` def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated li...
``` isinstance(your_var, basestring) ```
How can I tell if a python variable is a string or a list?
836,387
51
2009-05-07T18:53:26Z
836,406
30
2009-05-07T18:58:29Z
[ "python", "list", "duck-typing" ]
I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example: ``` def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated li...
Well, there's nothing unpythonic about checking type. Having said that, if you're willing to put a small burden on the caller: ``` def func( *files ): for f in files: doSomethingWithFile( f ) func( *['file1','file2','file3'] ) #Is treated like func('file1','file2','file3') func( 'file1' ) ``` I'd argue ...
How can I tell if a python variable is a string or a list?
836,387
51
2009-05-07T18:53:26Z
836,407
30
2009-05-07T18:58:58Z
[ "python", "list", "duck-typing" ]
I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example: ``` def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated li...
Personally, I don't really like this sort of behavior -- it interferes with duck typing. One could argue that it doesn't obey the "Explicit is better than implicit" mantra. Why not use the varargs syntax: ``` def func( *files ): for f in files: doSomethingWithFile( f ) func( 'file1', 'file2', 'file3' ) fu...
How can I tell if a python variable is a string or a list?
836,387
51
2009-05-07T18:53:26Z
836,535
14
2009-05-07T19:24:29Z
[ "python", "list", "duck-typing" ]
I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example: ``` def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated li...
I would say the most Python'y way is to make the user always pass a list, even if there is only one item in it. It makes it really obvious `func()` can take a list of files ``` def func(files): for cur_file in files: blah(cur_file) func(['file1']) ``` As Dave suggested, you could use the `func(*files)` s...
How can I tell if a python variable is a string or a list?
836,387
51
2009-05-07T18:53:26Z
837,588
10
2009-05-07T23:42:28Z
[ "python", "list", "duck-typing" ]
I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example: ``` def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated li...
``` if hasattr(f, 'lower'): print "I'm string like" ```
How can I tell if a python variable is a string or a list?
836,387
51
2009-05-07T18:53:26Z
837,986
9
2009-05-08T02:25:58Z
[ "python", "list", "duck-typing" ]
I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example: ``` def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated li...
``` def func(files): for f in files if not isinstance(files, basestring) else [files]: doSomethingWithFile(f) func(['file1', 'file2', 'file3']) func('file1') ```
Find the oldest file (recursively) in a directory
837,606
8
2009-05-07T23:50:50Z
837,629
12
2009-05-08T00:00:52Z
[ "python", "linux", "file-io" ]
I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to \*.avi files only. The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better? At the moment I...
To do it in Python, you can use [`os.walk(path)`](http://docs.python.org/library/os.html) to iterate recursively over the files, and the `st_size` and `st_mtime` attributes of [`os.stat(filename)`](http://docs.python.org/library/os.html) to get the file sizes and modification times.
Find the oldest file (recursively) in a directory
837,606
8
2009-05-07T23:50:50Z
837,631
10
2009-05-08T00:01:00Z
[ "python", "linux", "file-io" ]
I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to \*.avi files only. The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better? At the moment I...
You can use [stat](http://docs.python.org/library/stat.html#module-stat) and [fnmatch](http://docs.python.org/library/fnmatch.html#module-fnmatch) modules together to find the files ST\_MTIME refere to the last modification time. You can choose another value if you want ``` import os, stat, fnmatch file_list = [] for...
Find the oldest file (recursively) in a directory
837,606
8
2009-05-07T23:50:50Z
837,641
7
2009-05-08T00:04:04Z
[ "python", "linux", "file-io" ]
I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to \*.avi files only. The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better? At the moment I...
I think the easiest way to do this would be to use find along with ls -t (sort files by time). something along these lines should do the trick (deletes oldest avi file under specified directory) ``` find / -name "*.avi" | xargs ls -t | tail -n 1 | xargs rm ``` step by step.... **find / -name "\*.avi"** - find all a...
Find the oldest file (recursively) in a directory
837,606
8
2009-05-07T23:50:50Z
837,840
19
2009-05-08T01:24:55Z
[ "python", "linux", "file-io" ]
I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to \*.avi files only. The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better? At the moment I...
Hm. Nadia's answer is closer to what you *meant* to ask; however, for finding the (single) oldest file in a tree, try this: ``` import os def oldest_file_in_tree(rootfolder, extension=".avi"): return min( (os.path.join(dirname, filename) for dirname, dirnames, filenames in os.walk(rootfolder) ...
How do I create a slug in Django?
837,828
156
2009-05-08T01:17:11Z
837,835
314
2009-05-08T01:22:34Z
[ "python", "django", "slug" ]
I am trying to create a SlugField in Django. I created this simple model: ``` from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() ``` I then do this: ``` >>> from mysite.books.models import Test >>> t=Test(q="aa a a a", s="b b b b") >>> t.s 'b b...
You will need to use the slugify function. ``` >>> from django.template.defaultfilters import slugify >>> slugify("b b b b") u'b-b-b-b' >>> ``` You can call `slugify` automatically by overriding the `save` method: ``` class test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() d...
How do I create a slug in Django?
837,828
156
2009-05-08T01:17:11Z
842,865
26
2009-05-09T07:26:29Z
[ "python", "django", "slug" ]
I am trying to create a SlugField in Django. I created this simple model: ``` from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() ``` I then do this: ``` >>> from mysite.books.models import Test >>> t=Test(q="aa a a a", s="b b b b") >>> t.s 'b b...
If you're using the admin interface to add new items of your model, you can set up a `ModelAdmin` in your `admin.py` and utilize [`prepopulated_fields`](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields) to automate entering of a slug: ``` class ClientAdmin(ad...
How do I create a slug in Django?
837,828
156
2009-05-08T01:17:11Z
843,067
20
2009-05-09T10:10:12Z
[ "python", "django", "slug" ]
I am trying to create a SlugField in Django. I created this simple model: ``` from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() ``` I then do this: ``` >>> from mysite.books.models import Test >>> t=Test(q="aa a a a", s="b b b b") >>> t.s 'b b...
In most cases the slug should not change, so you really only want to calculate it on first save: ``` class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField(editable=False) # hide from admin def save(self): if not self.id: self.s = slugify(self.q) su...
How do I create a slug in Django?
837,828
156
2009-05-08T01:17:11Z
1,480,440
49
2009-09-26T04:36:35Z
[ "python", "django", "slug" ]
I am trying to create a SlugField in Django. I created this simple model: ``` from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() ``` I then do this: ``` >>> from mysite.books.models import Test >>> t=Test(q="aa a a a", s="b b b b") >>> t.s 'b b...
A small correction to Thepeer's answer: To override `save()` function in model classes, better add arguments to it: ``` from django.utils.text import slugify def save(self, *args, **kwargs): if not self.id: self.s = slugify(self.q) super(test, self).save(*args, **kwargs) ``` Otherwise, `test.objects...
How do I create a slug in Django?
837,828
156
2009-05-08T01:17:11Z
12,212,162
87
2012-08-31T09:05:21Z
[ "python", "django", "slug" ]
I am trying to create a SlugField in Django. I created this simple model: ``` from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() ``` I then do this: ``` >>> from mysite.books.models import Test >>> t=Test(q="aa a a a", s="b b b b") >>> t.s 'b b...
There is corner case with some utf-8 characters Example: ``` >>> from django.template.defaultfilters import slugify >>> slugify(u"test ąęśćółń") u'test-aescon' # there is no "l" ``` This can be solved with [Unidecode](http://pypi.python.org/pypi/Unidecode/0.04.9) ``` >>> from unidecode import unidecode >>> f...
Working with subdomain in google app engine
838,078
19
2009-05-08T03:15:08Z
838,726
26
2009-05-08T08:05:53Z
[ "python", "google-app-engine", "subdomain" ]
How can I work with sub domain in google app engine (python). I wanna get first domain part and take some action (handler). **Example:**      product.example.com -> send it to products handler      user.example.com -> send it to users handler Actually, using virtual path I have this code: ``` application = we...
WSGIApplication isn't capable of routing based on domain. Instead, you need to create a separate application for each subdomain, like this: ``` applications = { 'product.example.com': webapp.WSGIApplication([ ('/', IndexHandler), ('/(.*)', ProductHandler)]), 'user.example.com': webapp.WSGIApplication([ ...
Python dictionary deepcopy
838,642
19
2009-05-08T07:38:49Z
838,673
14
2009-05-08T07:49:17Z
[ "python", "dictionary", "deep-copy" ]
I was wondering in how does exactly deepcopy work in the following context: ``` from copy import deepcopy def copyExample: self.myDict = {} firstPosition = "First" firstPositionContent = ["first", "primero"] secondPosition = "Second" secondPositionContent = ["second"] self.myDict[firstPosition...
The [documentation](http://docs.python.org/library/copy.html) makes it pretty clear that you're getting new copies, not references. Deepcopy creates deep copies for built in types, with various exceptions and that you can add custom copy operations to your user-defined objects to get deep copy support for them as well....
cursor.rowcount always -1 in sqlite3 in python3k
839,069
12
2009-05-08T09:49:27Z
839,419
11
2009-05-08T11:33:06Z
[ "python", "database", "sqlite" ]
I am trying to get the `rowcount` of a `sqlite3` `cursor` in my Python3k program, but I am puzzled, as the `rowcount` is always `-1`, despite what Python3 docs say (actually it is contradictory, it should be `None`). Even after fetching all the rows, `rowcount` stays at `-1`. Is it a `sqlite3` bug? I have already check...
From the [documentation](http://docs.python.org/3.0/library/sqlite3.html#sqlite3.Cursor.rowcount): > As required by the Python DB API Spec, > the rowcount attribute “is -1 in case > no executeXX() has been performed on > the cursor or the rowcount of the last > operation is not determinable by the > interface”. > ...
cursor.rowcount always -1 in sqlite3 in python3k
839,069
12
2009-05-08T09:49:27Z
845,555
7
2009-05-10T15:50:09Z
[ "python", "database", "sqlite" ]
I am trying to get the `rowcount` of a `sqlite3` `cursor` in my Python3k program, but I am puzzled, as the `rowcount` is always `-1`, despite what Python3 docs say (actually it is contradictory, it should be `None`). Even after fetching all the rows, `rowcount` stays at `-1`. Is it a `sqlite3` bug? I have already check...
Instead of "checking if a fetchone() returns something different than None", I suggest: ``` cursor.execute('SELECT * FROM foobar') for row in cursor: ... ``` this is `sqlite`-only (not supported in other DB API implementations) but very handy for `sqlite`-specific Python code (*and* fully documented, see <http://d...