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 to refer to a method name from with a method in Python?
2,222,044
8
2010-02-08T14:05:28Z
2,222,132
11
2010-02-08T14:20:04Z
[ "python", "methods", "introspection" ]
Say I have the following class defined with the method `foo`: ``` class MyClass: def foo(self): print "My name is %s" % __name__ ``` Now when I call `foo()` I expect/want to see this printed out ``` My name is foo ``` However I get ``` My name is __main__ ``` And if I was to put the class definition i...
This does what you're after: ``` from inspect import currentframe, getframeinfo class MyClass: def foo(self): print "My name is %s" % getframeinfo(currentframe())[2] ```
Python: defining functions on the fly
2,222,466
4
2010-02-08T15:06:26Z
2,222,530
13
2010-02-08T15:17:28Z
[ "python", "lambda" ]
I have the following code: ``` funcs = [] for i in range(10): def func(): print i funcs.append(func) for f in funcs: f() ``` The problem is that `func` is being overriden. Ie the output of the code is: ``` 9 9 9 ... ``` How would you solve this *without* defining new functions? The optimal solut...
The problem is not that func is being overwritten, it's that the value of `i` is being evaluated when the function is called, not when it is defined. If you want to evaluate `i` at definition time, put it in the function declaration, as a default argument to `func`. ``` funcs = [] for i in range(10): def func(valu...
Python: making your own statements
2,222,843
2
2010-02-08T15:58:51Z
2,222,867
7
2010-02-08T16:01:37Z
[ "python" ]
Is there a way to define new statements like `def`, `with`, `for`,.. of my own in python. Of course, I don't mean to override the existing statements.. Only create some of my own. If so, how do I do it? Can you point me to good docs on the subject?
No, you cannot add new syntax within a Python program. The only way to alter the language is to edit and recompile the grammar file and supporting C code, to obtain a new altered interpreter, compiler and runtime.
Python dictionary instead of switch/case
2,222,859
2
2010-02-08T16:00:31Z
2,222,958
10
2010-02-08T16:11:31Z
[ "python", "dictionary", "switch-statement" ]
I've recently learned that python doesn't have the switch/case statement. I've been reading about using dictionaries in its stead, like this for example: ``` values = { value1: do_some_stuff1, value2: do_some_stuff2, valueN: do_some_stuffN, } values.get(var, do_default_stuff)() ``` What I can't figu...
A dictionary is the wrong structure for this. The [`bisect` examples](http://docs.python.org/library/bisect.html#examples) show an example of this sort of range test.
How to execute a function asynchronously every 60 seconds in Python?
2,223,157
32
2010-02-08T16:40:18Z
2,223,182
54
2010-02-08T16:43:17Z
[ "python", "function", "asynchronous", "call" ]
I want to execute a function every 60 seconds on Python but I don't want to be blocked meanwhile. How can I do it asynchronously? ``` import threading import time def f(): print("hello world") threading.Timer(3, f).start() if __name__ == '__main__': f() time.sleep(20) ``` With this code, the fu...
You could try the threading.Timer class: <http://docs.python.org/library/threading.html#timer-objects>. ``` import threading def f(): # do something here ... # call f() again in 60 seconds threading.Timer(60, f).start() # start calling f now and every 60 sec thereafter f() ```
A class subclass of itself. Why mutual subclassing is forbidden?
2,223,300
4
2010-02-08T16:57:22Z
2,223,343
9
2010-02-08T17:03:21Z
[ "python", "class", "design", "owl" ]
Complex question I assume, but studying OWL opened a new perspective to live, the universe and everything. I'm going philosophical here. I am trying to achieve a class C which is subclass of B which in turn is subclass of C. Just for fun, you know... So here it is ``` >>> class A(object): pass ... >>> class B(A): p...
Python doesn't allow it because there is no sensible way to do it. You could invent arbitrary rules about how to handle such a case (and perhaps some languages do), but since there is no actual gain in doing so, Python refuses to guess. Classes are required to have a stable, predictable method resolution order for a nu...
Multiple ModelAdmins/views for same model in Django admin
2,223,375
94
2010-02-08T17:07:35Z
2,228,821
171
2010-02-09T11:59:57Z
[ "python", "django", "django-admin" ]
How can I create more than one ModelAdmin for the same model, each customised differently and linked to different URLs? Let's say I have a Django model called Posts. By default, the admin view of this model will list all Post objects. I know I can customise the list of objects displayed on the page in various ways by...
I've found one way to achieve what I want, by using proxy models to get around the fact that each model may be registered only once. ``` class PostAdmin(admin.ModelAdmin): list_display = ('title', 'pubdate','user') class MyPosts(Post): class Meta: proxy = True class MyPostAdmin(PostAdmin): def qu...
parsing table with BeautifulSoup and write in text file
2,224,602
6
2010-02-08T20:23:27Z
2,226,569
9
2010-02-09T03:32:52Z
[ "python", "beautifulsoup" ]
I need data from table in text file (output.txt) in this format: data1;data2;data3;data4;..... Celkova podlahova plocha bytu;33m;Vytah;Ano;Nadzemne podlazie;Prizemne podlazie;.....;Forma vlastnictva;Osobne All in "**one line**", separator is "**;**" (later export in csv-file). I´m beginner.. Help, thanks. ``` from...
You are not keeping each record as you read it in. Try this, which stores the records in `records`: ``` from BeautifulSoup import BeautifulSoup import urllib2 import codecs response = urllib2.urlopen('http://www.reality.sk/zakazka/0747-003578/predaj/1-izb-byt/kosice-mestska-cast-sever-sladkovicova-kosice-sever/art-re...
Business days in Python
2,224,742
28
2010-02-08T20:47:33Z
2,224,837
12
2010-02-08T20:59:38Z
[ "python", "datetime" ]
I need to subtract *business days* from the current date. I currently have some code which needs always to be running on the most recent business day. So that may be today if we're Monday thru Friday, but if it's Saturday or Sunday then I need to set it back to the Friday before the weekend. I currently have some pret...
There seem to be several options if you're open to installing extra libraries. This post describes a way of defining workdays with [dateutil](http://labix.org/python-dateutil). <http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-09/3758.html> BusinessHours lets you custom-define your list of holidays, ...
Business days in Python
2,224,742
28
2010-02-08T20:47:33Z
19,036,752
43
2013-09-26T19:16:36Z
[ "python", "datetime" ]
I need to subtract *business days* from the current date. I currently have some code which needs always to be running on the most recent business day. So that may be today if we're Monday thru Friday, but if it's Saturday or Sunday then I need to set it back to the Friday before the weekend. I currently have some pret...
Use pandas! ``` import pandas as pd # BDay is business day, not birthday... from pandas.tseries.offsets import BDay # pd.datetime is an alias for datetime.datetime today = pd.datetime.today() print today - BDay(4) ``` Since today is Thursday, Sept 26, that will give you an output of: ``` datetime.datetime(2013, 9, ...
Determine the type of a Python object
2,225,038
839
2010-02-08T21:37:20Z
2,225,055
105
2010-02-08T21:39:17Z
[ "python" ]
Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell the difference.
You can do that using `type()`: ``` >>> a = [] >>> type(a) <type 'list'> >>> f = () >>> type(f) <type 'tuple'> ```
Determine the type of a Python object
2,225,038
839
2010-02-08T21:37:20Z
2,225,066
1,012
2010-02-08T21:40:06Z
[ "python" ]
Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell the difference.
To get the type of an object, you can use the built-in [`type()`](http://docs.python.org/3/library/functions.html#type) function. Passing an object as the only parameter will return the type object of that object: ``` >>> type([]) is list True >>> type({}) is dict True >>> type('') is str True >>> type(0) is int True ...
Determine the type of a Python object
2,225,038
839
2010-02-08T21:37:20Z
2,225,081
31
2010-02-08T21:43:51Z
[ "python" ]
Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell the difference.
It might be more Pythonic to use a `try`...`except` block. That way, if you have a class which quacks like a list, or quacks like a dict, it will behave properly regardless of what its type *really* is. To clarify, the preferred method of "telling the difference" between variable types is with something called [duck t...
Determine the type of a Python object
2,225,038
839
2010-02-08T21:37:20Z
17,330,925
20
2013-06-26T21:38:42Z
[ "python" ]
Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell the difference.
On instances of object you also have the: ``` __class__ ``` attribute. Here is a sample taken from Python 3.3 console ``` >>> str = "str" >>> str.__class__ <class 'str'> >>> i = 2 >>> i.__class__ <class 'int'> >>> class Test(): ... pass ... >>> a = Test() >>> a.__class__ <class '__main__.Test'> ``` Beware that ...
Get a filtered list of files in a directory
2,225,564
117
2010-02-08T23:02:56Z
2,225,582
159
2010-02-08T23:05:18Z
[ "python", "filesystems", "wildcard", "glob", "directory-listing" ]
I am trying to get a list of files in a directory using Python, but I do not want a list of ALL the files. What I essentially want is the ability to do something like the following but using Python and not executing ls. ``` ls 145592*.jpg ``` If there is no built-in method for this, I am currently thinking of writin...
[`glob.glob('145592*.jpg')`](http://docs.python.org/library/glob.html#glob.glob)
Get a filtered list of files in a directory
2,225,564
117
2010-02-08T23:02:56Z
2,225,927
53
2010-02-09T00:27:32Z
[ "python", "filesystems", "wildcard", "glob", "directory-listing" ]
I am trying to get a list of files in a directory using Python, but I do not want a list of ALL the files. What I essentially want is the ability to do something like the following but using Python and not executing ls. ``` ls 145592*.jpg ``` If there is no built-in method for this, I am currently thinking of writin...
`glob.glob()` is definitely the way to do it (as per Ignacio). However, if you do need more complicated matching, you can do it with a list comprehension and `re.match()`, something like so: ``` files = [f for f in os.listdir('.') if re.match(r'[0-9]+.*\.jpg', f)] ``` More flexible, but as you note, less efficient.
Get a filtered list of files in a directory
2,225,564
117
2010-02-08T23:02:56Z
21,096,293
18
2014-01-13T16:27:48Z
[ "python", "filesystems", "wildcard", "glob", "directory-listing" ]
I am trying to get a list of files in a directory using Python, but I do not want a list of ALL the files. What I essentially want is the ability to do something like the following but using Python and not executing ls. ``` ls 145592*.jpg ``` If there is no built-in method for this, I am currently thinking of writin...
Keep it simple: ``` import os relevant_path = "[path to folder]" included_extenstions = ['jpg', 'bmp', 'png', 'gif'] file_names = [fn for fn in os.listdir(relevant_path) if any(fn.endswith(ext) for ext in included_extenstions)] ``` I prefer this form of list comprehensions because it reads well in Engli...
How can I create stacked line graph with matplotlib?
2,225,995
30
2010-02-09T00:51:38Z
2,226,261
7
2010-02-09T01:56:37Z
[ "python", "matplotlib" ]
I would like to be able to produce a stacked line graph (similar to the method used [here](http://www.whitehouse.gov/omb/budget/fy2003/images/bud20c.jpg)) with Python (preferably using matplotlib, but another library would be fine too). How can I do this? This similar to the [stacked bar graph example](http://matplotl...
A slightly less hackish way would be to use a line graph in the first place and `matplotlib.pyplot.fill_between`. To emulate the stacking you have to shift the points up yourself. ``` x = np.arange(0,4) y1 = np.array([1,2,4,3]) y2 = np.array([5,2,1,3]) # y2 should go on top, so shift them up y2s = y1+y2 plot(x,y1) pl...
How can I create stacked line graph with matplotlib?
2,225,995
30
2010-02-09T00:51:38Z
2,226,534
40
2010-02-09T03:20:09Z
[ "python", "matplotlib" ]
I would like to be able to produce a stacked line graph (similar to the method used [here](http://www.whitehouse.gov/omb/budget/fy2003/images/bud20c.jpg)) with Python (preferably using matplotlib, but another library would be fine too). How can I do this? This similar to the [stacked bar graph example](http://matplotl...
I believe ***Area Plot*** is a common term for this type of plot, and in the specific instance recited in the OP, ***Stacked Area Plot***. Matplotlib does not have an "out-of-the-box" function that combines *both* the data processing and drawing/rendering steps to create a this type of plot, but it's easy to roll your...
How can I create stacked line graph with matplotlib?
2,225,995
30
2010-02-09T00:51:38Z
21,418,313
35
2014-01-28T22:31:48Z
[ "python", "matplotlib" ]
I would like to be able to produce a stacked line graph (similar to the method used [here](http://www.whitehouse.gov/omb/budget/fy2003/images/bud20c.jpg)) with Python (preferably using matplotlib, but another library would be fine too). How can I do this? This similar to the [stacked bar graph example](http://matplotl...
Newer versions of matplotlib contain the function [`plt.stackplot`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.stackplot), which allow for several different "out-of-the-box" stacked area plots: ``` import numpy as np import pylab as plt X = np.arange(0, 10, 1) Y = X + 5 * np.random.random((5, X.size...
Interpreting WAV Data
2,226,853
6
2010-02-09T05:01:25Z
2,227,174
13
2010-02-09T06:18:05Z
[ "python", "audio", "pcm" ]
I'm trying to write a program to display PCM data. I've been very frustrated trying to find a library with the right level of abstraction, but I've found the python wave library and have been using that. However, I'm not sure how to interpret the data. The wave.getparams function returns (2 channels, 2 bytes, 44100 Hz...
Thank you for your help! I got it working and I'll post the solution here for everyone to use in case some other poor soul needs it: ``` import wave import struct def pcm_channels(wave_file): """Given a file-like object or file path representing a wave file, decompose it into its constituent PCM data streams....
Are Python built-in containers thread-safe?
2,227,169
30
2010-02-09T06:17:20Z
2,227,220
34
2010-02-09T06:29:50Z
[ "python", "thread-safety" ]
I would like to know if the Python built-in containers (list, vector, set...) are thread-safe? Or do I need to implement a locking/unlocking environment for my shared variable?
You need to implement your own locking for all shared variables that will be modified in Python. You don't have to worry about reading from the variables that won't be modified (ie, concurrent reads are ok), so immutable types (`frozenset`, `tuple`, `str`) are *probably* safe, but it wouldn't hurt. For things you're go...
Why does Pylint give error E0702, raising NoneType, on this raise statement?
2,228,790
7
2010-02-09T11:54:23Z
2,228,811
11
2010-02-09T11:57:47Z
[ "python", "exception", "pylint" ]
Say I have the following code. ``` def foo(): foobar = None if foobar is not None: raise foobar ``` When I run this code through pylint, I get the following error: ``` E0702:4:foo: Raising NoneType while only classes, instances or string are allowed ``` Is this a bug in pylint? Is my pylint too old?...
It's **[a known bug](http://www.logilab.org/ticket/3207)**. Pylint doesn't do a lot of flow-control inferencing.
Python MD5 not matching md5 in terminal
2,229,298
3
2010-02-09T13:22:54Z
2,229,309
21
2010-02-09T13:25:23Z
[ "python", "hash", "md5" ]
Hey guys, am getting MD5 of several files using python function ``` filehash = hashlib.md5(file) print "FILE HASH: " + filehash.hexdigest() ``` though when I go to the terminal and do a ``` md5 file ``` the result I'm getting is not the same my python script is outputting (they don't match). Any chance someone know...
hashlib.md5() takes the contents of the file not its name. See <http://docs.python.org/library/hashlib.html> You need to open the file, and read its contents before hashing it. ``` f = open(filename,'rb') m = hashlib.md5() while True: ## Don't read the entire file at once... data = f.read(10240) if len(d...
What algorithm does buildbot use to assign builders to slaves?
2,229,481
6
2010-02-09T13:50:11Z
2,323,336
9
2010-02-24T02:49:18Z
[ "python", "project-management", "build-process", "build-automation", "buildbot" ]
I have a buildbot with some builders and two slave machines. Some of the builders can run on one slave, and some of them can run on both machines. What algorithm will buildbot use to schedule the builds? Will it notice that some builders can run on just one slave and that it should assign those that can run on both s...
First it gets a list of all the slaves attached to that builder. Then it picks one *at random*. If the slave is already running more than `slave.max_builds` builds, it picks another. You can override the `nextSlave` method on the `Builder` to change the way slaves are chosen. The arguments passed to your function will...
Django urlsafe base64 decoding with decryption
2,229,827
14
2010-02-09T14:39:17Z
2,230,623
29
2010-02-09T16:23:04Z
[ "python", "django", "encryption", "encoding", "base64" ]
I'm writing my own captcha system for user registration. So I need to create a suitable URL for receiving generated captcha pictures. Generation looks like this: ``` _cipher = cipher.new(settings.CAPTCHA_SECRET_KEY, cipher.MODE_ECB) _encrypt_block = lambda block: _cipher.encrypt(block + ' ' * (_cipher.block_size - len...
The problem is that b64decode quite explicitly can only take bytes (a string), not unicode. ``` >>> import base64 >>> test = "Hi, I'm a string" >>> enc = base64.urlsafe_b64encode(test) >>> enc 'SGksIEknbSBhIHN0cmluZw==' >>> uenc = unicode(enc) >>> base64.urlsafe_b64decode(enc) "Hi, I'm a string" >>> base64.urlsafe_b64...
How to fetch an email body using imaplib in python?
2,230,037
10
2010-02-09T15:10:14Z
2,230,571
11
2010-02-09T16:16:54Z
[ "python", "imaplib" ]
I'd like to fetch the whole message from IMAP4 server. In python docs if found this bit of code that works: ``` >>> t, data = M.fetch('1', '(RFC822)') >>> body = data[0][1] ``` I'm wondering if I can always trust that data[0][1] returns the body of the message. When I've run 'RFC822.SIZE' I've got just a string inste...
No... `imaplib` is a pretty good library, it's imap that's so unintelligible. You may wish to check that `t == 'OK'`, but `data[0][1]` works as expected for as much as I've used it. Here's a quick example I use to extract signed certificates I've received by email, not bomb-proof, but suits my purposes: ``` import g...
How to fetch an email body using imaplib in python?
2,230,037
10
2010-02-09T15:10:14Z
2,231,047
7
2010-02-09T17:27:38Z
[ "python", "imaplib" ]
I'd like to fetch the whole message from IMAP4 server. In python docs if found this bit of code that works: ``` >>> t, data = M.fetch('1', '(RFC822)') >>> body = data[0][1] ``` I'm wondering if I can always trust that data[0][1] returns the body of the message. When I've run 'RFC822.SIZE' I've got just a string inste...
The [IMAPClient](http://pypi.python.org/pypi/IMAPClient/) package is a fair bit easier to work with. From the description: > Easy-to-use, Pythonic and complete > IMAP client library.
Python subprocess/Popen with a modified environment
2,231,227
128
2010-02-09T17:55:16Z
2,231,325
20
2010-02-09T18:09:53Z
[ "python", "subprocess", "popen" ]
I believe that running an external command with a slightly modified environment is a very common case. That's how I tend to do it: ``` import subprocess, os my_env = os.environ my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"] subprocess.Popen(my_command, env=my_env) ``` I've got a gut feeling that there's a bette...
you might use `my_env.get("PATH", '')` instead of `my_env["PATH"]` in case `PATH` somehow not defined in the original environment, but other than that it looks fine.
Python subprocess/Popen with a modified environment
2,231,227
128
2010-02-09T17:55:16Z
4,453,495
161
2010-12-15T18:28:23Z
[ "python", "subprocess", "popen" ]
I believe that running an external command with a slightly modified environment is a very common case. That's how I tend to do it: ``` import subprocess, os my_env = os.environ my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"] subprocess.Popen(my_command, env=my_env) ``` I've got a gut feeling that there's a bette...
I think `os.environ.copy()` is better if you don't intend to modify the os.environ for the current process: ``` import subprocess, os my_env = os.environ.copy() my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"] subprocess.Popen(my_command, env=my_env) ```
Python subprocess/Popen with a modified environment
2,231,227
128
2010-02-09T17:55:16Z
28,989,538
28
2015-03-11T14:38:32Z
[ "python", "subprocess", "popen" ]
I believe that running an external command with a slightly modified environment is a very common case. That's how I tend to do it: ``` import subprocess, os my_env = os.environ my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"] subprocess.Popen(my_command, env=my_env) ``` I've got a gut feeling that there's a bette...
That depends on what the issue is. If it's to clone and modify the environment one solution could be: ``` subprocess.Popen(my_command, env=dict(os.environ, PATH="path")) ``` But that somewhat depends on that the replaced variables are valid python identifiers, which they most often are (how often do you run into envi...
Error when calling the metaclass bases: function() argument 1 must be code, not str
2,231,427
30
2010-02-09T18:24:16Z
2,231,478
46
2010-02-09T18:31:36Z
[ "python", "class", "inheritance", "metaclass" ]
I tried to subclass threading.Condition earlier today but it didn't work out. Here is the output of the Python interpreter when I try to subclass the threading.Condition class: ``` >>> import threading >>> class ThisWontWork(threading.Condition): ... pass ... Traceback (most recent call last): File "<stdin>", l...
You're getting that exception because, despite its class-like name, `threading.Condition` is a function, and you cannot subclass functions. ``` >>> type(threading.Condition) <type 'function'> ``` This not-very-helpful error message has been [raised on the Python bugtracker](http://bugs.python.org/issue6829), but it h...
Error when calling the metaclass bases: function() argument 1 must be code, not str
2,231,427
30
2010-02-09T18:24:16Z
3,507,510
19
2010-08-17T22:32:50Z
[ "python", "class", "inheritance", "metaclass" ]
I tried to subclass threading.Condition earlier today but it didn't work out. Here is the output of the Python interpreter when I try to subclass the threading.Condition class: ``` >>> import threading >>> class ThisWontWork(threading.Condition): ... pass ... Traceback (most recent call last): File "<stdin>", l...
Different problem than OP had, but you can also get this error if you try to subclass from a module instead of a class (e.g. you try to inherit My.Module instead of My.Module.Class). Kudos to [this post](http://andre.stechert.org/urwhatu/2005/03/typeerror_error.html) for helping me figure this out. > TypeError: Error ...
Error when calling the metaclass bases: function() argument 1 must be code, not str
2,231,427
30
2010-02-09T18:24:16Z
17,067,556
12
2013-06-12T14:02:15Z
[ "python", "class", "inheritance", "metaclass" ]
I tried to subclass threading.Condition earlier today but it didn't work out. Here is the output of the Python interpreter when I try to subclass the threading.Condition class: ``` >>> import threading >>> class ThisWontWork(threading.Condition): ... pass ... Traceback (most recent call last): File "<stdin>", l...
With respect to subclassing a module, this is a really easy mistake to make if you have, for example, class Foo defined in a file Foo.py. When you create a subclass of Foo in a different file, you might accidentally do the following (this is an attempt to subclass a module and will result in an error): ``` import Foo ...
Numpy with python 3.0
2,231,842
21
2010-02-09T19:25:26Z
2,232,131
11
2010-02-09T19:59:17Z
[ "python", "numpy", "python-3.x" ]
NumPy installer can't find python path in the registry. > Cannot install Python version 2.6 required, which was not found in the > registry. Is there a numpy build which can be used with python 3.0?
there is not [yet] a version of numpy that has been ported to Python 3. the last update I heard from the people on the project was this: <http://blog.jarrodmillman.com/2009/01/when-will-numpy-and-scipy-migrate-to.html> for now, if you need Numpy, you are stuck with Python 2.x
Numpy with python 3.0
2,231,842
21
2010-02-09T19:25:26Z
2,269,785
46
2010-02-15T23:57:23Z
[ "python", "numpy", "python-3.x" ]
NumPy installer can't find python path in the registry. > Cannot install Python version 2.6 required, which was not found in the > registry. Is there a numpy build which can be used with python 3.0?
Guido van Rossum (creator of Python) says he is [keen to see NumPy work in Python 3.x](http://neopythonic.blogspot.com/2009/11/python-in-scientific-world.html), because it would enable many dependent libraries to move to 3.x. **Update 2010-08-05:** [NumPy version 1.5 supports Python 3.x, and SciPy will soon.](http://w...
Numpy with python 3.0
2,231,842
21
2010-02-09T19:25:26Z
2,737,113
7
2010-04-29T12:09:07Z
[ "python", "numpy", "python-3.x" ]
NumPy installer can't find python path in the registry. > Cannot install Python version 2.6 required, which was not found in the > registry. Is there a numpy build which can be used with python 3.0?
The current development verson of Numpy is compatible with Python 3 -- you can get it from Numpy's SVN and build it yourself. It will probably be released later this year (probably in the summer) as Numpy 2.0.
Numpy with python 3.0
2,231,842
21
2010-02-09T19:25:26Z
8,421,835
7
2011-12-07T20:08:59Z
[ "python", "numpy", "python-3.x" ]
NumPy installer can't find python path in the registry. > Cannot install Python version 2.6 required, which was not found in the > registry. Is there a numpy build which can be used with python 3.0?
Scipy now also supports Python 3 (<http://sourceforge.net/projects/scipy/files/scipy/0.10.0/>).
Correct way to emulate single precision floating point in python?
2,232,362
15
2010-02-09T20:37:10Z
2,232,382
17
2010-02-09T20:41:24Z
[ "python", "floating-point" ]
What's the best way to emulate single-precision floating point in python? (Or other floating point formats for that matter?) Just use ctypes?
[`numpy`](http://numpy.scipy.org/) has a [`float32`](http://docs.scipy.org/doc/numpy/user/basics.types.html?highlight=float32#array-types-and-conversions-between-types) type.
How to mount a network directory using python?
2,232,420
7
2010-02-09T20:47:49Z
5,185,074
8
2011-03-03T18:46:06Z
[ "python", "linux", "scripting", "mount" ]
I need to mount a directory "dir" on a network machine "data" using python on a linux machine I know that I can send the command via command line: ``` mkdir ~/mnt/data_dir mount -t data:/dir/ ~/mnt/data_dir ``` but how would I send those commands from a python script?
I'd recommend you use `subprocess.checkcall`. ``` from subprocess import * #most simply check_call( 'mkdir ~/mnt/data_dir', shell=True ) check_call( 'mount -t whatever data:/dir/ ~/mnt/data_dir', shell=True ) #more securely from os.path import expanduser check_call( [ 'mkdir', expanduser( '~/mnt/data_dir' ) ] ) che...
Python newbie having a problem using classes
2,232,740
6
2010-02-09T21:43:23Z
2,232,753
7
2010-02-09T21:44:55Z
[ "python", "class" ]
Im just beginning to mess around a bit with classes; however, I am running across a problem. ``` class MyClass(object): def f(self): return 'hello world' print MyClass.f ``` The previous script is returning `<unbound method MyClass.f>` instead of the intended value. How do I fix this?
Create an instance of your class: `m = MyClass()` then use `m.f()` to call the function Now you may wonder why you don't have to pass a parameter to the function (the 'self' param). It is because the instance on which you call the function is actually passed as the first parameter. That is, `MyClass.f(m)` equals `m....
Python newbie having a problem using classes
2,232,740
6
2010-02-09T21:43:23Z
2,232,772
14
2010-02-09T21:47:12Z
[ "python", "class" ]
Im just beginning to mess around a bit with classes; however, I am running across a problem. ``` class MyClass(object): def f(self): return 'hello world' print MyClass.f ``` The previous script is returning `<unbound method MyClass.f>` instead of the intended value. How do I fix this?
`MyClass.f` refers to the function object f which is a property of MyClass. In your case, f is an instance method (has a self parameter) so its called on a particular instance. Its "unbound" because you're referring to f without specifying a specific class, kind of like referring to a steering wheel without a car. You...
Does Python PIL resize maintain the aspect ratio?
2,232,742
2
2010-02-09T21:43:27Z
4,271,003
7
2010-11-24T20:04:17Z
[ "python", "resize", "python-imaging-library" ]
Does PIL resize to the exact dimensions I give it no matter what? Or will it try to keep the aspect ratio if I give it something like the `Image.ANTIALIAS` argument?
Yes it will keep aspect ratio using **thumbnail** method: ``` image = Image.open(source_path) image.thumbnail(size, Image.ANTIALIAS) image.save(dest_path, "JPEG") ```
How does zip(*[iter(s)]*n) work in Python?
2,233,204
65
2010-02-09T23:07:21Z
2,233,247
68
2010-02-09T23:15:10Z
[ "python", "iterator" ]
``` s = [1,2,3,4,5,6,7,8,9] n = 3 zip(*[iter(s)]*n) # returns [(1,2,3),(4,5,6),(7,8,9)] ``` How does `zip(*[iter(s)]*n)` work? What would it look like if it was written with more verbose code?
[`iter()`](https://docs.python.org/2/library/functions.html#iter) is an iterator over a sequence. `[x] * n` produces a list containing `n` quantity of `x`, i.e. a list of length `n`, where each element is `x`. `*arg` unpacks a sequence into arguments for a function call. Therefore you're passing the same iterator 3 tim...
How does zip(*[iter(s)]*n) work in Python?
2,233,204
65
2010-02-09T23:07:21Z
2,233,827
33
2010-02-10T01:32:39Z
[ "python", "iterator" ]
``` s = [1,2,3,4,5,6,7,8,9] n = 3 zip(*[iter(s)]*n) # returns [(1,2,3),(4,5,6),(7,8,9)] ``` How does `zip(*[iter(s)]*n)` work? What would it look like if it was written with more verbose code?
The other great answers and comments explain well the roles of [**argument unpacking**](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists) and [**zip()**](http://docs.python.org/library/functions.html#zip). As [Ignacio](http://stackoverflow.com/questions/2233204/how-does-zipitersn-work-in-pytho...
Overriding urllib2.HTTPError or urllib.error.HTTPError and reading response HTML anyway
2,233,687
68
2010-02-10T00:55:01Z
2,233,704
8
2010-02-10T00:59:42Z
[ "python", "urllib2", "urllib", "http-error" ]
I receive a 'HTTP Error 500: Internal Server Error' response, but I still want to read the data inside the error HTML. With Python 2.6, I normally fetch a page using: ``` import urllib2 url = "http://google.com" data = urllib2.urlopen(url) data = data.read() ``` When attempting to use this on the failing URL, I get ...
If you mean you want to read the body of the 500: ``` request = urllib2.Request(url, data, headers) try: resp = urllib2.urlopen(request) print resp.read() except urllib2.HTTPError, error: print "ERROR: ", error.read() ``` In your case, you don't need to build up the request. Just do ``` try: ...
Overriding urllib2.HTTPError or urllib.error.HTTPError and reading response HTML anyway
2,233,687
68
2010-02-10T00:55:01Z
2,233,778
131
2010-02-10T01:18:53Z
[ "python", "urllib2", "urllib", "http-error" ]
I receive a 'HTTP Error 500: Internal Server Error' response, but I still want to read the data inside the error HTML. With Python 2.6, I normally fetch a page using: ``` import urllib2 url = "http://google.com" data = urllib2.urlopen(url) data = data.read() ``` When attempting to use this on the failing URL, I get ...
The `HTTPError` [is a file-like object](http://docs.python.org/library/urllib2.html#urllib2.HTTPError). You can catch it and then `read` its contents. ``` try: resp = urllib2.urlopen(url) contents = resp.read() except urllib2.HTTPError, error: contents = error.read() ```
overriding bool() for custom class
2,233,786
29
2010-02-10T01:20:47Z
2,233,801
38
2010-02-10T01:24:23Z
[ "python", "class", "casting", "boolean", "python-2.x" ]
All I want is for bool(myInstance) to return False (and for myInstance to evaluate to False when in a conditional like if/or/and. I know how to override >, <, =) I've tried this: ``` class test: def __bool__(self): return False myInst = test() print bool(myInst) #prints "True" print myInst.__bool__() #pr...
Is this Python 2.x or Python 3.x? For Python 2.x you are looking to override `__nonzero__` instead. ``` class test: def __nonzero__(self): return False ```
overriding bool() for custom class
2,233,786
29
2010-02-10T01:20:47Z
2,233,850
38
2010-02-10T01:37:04Z
[ "python", "class", "casting", "boolean", "python-2.x" ]
All I want is for bool(myInstance) to return False (and for myInstance to evaluate to False when in a conditional like if/or/and. I know how to override >, <, =) I've tried this: ``` class test: def __bool__(self): return False myInst = test() print bool(myInst) #prints "True" print myInst.__bool__() #pr...
If you want to keep your code forward compatible with python3 you could do something like this ``` class test: def __bool__(self): return False __nonzero__=__bool__ ```
Get all related Django model objects
2,233,883
55
2010-02-10T01:46:12Z
2,315,053
72
2010-02-22T23:23:06Z
[ "python", "django", "django-models", "merge" ]
How can I get a list of all the model objects that have a ForeignKey pointing to an object? (Something like the delete confirmation page in the Django admin before DELETE CASCADE). I'm trying to come up with a generic way of merging duplicate objects in the database. Basically I want all of the objects that have Forei...
This gives you the property names for all related objects: ``` links = [rel.get_accessor_name() for rel in a._meta.get_all_related_objects()] ``` You can then use something like this to get all related objects: ``` for link in links: objects = getattr(a, link).all() for object in objects: # do someth...
Get all related Django model objects
2,233,883
55
2010-02-10T01:46:12Z
19,389,817
15
2013-10-15T19:50:56Z
[ "python", "django", "django-models", "merge" ]
How can I get a list of all the model objects that have a ForeignKey pointing to an object? (Something like the delete confirmation page in the Django admin before DELETE CASCADE). I'm trying to come up with a generic way of merging duplicate objects in the database. Basically I want all of the objects that have Forei...
@digitalPBK was close... here is probably what you are looking for using Django's built in stuff ``` from django.db.models.deletion import Collector from django.contrib.admin.util import NestedObjects collector = NestedObjects(using="default") #database name collector.collect([objective]) #list of objects. single one ...
How to input an integer tuple from user?
2,233,917
4
2010-02-10T01:57:53Z
2,233,923
10
2010-02-10T01:59:15Z
[ "python" ]
Presently I am doing this ``` print 'Enter source' source = tuple(sys.stdin.readline()) print 'Enter target' target = tuple(sys.stdin.readline()) ``` but source and target become string tuples in this case with a \n at the end
``` tuple(int(x.strip()) for x in raw_input().split(',')) ```
building dynamic forms in django
2,234,117
2
2010-02-10T02:55:01Z
2,234,306
10
2010-02-10T03:56:34Z
[ "python", "django", "django-forms" ]
I'm trying to build a form dynamically based on the field and its definitions stored in a database. In my db, I have defined 1 checkbox with some label and 1 textfield with some label. How do I build a form dynamically in my view from the data in the db? Thanks
Here are the slides from a talk I gave at EuroDjangoCon about doing precisely this: <http://www.slideshare.net/kingkilr/forms-getting-your-moneys-worth>
Parsing unicode input using python json.loads
2,234,228
10
2010-02-10T03:32:17Z
2,235,005
7
2010-02-10T07:01:52Z
[ "python", "django", "json", "unicode" ]
What is the best way to load JSON Strings in Python? I want to use json.loads to process unicode like this: ``` import json json.loads(unicode_string_to_load) ``` I also tried supplying 'encoding' parameter with value 'utf-16', but the error did not go away. Full SSCCE with error: ``` # -*- coding: utf-8 -*- impor...
I typecasting the string into unicode string using 'latin-1' fixed the error: ``` UnicodeDecodeError: 'utf16' codec can't decode byte 0x38 in position 6: truncated data ``` Fixed code: ``` import json ustr_to_load = unicode(str_to_load, 'latin-1') json.loads(ustr_to_load) ``` And then the error is not thrown.
Why both, import logging and import logging.config are needed?
2,234,982
6
2010-02-10T06:56:10Z
2,235,012
15
2010-02-10T07:03:53Z
[ "python", "logging", "import" ]
Should not it be handled by a single import? i.e. import logging. If I do not include import logging.config in my script, it gives : AttributeError: 'module' object has no attribute 'config'
`logging` is a package. Modules in packages aren't imported until you (or something in your program) imports them. You don't need both `import logging` and `import logging.config` though: just `import logging.config` will make the name `logging` available already.
Subclass builtin List
2,235,556
11
2010-02-10T09:08:43Z
2,235,580
9
2010-02-10T09:12:33Z
[ "python", "list", "subclass", "builtin" ]
I want to subclass the `list` type and have slicing return an object of the descendant type, however it is returning a `list`. What is the minimum code way to do this? If there isn't a neat way to do it, I'll just include a list internally which is slightly more messy, but not unreasonable. My code so far: ``` class...
I guess you should override the `__getslice__` method to return an object of your type... Maybe something like the following? ``` class MyList(list): #your stuff here def __getslice__(self, i, j): return MyList(list.__getslice__(self, i, j)) ```
Will Python use all processors in thread mode?
2,236,321
5
2010-02-10T11:17:56Z
2,236,368
10
2010-02-10T11:24:47Z
[ "python", "django", "multithreading", "performance", "multiprocessing" ]
While developing a Django app deployed on Apache mod\_wsgi I found that in case of multithreading (Python threads; mod\_wsgi processes=1 threads=8) Python won't use all available processors. With the multiprocessing approach (mod\_wsgi processes=8 threads=1) all is fine and I can load my machine at full. So the questi...
Will Python use all processors in thread mode? No. Python won't use all available processors; is this Python behavior normal? Yes, it's normal because of the GIL. For a discussion see <http://mail.python.org/pipermail/python-3000/2007-May/007414.html>. You may find that having a couple (or 4) of threads per core/pro...
Tell urllib2 to use custom DNS
2,236,498
11
2010-02-10T11:46:05Z
2,237,040
19
2010-02-10T13:24:10Z
[ "python", "dns", "urllib2", "dnspython", "urlopen" ]
I'd like to tell `urllib2.urlopen` (or a **custom opener**) to use `127.0.0.1` (or `::1`) to resolve addresses. I wouldn't change my `/etc/resolv.conf`, however. One possible solution is to use a tool like `dnspython` to query addresses and `httplib` to build a custom url opener. I'd prefer telling `urlopen` to use a ...
Looks like name resolution is ultimately handled by `socket.create_connection`. ``` -> urllib2.urlopen -> httplib.HTTPConnection -> socket.create_connection ``` Though once the "Host:" header has been set, you can resolve the host and pass on the IP address through down to the opener. I'd suggest that you subclass `...
Tell urllib2 to use custom DNS
2,236,498
11
2010-02-10T11:46:05Z
15,065,711
11
2013-02-25T11:15:27Z
[ "python", "dns", "urllib2", "dnspython", "urlopen" ]
I'd like to tell `urllib2.urlopen` (or a **custom opener**) to use `127.0.0.1` (or `::1`) to resolve addresses. I wouldn't change my `/etc/resolv.conf`, however. One possible solution is to use a tool like `dnspython` to query addresses and `httplib` to build a custom url opener. I'd prefer telling `urlopen` to use a ...
Another (dirty) way is monkey-patching `socket.getaddrinfo`. For example this code adds a (unlimited) cache for dns lookups. ``` import socket prv_getaddrinfo = socket.getaddrinfo dns_cache = {} # or a weakref.WeakValueDictionary() def new_getaddrinfo(*args): try: return dns_cache[args] except KeyErr...
First Python list index greater than x?
2,236,906
25
2010-02-10T13:01:40Z
2,236,935
40
2010-02-10T13:06:16Z
[ "python", "list" ]
What would be the most pythonesque way to find the first index in a list that is greater than x? For example, with ``` list = [0.5, 0.3, 0.9, 0.8] ``` The function ``` f(list, 0.7) ``` would return ``` 2. ```
``` next(x[0] for x in enumerate(L) if x[1] > 0.7) ```
First Python list index greater than x?
2,236,906
25
2010-02-10T13:01:40Z
2,236,956
9
2010-02-10T13:09:31Z
[ "python", "list" ]
What would be the most pythonesque way to find the first index in a list that is greater than x? For example, with ``` list = [0.5, 0.3, 0.9, 0.8] ``` The function ``` f(list, 0.7) ``` would return ``` 2. ```
``` >>> alist= [0.5, 0.3, 0.9, 0.8] >>> [ n for n,i in enumerate(alist) if i>0.7 ][0] 2 ```
First Python list index greater than x?
2,236,906
25
2010-02-10T13:01:40Z
2,236,993
7
2010-02-10T13:14:35Z
[ "python", "list" ]
What would be the most pythonesque way to find the first index in a list that is greater than x? For example, with ``` list = [0.5, 0.3, 0.9, 0.8] ``` The function ``` f(list, 0.7) ``` would return ``` 2. ```
``` filter(lambda x: x>.7, seq)[0] ```
passing arguments to a dynamic form in django
2,237,064
18
2010-02-10T13:28:06Z
2,237,118
41
2010-02-10T13:36:49Z
[ "python", "django", "django-forms" ]
I have a Dynamic Form in forms. How can I pass an argument from my view when I instantiate my form? Something like: ``` form = DynamicForm("some string argument I'm passing to my form") ``` This is the form I have: ``` class DynamicForm(Form): def __init__(self, *args, **kwargs): super(DynamicForm, self).__init...
Add it as keyword argument, say it's called my\_arg. ``` class DynamicForm(Form): def __init__(self, *args, **kwargs): my_arg = kwargs.pop('my_arg') super(DynamicForm, self).__init__(*args, **kwargs) for item in range(5): self.fields['test_field_%d' % item] = CharField(max_length=255) ``` And wh...
Serving static media during Django development: Why not MEDIA_ROOT?
2,237,418
17
2010-02-10T14:21:59Z
2,237,514
24
2010-02-10T14:37:21Z
[ "python", "django", "static-media" ]
I read [this guide](http://docs.djangoproject.com/en/1.1/howto/static-files/) about serving static media with Django during development. I noticed that `MEDIA_URL` and `MEDIA_ROOT` were not used in this. Why? What's the difference? I tried doing it with `MEDIA_URL` and `MEDIA_ROOT`, and got weird results.
In a production situation you will want your media to be served from your front end web server (Apache, Nginx or the like) to avoid extra load on the Django/Python process. The MEDIA\_URL and MEDIA\_ROOT are usually used for this. Running the built in Development server you will need to set the correct url in your url...
Serving static media during Django development: Why not MEDIA_ROOT?
2,237,418
17
2010-02-10T14:21:59Z
2,237,542
20
2010-02-10T14:40:57Z
[ "python", "django", "static-media" ]
I read [this guide](http://docs.djangoproject.com/en/1.1/howto/static-files/) about serving static media with Django during development. I noticed that `MEDIA_URL` and `MEDIA_ROOT` were not used in this. Why? What's the difference? I tried doing it with `MEDIA_URL` and `MEDIA_ROOT`, and got weird results.
Straight from the comments in settings.py... ### MEDIA\_ROOT The `MEDIA_ROOT` is the absolute path to the directory that holds media such as `/home/media/media.lawrence.com/`. ### MEDIA\_URL The `MEDIA_URL` is the URL that handles the media served from `MEDIA_ROOT`. Make sure to use a trailing slash if there is a p...
Applying python decorators to methods in a class
2,237,624
12
2010-02-10T14:51:10Z
2,238,076
17
2010-02-10T15:40:32Z
[ "python", "decorator" ]
I have decorator `@login_testuser` applied against method **test\_1**: ``` class TestCase(object): @login_testuser def test_1(self): print "test_1()" ``` Is there a way I can apply `@login_testuser` on every method of the class prefixed with "test\_"? In other words, the decorator would apply to **te...
In Python 2.6, a [class decorator](http://docs.python.org/whatsnew/2.6.html#pep-3129-class-decorators) is definitely the way to go. E.g., here's a pretty general one for these kind of tasks: ``` import inspect def decallmethods(decorator, prefix='test_'): def dectheclass(cls): for name, m in inspect.getmembers(...
What is the pythonic way to unpack tuples?
2,238,355
55
2010-02-10T16:14:49Z
2,238,361
88
2010-02-10T16:15:52Z
[ "python", "tuples" ]
This is ugly. What's a more Pythonic way to do it? ``` import datetime t= (2010, 10, 2, 11, 4, 0, 2, 41, 0) dt = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6]) ```
Generally you can use the `func(*tuple)` syntax. You can even pass a part of the tuple, which seems like what you're trying to do here: ``` t = (2010, 10, 2, 11, 4, 0, 2, 41, 0) dt = datetime.datetime(*t[0:7]) ``` This is called *unpacking* a tuple, and can be used for other itarables (such as lists) too. Here's anot...
What is the pythonic way to unpack tuples?
2,238,355
55
2010-02-10T16:14:49Z
2,238,362
8
2010-02-10T16:15:59Z
[ "python", "tuples" ]
This is ugly. What's a more Pythonic way to do it? ``` import datetime t= (2010, 10, 2, 11, 4, 0, 2, 41, 0) dt = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6]) ```
Refer <https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists> ``` dt = datetime.datetime(*t[:7]) ```
How can files be added to a tarfile with Python, without adding the directory hierarchy?
2,239,655
24
2010-02-10T19:21:54Z
2,239,679
27
2010-02-10T19:25:02Z
[ "python", "tar" ]
When I invoke `add()` on a `tarfile` object with a file path, the file is added to the tarball with directory hierarchy associated. In other words, if I unzip the tarfile the directories in the original directories hierarchy are reproduced. Is there a way to simply adding a plain file without directory info that untar...
You can use [`tarfile.addfile()`](http://www.python.org/doc/2.6/library/tarfile.html#tarfile.TarFile.addfile), in the [`TarInfo`](http://www.python.org/doc/2.6/library/tarfile.html#tarfile.TarInfo) object, which is the first parameter, you can specify a `name` that's different from the file you're adding. This piece o...
How can files be added to a tarfile with Python, without adding the directory hierarchy?
2,239,655
24
2010-02-10T19:21:54Z
10,962,896
31
2012-06-09T17:06:56Z
[ "python", "tar" ]
When I invoke `add()` on a `tarfile` object with a file path, the file is added to the tarball with directory hierarchy associated. In other words, if I unzip the tarfile the directories in the original directories hierarchy are reproduced. Is there a way to simply adding a plain file without directory info that untar...
The **arch** argument of TarFile.add() method is an alternate and convenient way to match your destination. Example: you want to archive a dir *repo/a.git/* to a *tar.gz* file, but you rather want the tree root in the archive begins by *a.git/* but not *repo/a.git/*, you can do like followings: ``` archive = tarfile....
Is it better to use "is" or "==" for number comparison in Python?
2,239,737
16
2010-02-10T19:34:10Z
2,239,753
31
2010-02-10T19:36:39Z
[ "python" ]
Is it better to use the "is" operator or the "==" operator to compare two numbers in Python? Examples: ``` >>> a = 1 >>> a is 1 True >>> a == 1 True >>> a is 0 False >>> a == 0 False ```
Use `==`. Only integers from -1 to 256 will work with `is`.
Is it better to use "is" or "==" for number comparison in Python?
2,239,737
16
2010-02-10T19:34:10Z
2,239,788
15
2010-02-10T19:41:59Z
[ "python" ]
Is it better to use the "is" operator or the "==" operator to compare two numbers in Python? Examples: ``` >>> a = 1 >>> a is 1 True >>> a == 1 True >>> a is 0 False >>> a == 0 False ```
Others have answered your question, but I'll go into a little bit more detail: Python's `is` compares identity - it asks the question "is this one thing exactly identical to this other thing" (similar to `==` in Java). So, there are some times when using `is` makes sense - the most common one being checking for `None`...
Separate number from unit in a string in Python
2,240,303
3
2010-02-10T20:59:55Z
2,240,469
7
2010-02-10T21:26:47Z
[ "python", "string", "units-of-measurement" ]
I have strings containing numbers with their units, e.g. 2GB, 17ft, etc. I would like to separate the number from the unit and create 2 different strings. Sometimes, there is a whitespace between them (e.g. 2 GB) and it's easy to do it using split(' '). When they are together (e.g. 2GB), I would test every character u...
You can break out of the loop when you find the first non-digit character ``` for i,c in enumerate(s): if not c.isdigit(): break number = s[:i] unit = s[i:].lstrip() ``` If you have negative and decimals: ``` numeric = '0123456789-.' for i,c in enumerate(s): if c not in numeric: break number ...
Python 2.6.4 property decorators not working
2,240,351
6
2010-02-10T21:07:49Z
2,240,368
20
2010-02-10T21:09:59Z
[ "python", "properties", "decorator" ]
I've seen many examples [online](http://blog.ianbicking.org/property-decorator.html) and [in this forum](http://stackoverflow.com/questions/2123585/python-multiple-properties-one-setter-getter) of how to create properties in Python with special **getters** and **setters**. However, I can't get the special getter and se...
**PathInfo** must subclass **object**. Like this: ``` class PathInfo(object): ``` Properties work only on new style classes.
Cross-platform desktop notifier in Python
2,240,674
43
2010-02-10T22:02:36Z
2,244,315
17
2010-02-11T12:21:36Z
[ "python", "cross-platform", "desktop", "notifications", "growl" ]
I am looking for [Growl](http://growl.info/)-like, Windows balloon-tip-like notifications library in Python. Imagine writing code like: ``` >>> import desktopnotifier as dn >>> dn.notify('Title', 'Long description goes here') ``` .. and that would notify with corresponding tooltips on Mac, Windows and Linux. Does suc...
[Here's a desktop notifier I wrote a few years ago using wxPython](http://code.google.com/p/readertray/source/browse/trunk/readergui.py) - it behaves identically across Windows and Linux and should also run on OSX. It contains a threaded event loop that can be used to animate a notification window containing an icon an...
Cross-platform desktop notifier in Python
2,240,674
43
2010-02-10T22:02:36Z
7,076,231
15
2011-08-16T09:37:38Z
[ "python", "cross-platform", "desktop", "notifications", "growl" ]
I am looking for [Growl](http://growl.info/)-like, Windows balloon-tip-like notifications library in Python. Imagine writing code like: ``` >>> import desktopnotifier as dn >>> dn.notify('Title', 'Long description goes here') ``` .. and that would notify with corresponding tooltips on Mac, Windows and Linux. Does suc...
At Pycon 2010 there was a [presentation on cross-platform Python development](http://python.mirocommunity.org/video/1595/pycon-2010-cross-platform-appl). There was a html page about it as well, containing some advice for cross-platform notification. However, I don't find it online anymore, but I saved a local copy, and...
Is CherryPy a robust webserver (ie, is it reliable under a huge load like Apache)?
2,240,700
12
2010-02-10T22:07:06Z
2,240,753
17
2010-02-10T22:14:18Z
[ "python", "webserver", "cherrypy" ]
I'm wondering because [CherryPy](http://www.cherrypy.org/) is, from my knowledge, built purely in Python, which is obviously slower than C et al. Does this mean that it's only good for dev / testing environments, or could I use it behind [NGINX](http://www.nginx.org/) like I use Apache with [Fast CGI](http://www.fastcg...
CherryPy's WSGI server is about as fast as a pure-Python WSGI server is going to get. I personally use it behind Nginx in production, but even standalone on my dev machine I can load each instance with several hundred requests / sec. without problems. Can you find a faster server? Yes. Is CherryPy a robust web server,...
Is there a significant overhead by using different versions of sha hashing (hashlib module)
2,241,013
12
2010-02-10T23:03:57Z
2,241,072
18
2010-02-10T23:18:13Z
[ "python", "hash", "hashlib" ]
The [`hashlib`](http://docs.python.org/library/hashlib.html) Python module provides the following hash algorithms constructors: `md5()`, `sha1()`, `sha224()`, `sha256()`, `sha384()`, and `sha512()`. Assuming I don't want to use md5, is there a big difference in using, say, sha1 instead of sha512? I want to use somethi...
Why not just benchmark it? ``` >>> def sha1(s): ... return hashlib.sha1(s).hexdigest() ... >>> def sha512(s): ... return hashlib.sha512(s).hexdigest() ... >>> t1 = timeit.Timer("sha1('asdf' * 100)", "from __main__ import sha1") >>> t512 = timeit.Timer("sha512('asdf' * 100)", "from __main__ import sha512") >>> ...
Django and VirtualEnv Development/Deployment Best Practices
2,241,055
38
2010-02-10T23:14:20Z
2,243,060
21
2010-02-11T08:13:02Z
[ "python", "django", "git", "virtualenv" ]
Just curious how people are deploying their Django projects in combination with virtualenv * More specifically, how do you keep your production virtualenv's synched correctly with your development machine? I use git for scm but I don't have my virtualenv inside the git repo - should I, or is it best to use the pip fr...
I just set something like this up at work using pip, Fabric and git. The flow is basically like this, and borrows heavily from [this script](http://www.morethanseven.net/2009/07/27/fabric-django-git-apache-mod-wsgi-virtualenv-and-p/): 1. In our source tree, we maintain a requirements.txt file. We'll maintain this manu...
Is it possible to declare a function without arguments but then pass some arguments to that function without raising exception?
2,241,200
6
2010-02-10T23:43:20Z
2,241,224
9
2010-02-10T23:48:31Z
[ "python", "exception", "arguments" ]
In python is it possible to have the above code without raising an exception ? ``` def myfunc(): pass # TypeError myfunc() takes no arguments (1 given) myfunc('param') ``` Usually in php in some circumstances I launch a function without parameters and then retrieve the parameters inside the function. In practic...
There are two ways to pass args in **By Position** ``` >>> def myfunc(*args): ... print "args", args ... >>> myfunc("param") args ('param',) ``` **By Keyword** ``` >>> def myfunc(**kw): ... print "kw", kw ... >>> myfunc(param="param") kw {'param': 'param'} ``` And you can use a **combination of both** ``` >>> ...
Is it possible to declare a function without arguments but then pass some arguments to that function without raising exception?
2,241,200
6
2010-02-10T23:43:20Z
2,241,232
8
2010-02-10T23:50:41Z
[ "python", "exception", "arguments" ]
In python is it possible to have the above code without raising an exception ? ``` def myfunc(): pass # TypeError myfunc() takes no arguments (1 given) myfunc('param') ``` Usually in php in some circumstances I launch a function without parameters and then retrieve the parameters inside the function. In practic...
``` >>> def myFunc(*args, **kwargs): ... # This function accepts arbitary arguments: ... # Keywords arguments are available in the kwargs dict; ... # Regular arguments are in the args tuple. ... # (This behaviour is dictated by the stars, not by ... # the name of the formal parameters.) ... print args, kwa...
Python regex - r prefix
2,241,600
27
2010-02-11T01:18:56Z
2,241,618
41
2010-02-11T01:24:16Z
[ "python", "regex", "string", "literals", "prefix" ]
Can anyone explain why example 1 below works, when the r prefix is not used? I thought the r prefix must be used whenever escape sequences are used? Example 2 and example 3 demonstrates this.. ``` # example 1 import re print (re.sub('\s+', ' ', 'hello there there')) # prints 'hello there there' - not expected...
Because `\` begin escape sequences only when they are valid escape sequences. ``` >>> '\n' '\n' >>> r'\n' '\\n' >>> print '\n' >>> print r'\n' \n >>> '\s' '\s' >>> r'\s' '\\s' >>> print '\s' \s >>> print r'\s' \s ``` > [Unless](http://docs.python.org/library/re.html) an 'r' or 'R' prefix is present, [escape sequenc...
Python regex - r prefix
2,241,600
27
2010-02-11T01:18:56Z
2,241,641
10
2010-02-11T01:30:11Z
[ "python", "regex", "string", "literals", "prefix" ]
Can anyone explain why example 1 below works, when the r prefix is not used? I thought the r prefix must be used whenever escape sequences are used? Example 2 and example 3 demonstrates this.. ``` # example 1 import re print (re.sub('\s+', ' ', 'hello there there')) # prints 'hello there there' - not expected...
the 'r' means the the following is a "raw string", ie. backslash characters are treated literally instead of signifying special treatment of the following character. <http://docs.python.org/reference/lexical_analysis.html#literals> so `'\n'` is a single newline and `r'\n'` is two characters - a backslash and the le...
How to initialize a dict with keys from a list and empty value in Python?
2,241,891
84
2010-02-11T02:43:19Z
2,241,904
156
2010-02-11T02:45:35Z
[ "dictionary", "python" ]
I'd like to get from this: ``` keys = [1,2,3] ``` to this: ``` {1: None, 2: None, 3: None} ``` Is there a pythonic way of doing it? This is an ugly way to do it: ``` >>> keys = [1,2,3] >>> dict([(1,2)]) {1: 2} >>> dict(zip(keys, [None]*len(keys))) {1: None, 2: None, 3: None} ```
`dict.fromkeys([1, 2, 3, 4])` This is actually a classmethod, so it works for dict-subclasses (like `collections.defaultdict`) as well. The optional second argument specifies the value to use for the keys (defaults to `None`.)
How to initialize a dict with keys from a list and empty value in Python?
2,241,891
84
2010-02-11T02:43:19Z
2,241,911
27
2010-02-11T02:48:21Z
[ "dictionary", "python" ]
I'd like to get from this: ``` keys = [1,2,3] ``` to this: ``` {1: None, 2: None, 3: None} ``` Is there a pythonic way of doing it? This is an ugly way to do it: ``` >>> keys = [1,2,3] >>> dict([(1,2)]) {1: 2} >>> dict(zip(keys, [None]*len(keys))) {1: None, 2: None, 3: None} ```
``` dict.fromkeys(keys, None) ```
How to initialize a dict with keys from a list and empty value in Python?
2,241,891
84
2010-02-11T02:43:19Z
2,244,026
82
2010-02-11T11:18:18Z
[ "dictionary", "python" ]
I'd like to get from this: ``` keys = [1,2,3] ``` to this: ``` {1: None, 2: None, 3: None} ``` Is there a pythonic way of doing it? This is an ugly way to do it: ``` >>> keys = [1,2,3] >>> dict([(1,2)]) {1: 2} >>> dict(zip(keys, [None]*len(keys))) {1: None, 2: None, 3: None} ```
nobody cared to give a dict-comprehension solution ? ``` >>> keys = [1,2,3,5,6,7] >>> {key: None for key in keys} {1: None, 2: None, 3: None, 5: None, 6: None, 7: None} ```
How to send a xml-rpc request in python?
2,242,174
5
2010-02-11T03:59:09Z
2,242,202
10
2010-02-11T04:06:34Z
[ "python", "xml-rpc" ]
I was just wondering, how would I be able to send a `xml-rpc` request in python? I know you can use `xmlrpclib`, but how do I send out a request in `xml` to access a function? I would like to see the `xml` response. So basically I would like to send the following as my request to the server: ``` <?xml version="1.0"?...
Here's a simple XML-RPC client in Python: ``` import xmlrpclib s = xmlrpclib.ServerProxy('http://localhost:8000') print s.myfunction(2, 4) ``` Works with this server: ``` from SimpleXMLRPCServer import SimpleXMLRPCServer from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler # Restrict to a particular path. cla...
more pythonic way of finding element in list that maximizes a function
2,242,489
3
2010-02-11T05:33:31Z
2,242,496
14
2010-02-11T05:35:52Z
[ "list", "coding-style", "python", "maximize" ]
OK, I have this simple function that finds the element of the list that maximizes the value of another positive function. ``` def get_max(f, s): # f is a function and s is an iterable best = None best_value = -1 for element in s: this_value = f(element) if this_value > best_value: ...
``` def get_max(f, s): return max(s, key=f) ```
methods of metaclasses on class instances
2,242,715
9
2010-02-11T06:37:39Z
2,242,740
7
2010-02-11T06:43:02Z
[ "python", "metaclass" ]
I was wondering what happens to methods declared on a metaclass. I expected that if you declare a method on a metaclass, it will end up being a classmethod, however, the behavior is different. Example ``` >>> class A(object): ... @classmethod ... def foo(cls): ... print "foo" ... >>> a=A() >>> a.foo()...
The rule is like this: when searching for an attribute on an object, the object's class and its parent classes are considered as well. An object's class's metaclass, however, is *not* considered. When you access an attribute of a class, the class's class is the metaclass, so it *is* considered. The fallback from object...
methods of metaclasses on class instances
2,242,715
9
2010-02-11T06:37:39Z
2,245,993
12
2010-02-11T16:43:33Z
[ "python", "metaclass" ]
I was wondering what happens to methods declared on a metaclass. I expected that if you declare a method on a metaclass, it will end up being a classmethod, however, the behavior is different. Example ``` >>> class A(object): ... @classmethod ... def foo(cls): ... print "foo" ... >>> a=A() >>> a.foo()...
You raise a good point. Here is a [good reference](http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html)to get a better understanding of the relations between objects, classes and metaclasses: I also find [this reference on descriptors](http://users.rcn.com/python/download/Descriptor.h...
Django user impersonation by admin
2,242,909
17
2010-02-11T07:35:59Z
2,243,865
9
2010-02-11T10:42:12Z
[ "python", "django", "impersonation" ]
I have a Django app. When logged in as an admin user, I want to be able to pass a secret parameter in the URL and have the whole site behave as if I were another user. Let's say I have the URL `/my-profile/` which shows the currently logged in user's profile. I want to be able to do something like `/my-profile/?__user...
I solved this with a simple middleware. It also handles redirects (that is, the GET parameter is preserved during a redirect). Here it is: ``` class ImpersonateMiddleware(object): def process_request(self, request): if request.user.is_superuser and "__impersonate" in request.GET: request.user =...
Django user impersonation by admin
2,242,909
17
2010-02-11T07:35:59Z
4,672,864
30
2011-01-12T19:02:19Z
[ "python", "django", "impersonation" ]
I have a Django app. When logged in as an admin user, I want to be able to pass a secret parameter in the URL and have the whole site behave as if I were another user. Let's say I have the URL `/my-profile/` which shows the currently logged in user's profile. I want to be able to do something like `/my-profile/?__user...
I don't have enough reputation to edit or reply yet (I think), but I found that although ionaut's solution worked in simple cases, a more robust solution for me was to use a session variable. That way, even AJAX requests are served correctly without modifying the request URL to include a GET impersonation parameter. `...
Django: "TypeError: [] is not JSON serializable" Why?
2,243,002
33
2010-02-11T07:58:32Z
2,243,652
52
2010-02-11T10:05:59Z
[ "python", "django", "json" ]
How can this be that this error was raised? I entered this: ``` def json(self): return json.dumps( { 'items': self.items } ) ``` and got that error (because self.items was an empty queryset (Django) but then, ``` def json(self): return json.dumps( { 'items...
Querysets are not serializable out-of-the-box. If you try `list(self.items)` instead of just `self.items`, that should work as long as the items themselves are JSON-serializable. **Update:** It will raise an exception even if it isn't empty. I don't think it'll be accepted as a Django bug, though of course you can try...
(python) docstring is causing indentation error
2,243,009
7
2010-02-11T08:01:03Z
2,243,027
9
2010-02-11T08:04:19Z
[ "python", "indentation" ]
``` def getText(nodelist): """Extracts the text between XML tags I took this directly from http://docs.python.org/library/xml.dom.minidom.html. For example, if I have a tag <Tag>525</Tag> this method returns me '525' """ rc = "" for node in nodelist: if node.nodeType == node.TEXT_NODE: ...
Your docstring starts with tabs. Make your code only use spaces for indentation (or only tabs), including the indentation for the docstrings.
Getting certain attribute value using XPath
2,243,131
6
2010-02-11T08:29:34Z
2,243,186
9
2010-02-11T08:42:18Z
[ "python", "xpath" ]
From the following HTML snippet: ``` <link rel="index" href="/index.php" /> <link rel="contents" href="/getdata.php" /> <link rel="copyright" href="/blabla.php" /> <link rel="shortcut icon" href="/img/all/favicon.ico" /> ``` I'm trying to get the `href` value of the `link` tag with rel value = `"shortcut icon"`, I'm ...
Like this: ``` data = """<link rel="index" href="/index.php" /> <link rel="contents" href="/getdata.php" /> <link rel="copyright" href="/blabla.php" /> <link rel="shortcut icon" href="/img/all/favicon.ico" /> """ from lxml import etree d = etree.HTML(data) d.xpath('//link[@rel="shortcut icon"]/@href') ['/img/all/fa...
how to efficiently get the k bigger elements of a list in python
2,243,542
14
2010-02-11T09:47:17Z
2,243,562
28
2010-02-11T09:50:45Z
[ "algorithm", "sorting", "performance", "python" ]
What´s the most efficient, elegant and pythonic way of solving this problem? Given a list (or set or whatever) of n elements, we want to get the k biggest ones. ( You can assume `k<n/2` without loss of generality, I guess) For example, if the list were: ``` l = [9,1,6,4,2,8,3,7,5] ``` n = 9, and let's say k = 3. Wh...
Use nlargest from heapq module ``` from heapq import nlargest lst = [9,1,6,4,2,8,3,7,5] nlargest(3, lst) # Gives [9,8,7] ``` You can also give a key to nlargest in case you wanna change your criteria: ``` from heapq import nlargest tags = [ ("python", 30), ("ruby", 25), ("c++", 50), ("lisp", 20) ] nlargest(2, tags, ...
reading csv file without for
2,243,655
7
2010-02-11T10:06:50Z
2,244,051
12
2010-02-11T11:22:54Z
[ "python", "csv" ]
I need to read a CSV file in python. Since for last row I receive a 'NULL byte' error I would like to avoid using for keyword but the while. Do you know how to do that? ``` reader = csv.reader( file ) for row in reader # I have an error at this line # do whatever with row ``` I want to substitute...
Maybe you could catch the exception raised by the CSV reader. Something like this: ``` filename = "my.csv" reader = csv.reader(open(filename)) try: for row in reader: print 'Row read with success!', row except csv.Error, e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) ``` Or you c...
Location to put user configuration files in windows
2,243,895
5
2010-02-11T10:48:37Z
2,243,910
9
2010-02-11T10:52:01Z
[ "python", "windows", "configuration", "configuration-files" ]
I'm writing a python library that has a per-user configuration file that can be edited by the user of the library. The library also generates logging files. On \*nix, the standard seems to be to dump them in $HOME/.library\_name. However, I am not sure what to do with Windows users. I've used windows for years before ...
%APPDATA% is the right place for these (probably in a subdirectory for your library). Unfortunately a fair number of \*nix apps ported to Windows *don't* respect that and I end up with .gem, .ssh, .VirtualBox, etc., folders cluttering up my home directory and not hidden by default as on \*nix. You can make it easy eve...
How to log python program activity in Mac OS X
2,244,153
9
2010-02-11T11:45:47Z
2,244,619
20
2010-02-11T13:15:31Z
[ "python", "osx", "logging" ]
I'm pretty new to Python programming so I have this question: How can I log a Python application activity into /var/log with Mac OS X? I tried using syslog module, but it does not seem to write anything. I tried also with the logging module, but I always run into a permission error. How can I do it? Update: ``` im...
I found the solution. It seems that Mac OS X does not record any log activity lower than LOG\_ALERT, so this does the trick ``` import syslog # Define identifier syslog.openlog("Python") # Record a message syslog.syslog(syslog.LOG_ALERT, "Example message") ``` This message is recorded on /var/log/system.log
Get a Try statement to loop around until correct value obtained
2,244,270
10
2010-02-11T12:09:44Z
2,244,307
23
2010-02-11T12:19:48Z
[ "python", "exception-handling", "loops", "try-catch" ]
I am trying to get a user to enter a number between 1 and 4. I have code to check if the number is correct but I want the code to loop around several times until the numbers is correct. Does anyone know how to do this? The code is below: ``` def Release(): try: print 'Please select one of the following?\...
``` def files(a): pass while True: try: i = int(input('Select: ')) if i in range(4): files(i) break except: pass print '\nIncorrect input, try again' ```