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
python's datetime and end of the month
1,662,140
4
2009-11-02T15:58:45Z
1,662,154
14
2009-11-02T16:02:10Z
[ "python", "datetime" ]
How to create datetime object representing the very last moment of the current month ?
Use a simple trick: Set the date to the first of the *next* month and then subtract one second/hour/day/as much as you need.
How can I capture the return value of shutil.copy() in Python ( on DOS )?
1,662,261
8
2009-11-02T16:26:01Z
1,662,314
13
2009-11-02T16:33:44Z
[ "python", "exception", "logging" ]
I am trying to record the success or failure of a number of copy commands, into a log file. I'm using `shutil.copy()` - e.g. ``` str_list.append(getbitmapsfrom) game.bigbitmap = "i doubt this is there.bmp" str_list.append(game.bigbitmap) source = '\\'.join(str_list) shutil.copy(source, newbigbmpname) ``` I forced on...
You'll want to look at the [exceptions section](http://docs.python.org/tutorial/errors.html#exceptions) of the [Python tutorial](http://docs.python.org/tutorial/index.html). In the case of shutil.copy() not finding one of the arguments, an IOError exception will be raised. You can get the message from the exception ins...
problem with the new lines when I use toprettyxml()
1,662,351
9
2009-11-02T16:40:24Z
2,455,250
9
2010-03-16T14:40:13Z
[ "python", "xml" ]
I'm currently using the toprettyxml() function of the xml.dom module in a python script and I have some troubles with the newlines. If don't use the newl parameter or if I use toprettyxml(newl='\n') actually it displays several new lines instead of only one. For instance ``` f = open(filename, 'w') f.write(dom1.topre...
`toprettyxml()` is quite awful. It is not a matter of Windows and '\r\n'. Trying any string as the `newl`parameter shows that too many lines are being added. Not only that, but other blanks (that may cause you problems when a machine reads the xml) are also added. Some workarounds available at <http://ronrothman.com...
Running Python's IDLE in windows
1,662,576
7
2009-11-02T17:22:42Z
1,662,586
14
2009-11-02T17:25:56Z
[ "python", "windows", "python-idle" ]
I messed up my IDLE shortcut. What is the way to start IDLE from the cmd.exe shell in Windows?
On my system, running `C:\Python26\lib\idlelib\idle.py` launches idle from the command prompt. Obviously you will need to adjust your path if your main Python directory isn't `C:\Python26\`. It looks like you could also launch it via `idle.pyw` or `idle.bat` in that same directory.
Python on windows7 intel 64bit
1,662,920
4
2009-11-02T18:43:00Z
1,662,955
13
2009-11-02T18:48:57Z
[ "python", "installation" ]
I've been messing around with Python over the weekend and find myself pretty much back at where I started. I've specifically been having issues with easy\_install and nltk giving me errors about not finding packages, etc. I've tried both Python 2.6 and Python 3.1. I think part of the problem may be that I'm running ...
The most popular 64-bit mode for "86-oid" processor is commonly known as AMD64 because AMD first came up with it (Intel at that time was pushing Itanium instead, and that didn't really catch fire -- it's still around but I don't even know if Win7 supports it); Intel later had to imitate that mode to get into the mass-6...
How do I loop through all levels of a data structure to extract all data when I don't know how many levels there will be?
1,663,077
2
2009-11-02T19:13:27Z
1,663,114
10
2009-11-02T19:17:55Z
[ "python", "xml", "data-structures", "loops" ]
I need to extract data from a structure and put it into a list, but I don't know how many levels the structure has. For each level, I can call `level.children()`, if there are no levels below the current one, it returns `[]`, if there are, it returns `[object, object, ...]`, on each of which I can call `children()` on...
You're describing [recursion](http://en.wikipedia.org/wiki/Recursion%5F%28computer%5Fscience%29), but I'm guessing there are [better](http://codespeak.net/lxml/), [ways](http://pyxml.sourceforge.net/topics/howto/xml-howto.html), [to](http://effbot.org/zone/element.htm), [parse](http://www.diveintopython.org/xml%5Fproce...
Python urllib2: Reading content body even during HTTPError exception?
1,663,790
41
2009-11-02T21:23:28Z
1,663,809
37
2009-11-02T21:26:40Z
[ "python" ]
I'm using urllib2 to fetch a a page via HTTP. Sometimes the resource throws a HTTP error 400 (Bad Request) when my request contains an error. However, that response also contains an XML element that gives a detailed error message. It would be very handy to be able to see that error rather than just the HTTPError except...
You can treat the error as a response. <http://www.voidspace.org.uk/python/articles/urllib2.shtml#httperror> > When an error is raised the server > responds by returning an HTTP error > code and an error page. You can use > the HTTPError instance as a response > on the page returned. This means that > as well as the ...
Python urllib2: Reading content body even during HTTPError exception?
1,663,790
41
2009-11-02T21:23:28Z
1,664,074
41
2009-11-02T22:15:13Z
[ "python" ]
I'm using urllib2 to fetch a a page via HTTP. Sometimes the resource throws a HTTP error 400 (Bad Request) when my request contains an error. However, that response also contains an XML element that gives a detailed error message. It would be very handy to be able to see that error rather than just the HTTPError except...
``` import urllib2 try: request = urllib2.Request('http://www.somesite.com') response = urllib2.urlopen(req) except urllib2.HTTPError as e: error_message = e.read() print error_message ```
How can I iterate through two lists in parallel in Python?
1,663,807
272
2009-11-02T21:26:24Z
1,663,818
23
2009-11-02T21:27:53Z
[ "python", "iterator" ]
I have two iterables in Python, and I want to go over them in pairs: ``` foo = (1, 2, 3) bar = (4, 5, 6) for (f, b) in some_iterator(foo, bar): print "f: ", f, "; b: ", b ``` It should result in: ``` f: 1; b: 4 f: 2; b: 5 f: 3; b: 6 ``` *One* way to do it is to iterate over the indices: ``` for i in xrange(le...
You want the `zip` function. ``` for (f,b) in zip(foo, bar): print "f: ", f ,"; b: ", b ```
How can I iterate through two lists in parallel in Python?
1,663,807
272
2009-11-02T21:26:24Z
1,663,823
10
2009-11-02T21:28:11Z
[ "python", "iterator" ]
I have two iterables in Python, and I want to go over them in pairs: ``` foo = (1, 2, 3) bar = (4, 5, 6) for (f, b) in some_iterator(foo, bar): print "f: ", f, "; b: ", b ``` It should result in: ``` f: 1; b: 4 f: 2; b: 5 f: 3; b: 6 ``` *One* way to do it is to iterate over the indices: ``` for i in xrange(le...
The builtin `zip` does exactly what you want. If you want the same over iterables instead of lists you could look at itertools.izip which does the same thing but gives results one at a time.
How can I iterate through two lists in parallel in Python?
1,663,807
272
2009-11-02T21:26:24Z
1,663,826
469
2009-11-02T21:28:27Z
[ "python", "iterator" ]
I have two iterables in Python, and I want to go over them in pairs: ``` foo = (1, 2, 3) bar = (4, 5, 6) for (f, b) in some_iterator(foo, bar): print "f: ", f, "; b: ", b ``` It should result in: ``` f: 1; b: 4 f: 2; b: 5 f: 3; b: 6 ``` *One* way to do it is to iterate over the indices: ``` for i in xrange(le...
``` for f, b in zip(foo, bar): print(f, b) ``` `zip` stops when the shorter of `foo` or `bar` stops. In **Python 2**, [`zip`](https://docs.python.org/2/library/functions.html#zip) returns a list of tuples. This is fine when `foo` and `bar` are not massive. If they are both massive then forming `zip(foo,bar)` is a...
How to avoid writing request.GET.get() twice in order to print it?
1,663,995
37
2009-11-02T21:59:42Z
1,664,010
23
2009-11-02T22:02:14Z
[ "python", "if-statement", "dictionary" ]
I come from a PHP background and would like to know if there's a way to do this in Python. In PHP you can kill 2 birds with one stone like this: Instead of: ``` if(getData()){ $data = getData(); echo $data; } ``` I can do this: ``` if($data = getData()){ echo $data; } ``` You check to see if `getData(...
Probably not exactly what you were thinking, but... ``` q = request.GET.get('q') if q: print q ``` this?
How to avoid writing request.GET.get() twice in order to print it?
1,663,995
37
2009-11-02T21:59:42Z
1,664,013
23
2009-11-02T22:03:18Z
[ "python", "if-statement", "dictionary" ]
I come from a PHP background and would like to know if there's a way to do this in Python. In PHP you can kill 2 birds with one stone like this: Instead of: ``` if(getData()){ $data = getData(); echo $data; } ``` I can do this: ``` if($data = getData()){ echo $data; } ``` You check to see if `getData(...
See my 8-year-old recipe [here](http://code.activestate.com/recipes/66061/) for just this task. ``` # In Python, you can't code "if x=foo():" -- assignment is a statement, thus # you can't fit it into an expression, as needed for conditions of if and # while statements, &c. No problem, if you just structure your code...
How to avoid writing request.GET.get() twice in order to print it?
1,663,995
37
2009-11-02T21:59:42Z
1,806,338
9
2009-11-27T01:03:20Z
[ "python", "if-statement", "dictionary" ]
I come from a PHP background and would like to know if there's a way to do this in Python. In PHP you can kill 2 birds with one stone like this: Instead of: ``` if(getData()){ $data = getData(); echo $data; } ``` I can do this: ``` if($data = getData()){ echo $data; } ``` You check to see if `getData(...
A variation on [Alex's answer](http://stackoverflow.com/questions/1663995/python-variable-assignment-and-if-statement/1664013#1664013): ``` class DataHolder: def __init__(self, value=None, attr_name='value'): self._attr_name = attr_name self.set(value) def __call__(self, value): return ...
What does "evaluated only once" mean for chained comparisons in Python?
1,664,292
19
2009-11-02T23:01:45Z
1,664,307
44
2009-11-02T23:06:57Z
[ "python" ]
A friend brought this to my attention, and after I pointed out an oddity, we're both confused. Python's docs, say, and have said since at least 2.5.1 (haven't checked further back: > Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but i...
The 'expression' `y` is evaluated once. I.e., in the following expression, the function is executed only one time. ``` >>> def five(): ... print 'returning 5' ... return 5 ... >>> 1 < five() <= 5 returning 5 True ``` As opposed to: ``` >>> 1 < five() and five() <= 5 returning 5 returning 5 True ```
What does "evaluated only once" mean for chained comparisons in Python?
1,664,292
19
2009-11-02T23:01:45Z
1,664,313
8
2009-11-02T23:08:37Z
[ "python" ]
A friend brought this to my attention, and after I pointed out an oddity, we're both confused. Python's docs, say, and have said since at least 2.5.1 (haven't checked further back: > Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but i...
In the context of y being evaluated, y is meant as an arbitrary expression that could have side-effects. For instance: ``` class Foo(object): @property def complain(self): print("Evaluated!") return 2 f = Foo() print(1 < f.complain < 3) # Prints evaluated once print(1 < f.complain and f.compla...
Django date filter by day of month
1,664,636
4
2009-11-03T00:58:35Z
1,664,681
7
2009-11-03T01:20:46Z
[ "python", "django" ]
I need to write a query that returns all object less that or equal to a certain day of a certain month. The year is not important. It's easy enough to get an object by a particular day/month (assume `now = datetime.datetime.now()`): ``` posts = TodaysObject.objects.filter(publish_date__day=now.day, publish_date__month...
Try this: Option 1: ``` from django.db.models import Q datafilter = Q() for i in xrange(1, now.day+1): datafilter = datafilter | Q(publish_date__day=i) datafilter = datafilter & Q(publish_date__month=now.month) posts = TodaysObject.objects.filter(datafilter) ``` Option 2: Perform raw sql query: ``` def query_...
Python string interning and substrings
1,664,840
4
2009-11-03T02:15:13Z
1,664,919
7
2009-11-03T02:40:32Z
[ "python" ]
Does python create a completely new string (copying the contents) when you do a substring operation like: ``` new_string = my_old_string[foo:bar] ``` Or does it use interning to point to the old data ? As a clarification, I'm curious if the underlying character buffer is shared as it is in Java. I realize that strin...
Examining [the source](http://svn.python.org/view/python/trunk/Objects/stringobject.c?revision=75722&view=markup) reveals: When the slice indexes match the start and end of the original string, then the original string is returned. Otherwise, you get the result of the function `PyString_FromStringAndSize`, which take...
Python string interning and substrings
1,664,840
4
2009-11-03T02:15:13Z
1,664,990
8
2009-11-03T03:05:32Z
[ "python" ]
Does python create a completely new string (copying the contents) when you do a substring operation like: ``` new_string = my_old_string[foo:bar] ``` Or does it use interning to point to the old data ? As a clarification, I'm curious if the underlying character buffer is shared as it is in Java. I realize that strin...
You may also be interested in islice which does provide a view of the original string ``` >>> from sys import getrefcount >>> from itertools import islice >>> h="foobarbaz" >>> getrefcount(h) 2 >>> g=islice(h,3,6) >>> getrefcount(h) 3 >>> "".join(g) 'bar' >>> ```
How to create an image from a string in python
1,664,861
16
2009-11-03T02:20:39Z
1,664,958
28
2009-11-03T02:56:27Z
[ "python", "string", "image", "sockets" ]
I'm currently having trouble creating an image from a binary string of data in my Python program. I receive the binary data via a socket but when I try the methods I read about on [here](http://effbot.org/imagingbook/introduction.htm) like this: ``` buff = StringIO.StringIO() #buffer where image is stored #Then I conc...
I suspect that you're not `seek`-ing back to the beginning of the buffer before you pass the StringIO object to PIL. Here's some code the demonstrates the problem and solution: ``` >>> buff = StringIO.StringIO() >>> buff.write(open('map.png', 'rb').read()) >>> >>> #seek back to the beginning so the whole thing will b...
Python equivalent to atoi / atof
1,665,511
10
2009-11-03T06:02:24Z
1,665,550
7
2009-11-03T06:15:12Z
[ "python" ]
Python loves raising exceptions, which is usually great. But I'm facing some strings I desperately want to convert to integers using C's atoi / atof semantics - e.g. atoi of "3 of 12", "3/12", "3 / 12", should all become 3; atof("3.14 seconds") should become 3.14; atoi(" -99 score") should become -99. Python of course ...
I think the iterative version is better than the recursive version ``` # Iterative def atof(s): s,_,_=s.partition(' ') # eg. this helps by trimming off at the first space while s: try: return float(s) except: s=s[:-1] return 0.0 # Recursive def atof(s): try: ...
Python equivalent to atoi / atof
1,665,511
10
2009-11-03T06:02:24Z
1,665,551
31
2009-11-03T06:15:55Z
[ "python" ]
Python loves raising exceptions, which is usually great. But I'm facing some strings I desperately want to convert to integers using C's atoi / atof semantics - e.g. atoi of "3 of 12", "3/12", "3 / 12", should all become 3; atof("3.14 seconds") should become 3.14; atoi(" -99 score") should become -99. Python of course ...
If you're so keen on getting exactly the functionality of c's `atoi`, why not use it directly? E.g., on my Mac, ``` >>> import ctypes, ctypes.util >>> whereislib = ctypes.util.find_library('c') >>> whereislib '/usr/lib/libc.dylib' >>> clib = ctypes.cdll.LoadLibrary(whereislib) >>> clib.atoi('-99foobar') -99 ``` In Li...
Python list filtering and transformation
1,665,667
9
2009-11-03T06:57:29Z
1,665,694
19
2009-11-03T07:05:11Z
[ "python", "list", "filtering", "transformation" ]
I have a list of library filenames that I need to filter against regular expression and then extract version number from those that match. This is the obvious way to do that: ``` libs = ['libIce.so.33', 'libIce.so.3.3.1', 'libIce.so.32', 'libIce.so.3.2.0'] versions = [] regex = re.compile('libIce.so\.([0-9]+\.[0-9]+\....
How about a list comprehension? ``` In [5]: versions = [m.group(1) for m in [regex.match(lib) for lib in libs] if m] In [6]: versions Out[6]: ['3.3.1', '3.2.0'] ```
Python list filtering and transformation
1,665,667
9
2009-11-03T06:57:29Z
1,666,113
8
2009-11-03T09:05:11Z
[ "python", "list", "filtering", "transformation" ]
I have a list of library filenames that I need to filter against regular expression and then extract version number from those that match. This is the obvious way to do that: ``` libs = ['libIce.so.33', 'libIce.so.3.3.1', 'libIce.so.32', 'libIce.so.3.2.0'] versions = [] regex = re.compile('libIce.so\.([0-9]+\.[0-9]+\....
One more one-liner just to show other ways (I've also cleaned regexp a bit): ``` regex = re.compile(r'^libIce\.so\.([0-9]+\.[0-9]+\.[0-9]+)$') sum(map(regex.findall, libs), []) ``` But note, that your original version is more readable than all suggestions. Is it worth to change?
How do I get the string representation of a variable in python?
1,665,833
5
2009-11-03T07:49:04Z
1,665,916
12
2009-11-03T08:15:11Z
[ "python", "introspection" ]
I have a variable x in python. How can i find the string 'x' from the variable. Here is my attempt: ``` def var(v,c): for key in c.keys(): if c[key] == v: return key def f(): x = '321' print 'Local var %s = %s'%(var(x,locals()),x) x = '123' print 'Global var %s = %s'%(var(x,locals()),x) f() ``` T...
Q: I have a variable x in python. How can i find the string 'x' from the variable. A: If I am understanding your question properly, you want to go from the value of a variable to its name. This is not really possible in Python. In Python, there really isn't any such thing as a "variable". What Python really has are "...
What is the issubclass equivalent of isinstance in python?
1,666,079
8
2009-11-03T08:57:40Z
1,666,096
22
2009-11-03T09:01:43Z
[ "python", "introspection" ]
Given an object, how do I tell if it's a class, and a subclass of a given class Foo? e.g. ``` class Bar(Foo): pass isinstance(Bar(), Foo) # => True issubclass(Bar, Foo) # <--- how do I do that? ```
It works exactly as one would expect it to work... ``` class Foo(): pass class Bar(Foo): pass class Bar2(): pass print issubclass(Bar, Foo) # True print issubclass(Bar2, Foo) # False ``` If you want to know if an *instance* of a class derived from a given base class, you could use: ``` bar_instance =...
Python: OAuth Library
1,666,415
17
2009-11-03T10:14:01Z
1,666,490
12
2009-11-03T10:28:23Z
[ "python", "oauth", "yahoo" ]
Is there a full flegged python library for oauth? I haven't found any that handle reissuing of oauth tokens once they expire (Step 5 on the [Yahoo OAuth flow](http://developer.yahoo.com/oauth/guide/oauth-auth-flow.html)). So what is the most complete? I tried the one from [oauth.net](http://oauth.googlecode.com/svn/co...
I think Leah Culver's [python-oauth](http://www.python-oauth.com/) (that you've already found) is the best starting point even though it's not complete. Leah has a mirror up on github which would make it easy to collaborate: <http://github.com/leah/python-oauth/tree/master/oauth/> **Update**: As it stands today, it l...
Python: OAuth Library
1,666,415
17
2009-11-03T10:14:01Z
16,180,228
11
2013-04-23T22:27:09Z
[ "python", "oauth", "yahoo" ]
Is there a full flegged python library for oauth? I haven't found any that handle reissuing of oauth tokens once they expire (Step 5 on the [Yahoo OAuth flow](http://developer.yahoo.com/oauth/guide/oauth-auth-flow.html)). So what is the most complete? I tried the one from [oauth.net](http://oauth.googlecode.com/svn/co...
[Rauth](https://rauth.readthedocs.org/en/latest/) is the new best answer as far as I'm concerned. Wraps [requests](http://docs.python-requests.org/en/latest/) library and it's well-maintained.
Editing Windows registry, from Python, Under Linux
1,666,690
4
2009-11-03T11:12:24Z
1,667,151
7
2009-11-03T12:50:19Z
[ "python", "windows", "linux", "registry" ]
I am looking for a Python API (or a C API as I am willing to bind) for editing Windows registries from XP to 7 from within a Linux system. The Windows target will be a mounted volume under Linux. I would be willing to code a library if none exists. Therefore, any docs or internals on the registry would be handy too. ...
OK, so you're after a hive file editor? I wrote a `winregistry` module that does this (for both NT and win9x hives). It's not really ready for the public but worked quite well with the data I was using at the time. I'm not sure what state I left it in and I haven't tested it with Win7 hives, but maybe we could get it ...
How to count the number of times something occurs inside a certain string?
1,666,700
7
2009-11-03T11:16:23Z
1,666,709
23
2009-11-03T11:17:59Z
[ "python" ]
In python, I remember there is a function to do this. .count? "The big brown fox is brown" brown = 2.
why not read the docs first, it's very simple: ``` >>> "The big brown fox is brown".count("brown") 2 ```
How to count the number of times something occurs inside a certain string?
1,666,700
7
2009-11-03T11:16:23Z
1,666,756
17
2009-11-03T11:29:54Z
[ "python" ]
In python, I remember there is a function to do this. .count? "The big brown fox is brown" brown = 2.
One thing worth learning if you're a Python beginner is how to use [interactive mode](http://docs.python.org/tutorial/interpreter.html#interactive-mode) to help with this. The first thing to learn is the [`dir` function](http://docs.python.org/library/functions.html) which will tell you the attributes of an object. ``...
How do I mount a filesystem using Python?
1,667,257
12
2009-11-03T13:10:07Z
29,156,997
9
2015-03-19T23:46:12Z
[ "python", "unix" ]
I'm sure this is a easy question, my Google-fu is obviously failing me. How do I mount a filesystem using Python, the equivalent of running the shell command `mount ...`? Obviously I can use `os.system` to run the shell command, but surely there is a nice tidy, Python interface to the *mount* system call. I can't fi...
As others have pointed out, there is no built-in mount function. However, it is easy to create one using ctypes, and this is a bit lighter weight and more reliable than using a shell command: ``` import ctypes import os def mount(source, target, fs, options=''): ret = ctypes.CDLL('libc.so.6', use_errno=True).mount(...
Best way to convert HTML to plaintext using Python
1,668,081
9
2009-11-03T15:33:48Z
1,668,102
8
2009-11-03T15:37:28Z
[ "python", "html", "plaintext" ]
I'm working on a project that involves converting a large amount of HTML content to plain/text. I have a custom-written module that does the job OK, but I'm wondering if there's some standard tools to help get the job done.
[Html2Text](http://www.aaronsw.com/2002/html2text/) seems to be a good option
How to de-import a Python module?
1,668,223
30
2009-11-03T15:55:05Z
1,668,289
14
2009-11-03T16:05:14Z
[ "python" ]
I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system). Firstly I import a sc...
i think [this post](http://mail.python.org/pipermail/tutor/2006-August/048596.html) should help you edit: to secure the availability of this information (in case the link dies or something similar) i will include the original message from the [tutor mailing list](http://mail.python.org/mailman/listinfo/tutor) here: -...
Summing Consecutive Ranges Pythonically
1,668,491
7
2009-11-03T16:32:30Z
1,668,616
9
2009-11-03T16:49:22Z
[ "python" ]
I have a sumranges() function, which sums all the ranges of consecutive numbers found in a tuple of tuples. To illustrate: ``` def sumranges(nums): return sum([sum([1 for j in range(len(nums[i])) if nums[i][j] == 0 or nums[i][j - 1] + 1 != nums[i][j]]) for ...
Consider: ``` >>> nums = ((1, 2, 3, 4), (1, 5, 6), (19, 20, 24, 29, 400)) >>> flat = [[(x - i) for i, x in enumerate(tu)] for tu in nums] >>> print flat [[1, 1, 1, 1], [1, 4, 4], [19, 19, 22, 26, 396]] >>> import itertools >>> print sum(1 for tu in flat for _ in itertools.groupby(tu)) 7 >>> ``` we "flatten" the "incr...
Summing Consecutive Ranges Pythonically
1,668,491
7
2009-11-03T16:32:30Z
1,668,697
7
2009-11-03T16:59:11Z
[ "python" ]
I have a sumranges() function, which sums all the ranges of consecutive numbers found in a tuple of tuples. To illustrate: ``` def sumranges(nums): return sum([sum([1 for j in range(len(nums[i])) if nums[i][j] == 0 or nums[i][j - 1] + 1 != nums[i][j]]) for ...
Just to show something closer to your original code: ``` def sumranges(nums): return sum( (1 for i in nums for j, v in enumerate(i) if j == 0 or v != i[j-1] + 1) ) ``` The idea here was to: * avoid building intermediate lists but use a generator instead, it will save some re...
Summing Consecutive Ranges Pythonically
1,668,491
7
2009-11-03T16:32:30Z
1,668,796
14
2009-11-03T17:12:07Z
[ "python" ]
I have a sumranges() function, which sums all the ranges of consecutive numbers found in a tuple of tuples. To illustrate: ``` def sumranges(nums): return sum([sum([1 for j in range(len(nums[i])) if nums[i][j] == 0 or nums[i][j - 1] + 1 != nums[i][j]]) for ...
My 2 cents: ``` >>> sum(len(set(x - i for i, x in enumerate(t))) for t in nums) 7 ``` It's basically the same idea as descriped in [Alex' post](http://stackoverflow.com/questions/1668491#answer-1668616), but using a `set` instead of `itertools.groupby`, resulting in a shorter expression. Since `set`s are implemented ...
Where does Python first look for files?
1,668,594
3
2009-11-03T16:46:25Z
1,668,612
7
2009-11-03T16:48:54Z
[ "python", "file" ]
I'm trying to learn how to parse .txt files in Python. This has led me to opening the interpreter (terminal > python) and playing around. However, I can't seem to be able to specify the right path. Where does Python first look? This is my first step: ``` f = open("/Desktop/temp/myfile.txt","file1") ``` This blat...
Edit: Oh and yes, your second argument is wrong. Didn't even notice that :) Python looks where you tell it to for file opening. If you open up the interpreter in /home/malcmcmul then that will be the active directory. If you specify a path, that's where it looks. Are you sure /Desktop/temp is a valid path? I don't kn...
Where does Python first look for files?
1,668,594
3
2009-11-03T16:46:25Z
1,668,623
8
2009-11-03T16:50:53Z
[ "python", "file" ]
I'm trying to learn how to parse .txt files in Python. This has led me to opening the interpreter (terminal > python) and playing around. However, I can't seem to be able to specify the right path. Where does Python first look? This is my first step: ``` f = open("/Desktop/temp/myfile.txt","file1") ``` This blat...
That doesn't work as you've got the wrong syntax for `open`. At the interpreter prompt try this: ``` >>> help(open) Help on built-in function open in module __builtin__: open(...) open(name[, mode[, buffering]]) -> file object Open a file using the file() type, returns a file object. ``` So the second argu...
Decorating Instance Methods in Python
1,672,064
3
2009-11-04T06:50:58Z
1,672,094
7
2009-11-04T06:59:36Z
[ "python", "django", "class", "decorator", "instance" ]
Here's the gist of what I'm trying to do. I have a list of objects, and I know they have an instance method that looks like: ``` def render(self, name, value, attrs) # Renders a widget... ``` I want to (essentialy) decorate these functions at runtime, as I'm iterating over the list of objects. So that their render...
``` def decorate_method(f): def wrapper(self, name, value, attrs): self.attrs = attrs return f(self, name, value, attrs) return wrapper def decorate_class(c): for n in dir(c): f = getattr(c, n) if hasattr(f, 'im_func'): setattr(c, n, decorate_method(f.im_func)) ``` You'll probably need som...
text-mine PDF files with Python?
1,672,202
4
2009-11-04T07:30:02Z
1,672,230
11
2009-11-04T07:39:34Z
[ "python", "pdf", "text-mining" ]
Is there a package/library for python that would allow me to open a PDF, and search the text for certain words?
Using [PyPdf2](https://github.com/mstamy2/PyPDF2/) you can use [extractText()](http://code.activestate.com/recipes/511465/) method to extract pdf text and work on it. Update: Changed text to refer to PyPdf2, thanks to @Aditya Kumar for heads up.
Combining 2 lists in python
1,673,005
3
2009-11-04T10:43:54Z
1,673,012
13
2009-11-04T10:44:50Z
[ "python", "list" ]
I have 2 lists each of equal size and am interested to combine these two lists and write it into a file. ``` alist=[1,2,3,5] blist=[2,3,4,5] ``` --the resulting list should be like [(1,2), (2,3), (3,4), (5,5)] After that i want that to be written it to a file. How can i accomplish this?
``` # combine the lists zipped = zip(alist, blist) # write to a file (in append mode) file = open("filename", 'a') for item in zipped: file.write("%d, %d\n" % item) file.close() ``` The resulting output in the file will be: ``` 1,2 2,3 3,4 5,5 ```
What do backticks mean to the python interpreter: `num`
1,673,071
65
2009-11-04T11:00:38Z
1,673,087
89
2009-11-04T11:03:58Z
[ "python", "list-comprehension" ]
I'm playing around with list comprehensions and I came across this little snippet on another site: ``` return ''.join([`num` for num in xrange(loop_count)]) ``` I spent a few minutes trying to replicate the function (by typing) before realising the `` `num` `` bit was breaking it. What does enclosing a statement in ...
Backticks are a deprecated alias for `repr()`. Don't use them any more, the syntax was removed in Python 3.0. Using backticks seems to be faster than using `repr(num)` or `num.__repr__()` in version 2.x. I guess it's because additional dictionary lookup is required in the global namespace (for `repr`), or in the objec...
What do backticks mean to the python interpreter: `num`
1,673,071
65
2009-11-04T11:00:38Z
1,673,233
9
2009-11-04T11:32:57Z
[ "python", "list-comprehension" ]
I'm playing around with list comprehensions and I came across this little snippet on another site: ``` return ''.join([`num` for num in xrange(loop_count)]) ``` I spent a few minutes trying to replicate the function (by typing) before realising the `` `num` `` bit was breaking it. What does enclosing a statement in ...
Backtick quoting is generally non-useful and gone in Python 3. For what it's worth, this: ``` ''.join(map(repr, xrange(10000000))) ``` is marginally faster than the backtick version for me. But worrying about this is probably a premature optimisation.
How to match alphabetical chars without numeric chars with Python regexp?
1,673,749
8
2009-11-04T13:30:16Z
1,673,804
20
2009-11-04T13:40:33Z
[ "python", "regex" ]
Using Python module re, how to get the equivalent of the "\w" (which matches alphanumeric chars) WITHOUT matching the numeric characters (those which can be matched by "[0-9]")? Notice that the basic need is to match any character (including all unicode variation) without numerical chars (which are matched by "[0-9]")...
You want `[^\W\d]`: the group of characters that is not (either a digit or not an alphanumeric). Add an underscore in that negated set if you don't want them either. A bit twisted, if you ask me, but it works. Should be faster than the lookahead alternative.
How can I get the full list of running processes on a Mac from a python app
1,673,874
2
2009-11-04T13:52:51Z
1,673,985
7
2009-11-04T14:11:55Z
[ "python", "osx", "process" ]
I want to get the list of running processes on the Mac, similar to what you get from 'ps -ea' I have tried **os.popen('ps -ea')** but this only lists a small subset of the processes, presumably those owned by the owning shell. Other options I have tried are ``` 'sh -c /bin/ps -ea' 'bash -c /bin/ps -ea' 'csh -c /b...
`os.popen('ps aux')` looks like it's listing all processes for me.
Fastest Way To Remove Duplicates In Lists Python
1,675,321
8
2009-11-04T17:17:36Z
1,675,337
18
2009-11-04T17:19:47Z
[ "python", "list", "sorting" ]
I have two very large lists and to loop through it once takes at least a second and I need to do it 200,000 times. What's the fastest way to remove duplicates in two lists to form one?
This is the fastest way I can think of: ``` import itertools output_list = list(set(itertools.chain(first_list, second_list))) ``` Slight update: As [jcd](http://stackoverflow.com/questions/1675321/fastest-way-to-remove-duplicates-in-lists-python/1675380#1675380) points out, depending on your application, you probabl...
Fastest Way To Remove Duplicates In Lists Python
1,675,321
8
2009-11-04T17:17:36Z
1,675,357
7
2009-11-04T17:22:34Z
[ "python", "list", "sorting" ]
I have two very large lists and to loop through it once takes at least a second and I need to do it 200,000 times. What's the fastest way to remove duplicates in two lists to form one?
As Daniel states, a set cannot contain duplicate entries - so concatenate the lists: ``` list1 + list2 ``` Then convert the new list to a set: ``` set(list1 + list2) ``` Then back to a list: ``` list(set(list1 + list2)) ```
Fastest Way To Remove Duplicates In Lists Python
1,675,321
8
2009-11-04T17:17:36Z
1,675,380
10
2009-11-04T17:25:52Z
[ "python", "list", "sorting" ]
I have two very large lists and to loop through it once takes at least a second and I need to do it 200,000 times. What's the fastest way to remove duplicates in two lists to form one?
I'd recommend something like this: ``` def combine_lists(list1, list2): s = set(list1) s.update(list2) return list(s) ``` This eliminates the problem of creating a monster list of the concatenation of the first two. Depending on what you're doing with the output, don't bother to convert back to a list. I...
Using Google AppEngine as a "cache" for personal websites (wordpress blogs, wikis)
1,675,715
7
2009-11-04T18:22:58Z
1,675,884
9
2009-11-04T18:58:22Z
[ "java", "python", "google-app-engine", "caching" ]
I read an article of an indie game developer who is using Google AppEngine to cache his main site and blog, to protect provide high-availability during traffic spikes (Digg, Slashdot effect). [Wolfire Blog - Google App Engine for Indie Developers](http://blog.wolfire.com/2009/03/google-app-engine-for-indie-developers/...
You could start by taking the code for [DryDrop](http://drydrop.binaryage.com/), which mirrors static pages from a repository hosted on [GitHub](http://github.com/), and making it a more general reverse proxy. For example, you'd need to ensure that POST requests or logged-in users get passed through directly to the pro...
How do I create a namespace package in Python?
1,675,734
89
2009-11-04T18:27:10Z
1,676,069
61
2009-11-04T19:32:17Z
[ "python", "namespaces", "package" ]
In Python, a namespace package allows you to spread Python code among several projects. This is useful when you want to release related libraries as separate downloads. For example, with the directories `Package-1` and `Package-2` in `PYTHONPATH`, ``` Package-1/namespace/__init__.py Package-1/namespace/module1/__init_...
There's a standard module, called [pkgutil](http://docs.python.org/library/pkgutil.html), with which you can 'append' modules to a given namespace. With the directory structure you've provided: ``` Package-1/namespace/__init__.py Package-1/namespace/module1/__init__.py Package-2/namespace/__init__.py Package-2/namesp...
How do I create a namespace package in Python?
1,675,734
89
2009-11-04T18:27:10Z
27,586,272
24
2014-12-21T02:44:44Z
[ "python", "namespaces", "package" ]
In Python, a namespace package allows you to spread Python code among several projects. This is useful when you want to release related libraries as separate downloads. For example, with the directories `Package-1` and `Package-2` in `PYTHONPATH`, ``` Package-1/namespace/__init__.py Package-1/namespace/module1/__init_...
TL;DR: On Python 3.3 you don't have to do anything, just don't put any `__init__.py` in your namespace package directories and it will just work. On pre-3.3, choose the `pkgutil.extend_path()` solution over the `pkg_resources.declare_namespace()` one, because it's future-proof and already compatible with implicit name...
How to combine Pool.map with Array (shared memory) in Python multiprocessing?
1,675,766
28
2009-11-04T18:32:20Z
1,721,911
27
2009-11-12T12:39:03Z
[ "python", "multiprocessing", "shared-memory", "pool" ]
I have a very large (read only) array of data that I want to be processed by multiple processes in parallel. I like the Pool.map function and would like to use it to calculate functions on that data in parallel. I saw that one can use the Value or Array class to use shared memory data between processes. But when I tr...
Trying again as I just saw the bounty ;) Basically I think the error message means what it said - multiprocessing shared memory Arrays can't be passed as arguments (by pickling). It doesn't make sense to serialise the data - the point is the data is shared memory. So you have to make the shared array global. I think i...
Computing article abstracts
1,675,943
5
2009-11-04T19:09:01Z
1,676,000
7
2009-11-04T19:19:31Z
[ "python", "markdown" ]
I'm looking for a way to automatically produce an abstract, basically the first few sentances/paragraphs of a blog entry, to display in a list of articles (which are written in markdown). Currently, I'm doing something like this: ``` def abstract(article, paras=3): return '\n'.join(article.split('\n')[0:paras]) ``...
**EDIT:** You can do something like this: ``` from textwrap import wrap def getAbstract(text, lines=5, screenwidth=100): width = len(' '.join([ line for block in text.splitlines() for line in wrap(block, width=screenwidth) ][:lines])) return text[:width] + '...' ``` ...
Feedparser - retrieve old messages from Google Reader
1,676,223
4
2009-11-04T19:58:04Z
1,676,258
8
2009-11-04T20:02:51Z
[ "python", "rss", "google-reader", "feedparser" ]
I'm using the feedparser library in python to retrieve news from a local newspaper (my intent is to do Natural Language Processing over this corpus) and would like to be able to retrieve many past entries from the RSS feed. I'm not very acquainted with the technical issues of RSS, but I think this should be possible (...
You're only getting a dozen entries or so because that's what the feed contains. If you want historic data you will have to find a feed/database of said data. Check out this [ReadWriteWeb article](http://www.readwriteweb.com/archives/where%5Fto%5Ffind%5Fopen%5Fdata%5Fon%5Fthe.php) for some resources on finding open da...
How to pass flag to gcc in Python setup.py script?
1,676,384
14
2009-11-04T20:24:05Z
1,676,413
11
2009-11-04T20:30:52Z
[ "python", "distutils", "python-c-api" ]
I'm writing a Python extension in C that requires the CoreFoundation framework (among other things). This compiles fine with: ``` gcc -o foo foo.c -framework CoreFoundation -framework Python ``` ("-framework" is an Apple-only gcc extension, but that's okay because I'm using their specific framework anyway) How do I ...
Maybe you need to set `extra_link_args`, too? `extra_compile_args` is used when compiling the source code, `extra_link_args` when linking the result.
Python: How do I get a reference to a module inside the module itself?
1,676,835
82
2009-11-04T21:42:33Z
1,676,860
123
2009-11-04T21:45:59Z
[ "python", "self-reference" ]
How can I get a reference to a module from within that module? Also, how can I get a reference to the package containing that module?
``` import sys current_module = sys.modules[__name__] ```
Python: How do I get a reference to a module inside the module itself?
1,676,835
82
2009-11-04T21:42:33Z
1,676,861
10
2009-11-04T21:46:01Z
[ "python", "self-reference" ]
How can I get a reference to a module from within that module? Also, how can I get a reference to the package containing that module?
If you have a class in that module, then the `__module__` property of the class is the module name of the class. Thus you can access the module via `sys.modules[klass.__module__]`. This is also works for functions.
Overriding the newline generation behaviour of Python's print statement
1,677,424
7
2009-11-04T23:36:17Z
1,677,477
8
2009-11-04T23:48:07Z
[ "python", "printing", "cpython" ]
I have a bunch of legacy code for encoding raw emails that contains a lot of print statements such as ``` print >>f, "Content-Type: text/plain" ``` This is all well and good for emails, but we're now leveraging the same code for outputting HTTP request. The problem is that the Python print statement outputs `'\n'` wh...
(Not sure how/if this fits with the wrapper you intend to use, but in case...) In Python 2.6 (and many preceding versions), you can suppress the newline by adding a comma at the end of the print statement, as in: ``` data = 'some msg\r\n' print data, # note the comma ``` The downside of using this approach however ...
Overriding the newline generation behaviour of Python's print statement
1,677,424
7
2009-11-04T23:36:17Z
1,677,776
10
2009-11-05T01:25:38Z
[ "python", "printing", "cpython" ]
I have a bunch of legacy code for encoding raw emails that contains a lot of print statements such as ``` print >>f, "Content-Type: text/plain" ``` This is all well and good for emails, but we're now leveraging the same code for outputting HTTP request. The problem is that the Python print statement outputs `'\n'` wh...
You should solve your problem now and for forever by defining a new output function. Were print a function, this would have been much easier. I suggest writing a new output function, mimicing as much of the modern print function signature as possible (because reusing a good interface is good), for example: ``` def ou...
How does a classmethod object work?
1,677,468
7
2009-11-04T23:46:36Z
1,677,671
17
2009-11-05T00:49:11Z
[ "python", "metaclass", "class-method" ]
I'm having trouble to understand how a classmethod object works in Python, especially in the context of metaclasses and in `__new__`. In my special case I would like to get the name of a classmethod member, when I iterate through the `members` that were given to `__new__`. For normal methods the name is simply stored ...
A `classmethod` object is a descriptor. You need to understand how descriptors work. In a nutshell, a descriptor is an object which has a method `__get__`, which takes three arguments: `self`, an `instance`, and an `instance type`. During normal attribute lookup, if a looked-up object `A` has a method `__get__`, that...
Multiple figure arrangement using Matplotlib
1,677,571
8
2009-11-05T00:15:39Z
1,685,423
8
2009-11-06T04:28:27Z
[ "python", "matplotlib" ]
Can we control where [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) places figures on the screen? I want to generate four figures (in four separate windows) that do not overlap.
From [IPython](http://en.wikipedia.org/wiki/IPython) you can do the following: ``` figure() get_current_fig_manager().window.wm_geometry("400x600+20+40") ``` Or equivalently in a Python script: ``` import pylab as pl pl.figure() pl.get_current_fig_manager().window.wm_geometry("400x600+20+40") pl.show() ``` Note tha...
Building python 2.6 w/ sqlite3 module if sqlite is installed in non-standard location
1,677,666
8
2009-11-05T00:46:43Z
1,677,758
7
2009-11-05T01:20:32Z
[ "python", "sqlite3" ]
I am trying to build python2.6 with support for the sqlite3 module. I have successfully built and installed the sqlite-amalgamation to a non standard path: ./configure --prefix=/my/non/standard/install/path/sqlite/3.6.20/ make make install I would like the python2.6 build to use this path & build the sqlite3 module. ...
Rather than rebuilding `python`, the simplest way to get the most recent `sqlite3` is to install the [pysqlite](http://pypi.python.org/pypi/pysqlite/) package which is the more up-to-date version of the standard library's `sqlite3` module. It includes support for more recent `sqlite3` features and is upwards compatible...
Proper way of having a unique identifier in Python?
1,677,726
6
2009-11-05T01:10:38Z
1,677,770
9
2009-11-05T01:23:09Z
[ "python", "identifier" ]
Basically, I have a list like: `[START, 'foo', 'bar', 'spam', eggs', END]` and the START/END identifiers are necessary for later so I can compare later on. Right now, I have it set up like this: ``` START = object() END = object() ``` This works fine, but it suffers from the problem of not working with pickling. I tr...
If you want an object that's guaranteed to be unique **and** can also be guaranteed to get restored to exactly the same identify if pickled and unpickled right back, top-level functions, classes, class instances, and if you care about `is` rather than `==` also lists (and other mutables), are all fine. I.e., any of: `...
Python decorators on class members fail when decorator mechanism is a class
1,677,747
7
2009-11-05T01:18:23Z
1,677,774
10
2009-11-05T01:25:28Z
[ "python", "decorator" ]
When creating decorators for use on class methods, I'm having trouble when the decorator mechanism is a class rather than a function/closure. When the class form is used, my decorator doesn't get treated as a bound method. Generally I prefer to use the function form for decorators but in this case I have to use an exi...
Your `WrapperClass` needs to be a descriptor (just like a function is!), i.e., supply appropriate special methods `__get__` and `__set__`. [This how-to guide](http://users.rcn.com/python/download/Descriptor.htm) teaches all you need to know about that!-)
CherryPy3 and IIS 6.0
1,677,828
4
2009-11-05T01:38:55Z
1,680,636
10
2009-11-05T13:35:51Z
[ "python", "iis-6", "cherrypy", "isapi-wsgi" ]
I have a small Python web application using the Cherrypy framework. I am by no means an expert in web servers. I got Cherrypy working with Apache using mod\_python on our Ubuntu server. This time, however, I have to use Windows 2003 and IIS 6.0 to host my site. The site runs perfectly as a stand alone server - I am j...
I run CherryPy behind my IIS sites. There are several tricks to get it to work. 1. When running as the IIS Worker Process identity, you won't have the same permissions as you do when you run the site from your user process. Things will break. In particular, anything that wants to write to the file system will probably...
Komodo Python auto complete: type inference by variable metadata?
1,678,953
7
2009-11-05T07:40:06Z
1,681,587
8
2009-11-05T16:07:11Z
[ "python", "autocomplete", "komodo" ]
I'm using Komodo Edit for [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29) development, and I want to get the best out of the auto complete. If I do this: ``` a = A() a. ``` I can see a list of members of A. But if I do this: ``` a = [A()] b = a[0] b. ``` It does not work. I want to be...
This doesn't really answer your question, but with [Wing IDE](http://en.wikipedia.org/wiki/Wing%5FIDE) you can give hints to the type analyzer with `assert isinstance(b, A)`. See [here](http://www.wingware.com/doc/edit/helping-wing-analyze-code). I haven't found a way to do it with Komodo, though apparently it's [possi...
How to plot an image with non-linear y-axis with Matplotlib using imshow?
1,679,126
8
2009-11-05T08:32:02Z
1,679,455
8
2009-11-05T09:48:03Z
[ "python", "matplotlib" ]
How can I plot an 2D array as an image with [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) having the y scale relative to the power of two of the y value? For instance the first row of my array will have a height in the image of 1, the second row will have a height of 4, etc. (units are irrelevant) It's not sim...
Have you tried to transform the axis? For example: ``` ax = subplot(111) ax.yaxis.set_ticks([0, 2, 4, 8]) imshow(data) ``` This means there must be gaps in the data for the non-existent coordinates, unless there is a way to provide a transform function instead of just lists (never tried). **Edit**: I admit it was j...
How to open a file with the standard application?
1,679,798
16
2009-11-05T10:59:30Z
1,679,887
9
2009-11-05T11:18:27Z
[ "python", "windows", "linux" ]
My application prints a PDF to a temporary file. How can I open that file with the default application in Python? I need a solution for * Windows * Linux (Ubuntu with Xfce if there's nothing more general.) ### Related * [Open document with default application in Python](http://stackoverflow.com/questions/434597/ope...
on windows it works with `os.system('start <myFile>')`. On Mac (I know you didn't ask...) it's `os.system('open <myFile>')`
How to open a file with the standard application?
1,679,798
16
2009-11-05T10:59:30Z
1,679,895
22
2009-11-05T11:19:33Z
[ "python", "windows", "linux" ]
My application prints a PDF to a temporary file. How can I open that file with the default application in Python? I need a solution for * Windows * Linux (Ubuntu with Xfce if there's nothing more general.) ### Related * [Open document with default application in Python](http://stackoverflow.com/questions/434597/ope...
[os.startfile](http://docs.python.org/library/os.html#os.startfile) is only available for windows for now, but [xdg-open](http://portland.freedesktop.org/xdg-utils-1.0/xdg-open.html) will be available on any unix client running X. ``` if sys.platform == 'linux2': subprocess.call(["xdg-open", file]) else: os.st...
Python: How much space does each element of a list take?
1,680,436
8
2009-11-05T13:04:35Z
1,680,540
9
2009-11-05T13:21:18Z
[ "python", "memory", "list", "performance" ]
I need a very large list, and am trying to figure out how big I can make it so that it still fits in 1-2GB of RAM. I am using the CPython implementation, on 64 bit (x86\_64). *Edit: thanks to bua's answer, I have filled in some of the more concrete answers.* What is the space (memory) usage of (in bytes): * the list...
point to start: ``` >>> import sys >>> a=list() >>> type(a) <type 'list'> >>> sys.getsizeof(a) 36 >>> b=1 >>> type(b) <type 'int'> >>> sys.getsizeof(b) 12 ``` and from python help: ``` >>> help(sys.getsizeof) Help on built-in function getsizeof in module sys: getsizeof(...) getsizeof(object, default) -> int ...
How do I avoid having class data shared among instances?
1,680,528
61
2009-11-05T13:19:55Z
1,680,545
10
2009-11-05T13:22:00Z
[ "python", "class" ]
What I want is this behavior: ``` class a: list=[] y=a() x=a() x.list.append(1) y.list.append(2) x.list.append(3) y.list.append(4) print x.list [1,3] print y.list [2,4] ``` of course, what really happens when I print is: ``` print x.list [1,2,3,4] print y.list [1,2,3,4] ``` clearly they are ...
You declared "list" as a "class level property" and not "instance level property". In order to have properties scoped at the instance level, you need to initialize them through referencing with the "self" parameter in the `__init__` method (or elsewhere depending on the situation). You don't strictly have to initializ...
How do I avoid having class data shared among instances?
1,680,528
61
2009-11-05T13:19:55Z
1,680,555
70
2009-11-05T13:23:13Z
[ "python", "class" ]
What I want is this behavior: ``` class a: list=[] y=a() x=a() x.list.append(1) y.list.append(2) x.list.append(3) y.list.append(4) print x.list [1,3] print y.list [2,4] ``` of course, what really happens when I print is: ``` print x.list [1,2,3,4] print y.list [1,2,3,4] ``` clearly they are ...
You want this: ``` class a: def __init__(self): self.list = [] ``` Declaring the variables inside the class declaration makes them "class" members and not instance members. Declaring them inside the `__init__` method makes sure that a new instance of the members is created alongside every new instance of ...
Custom exception handling in Python
1,681,036
3
2009-11-05T14:49:49Z
1,681,086
8
2009-11-05T14:59:04Z
[ "python", "exception", "exception-handling" ]
I have two modules, main and notmain. I declared my custom exception in main module and want to catch it. This exception is raised in notmain module. The problem is I can't catch my exception raised in notmain module. main.py: ``` class MyException(Exception): pass m = __import__('notmain') try: m.func() exc...
Your module `main` is imported twice (as `main` and `__main__`), each having its own class `MyException`. You should consider redesigning your application to avoid circular imports.
Python: Platform independent way to modify PATH environment variable
1,681,208
43
2009-11-05T15:17:39Z
1,681,244
78
2009-11-05T15:21:57Z
[ "python", "path", "cross-platform", "environment-variables" ]
Is there a way to modify the PATH environment variable in a platform independent way using python? Something similar to os.path.join()?
You should be able to modify `os.environ`. Since `os.pathsep` is the character to separate different paths, you should use this to append each new path: ``` os.environ["PATH"] += os.pathsep + path ``` or, if there are several paths to add in a list: ``` os.environ["PATH"] += os.pathsep + os.pathsep.join(pathlist) `...
Python: Platform independent way to modify PATH environment variable
1,681,208
43
2009-11-05T15:17:39Z
3,952,557
12
2010-10-17T08:36:37Z
[ "python", "path", "cross-platform", "environment-variables" ]
Is there a way to modify the PATH environment variable in a platform independent way using python? Something similar to os.path.join()?
(Since comments can't contain formatting, I have to put this in an answer, but I feel like it's an important point to make. This is really a comment on [the comment about there being no equivalent to 'export'](http://stackoverflow.com/questions/1681208/python-platform-independent-way-to-modify-path-environment-variable...
how code a function similar to itertools.product in python 2.5
1,681,269
5
2009-11-05T15:26:28Z
1,681,286
12
2009-11-05T15:28:41Z
[ "python" ]
I have a list of tuples, e.g: ``` A=[(1,2,3), (3,5,7,9), (7)] ``` and want to generate all permutations with one item from each tuple. ``` 1,3,7 1,5,7 1,7,7 ... 3,9,7 ``` I can have any number of tuples and a tuple can have any number of elements. And I can't use `itertools.product()` because python 2.5.
docs of [`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product) have an example of how to implement it in py2.5: ``` def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(t...
How to debug a MemoryError in Python? Tools for tracking memory use?
1,681,836
10
2009-11-05T16:36:26Z
1,681,869
9
2009-11-05T16:39:43Z
[ "python", "memory-management", "profiling", "out-of-memory" ]
I have a Python program that dies with a MemoryError when I feed it a large file. Are there any tools that I could use to figure out what's using the memory? This program ran fine on smaller input files. The program obviously needs some scalability improvements; I'm just trying to figure out where. "Benchmark before y...
[Heapy](http://guppy-pe.sourceforge.net/#Heapy) is a memory profiler for Python, which is the type of tool you need.
How non blocking read/write throught remote FileSystem
1,682,515
5
2009-11-05T18:16:57Z
1,682,669
7
2009-11-05T18:40:50Z
[ "python", "networking", "filesystems", "twisted" ]
Is there a way to write and read files on a remote filesystem (such as NFS, SSHFS, or sambafs) in a way that read or write or even open return immediately with an error code? In fact I'm using Twisted and I want to know whether there is a safe way to access remote files without blocking my reactor.
In Twisted, for remote filesystems just like for any other blocking calls, you can use [threads.deferToThread](http://blog.ianbicking.org/twisted-and-threads.html) -- a reasonably elegant way to deal with pesky blocking syscalls!-)
Why does Python's list.append evaluate to false?
1,682,567
16
2009-11-05T18:24:09Z
1,682,572
16
2009-11-05T18:25:20Z
[ "python" ]
Is there a reason being `list.append` evaluating to false? Or is it just the C convention of returning 0 when successful that comes into play? ``` >>> u = [] >>> not u.append(6) True ```
`None` evaluates to `False` and in python a function that does not return anything is assumed to have returned `None`. If you type: ``` >> print u.append(6) None ``` Tadaaam :)
Why does Python's list.append evaluate to false?
1,682,567
16
2009-11-05T18:24:09Z
1,682,601
27
2009-11-05T18:29:40Z
[ "python" ]
Is there a reason being `list.append` evaluating to false? Or is it just the C convention of returning 0 when successful that comes into play? ``` >>> u = [] >>> not u.append(6) True ```
Most Python methods that mutate a container in-place return `None` -- an application of the principle of [Command-query separation](http://en.wikipedia.org/wiki/Command-query%5Fseparation). (Python's always reasonably pragmatic about things, so a few mutators do return a usable value when getting it otherwise would be ...
What does the ** maths operator do in Python?
1,683,008
11
2009-11-05T19:38:42Z
1,683,024
26
2009-11-05T19:40:20Z
[ "python", "syntax", "operators" ]
What does this mean in Python: ``` sock.recvfrom(2**16) ``` I know what sock is, and I get the gist of the `recvfrom` function, but what the heck is `2**16`? Specifically, the two asterisk/double asterisk operator? --- *(english keywords, because it's hard to search for this: times-times star-star asterisk-asterisk...
It is the power operator, see this reference: <http://www.webreference.com/programming/python/> It is equivalent to 216 = 65536
Django: Streaming dynamically generated XML output through an HttpResponse
1,683,144
4
2009-11-05T19:58:30Z
1,684,265
11
2009-11-05T23:01:03Z
[ "python", "xml", "django" ]
recently I wanted to return through a Django view a dynamically generated XML tree. The module I use for XML manipulation is the usual cElementTree. I think I tackled what I wanted by doing the following: ``` def view1(request): resp = HttpResponse(g()) return resp def g(): root = Element("ist") li...
About middlewares "breaking" streaming: CommonMiddleware will try to consume the whole iterator *if* you set `USE_ETAGS = True` in settings. But in modern Django (1.1) there's a better way to do conditional get than CommonMiddleware + ConditionalGetMiddleware -- [`condition` decorator](http://docs.djangoproject.com/en...
'getattr(): attribute name must be string' error in admin panel for a model with an ImageField
1,683,362
3
2009-11-05T20:27:17Z
1,683,591
11
2009-11-05T21:03:41Z
[ "python", "django", "django-models", "django-admin" ]
I have the following model set up: ``` class UserProfile(models.Model): "Additional attributes for users." url = models.URLField() location = models.CharField(max_length=100) user = models.ForeignKey(User, unique=True) avatar = models.ImageField(upload_to='/home/something/www/avatars', height_field...
Your problem is with `height_field=80` and `width_field=80` these should not contain the height and width you require but rather the names of fields in your model that can have the values for height and width save in them. As explained in the Django documentation for the [ImagedField](http://docs.djangoproject.com/en/...
Sort a multidimensional list by a variable number of keys
1,683,775
9
2009-11-05T21:30:45Z
1,683,863
7
2009-11-05T21:44:13Z
[ "python", "sorting" ]
I've read [this post](http://stackoverflow.com/questions/1516249/python-list-sorting-with-multiple-attributes-and-mixed-order) and is hasn't ended up working for me. *Edit: the functionality I'm describing is just like the sorting function in Excel... if that makes it any clearer* Here's my situation, I have a tab-de...
This will sort by columns 2 and 3: ``` a.sort(key=operator.itemgetter(2,3)) ```
Sort a multidimensional list by a variable number of keys
1,683,775
9
2009-11-05T21:30:45Z
1,683,900
10
2009-11-05T21:50:02Z
[ "python", "sorting" ]
I've read [this post](http://stackoverflow.com/questions/1516249/python-list-sorting-with-multiple-attributes-and-mixed-order) and is hasn't ended up working for me. *Edit: the functionality I'm describing is just like the sorting function in Excel... if that makes it any clearer* Here's my situation, I have a tab-de...
``` import operator: def sortByColumn(bigList, *args) bigList.sort(key=operator.itemgetter(*args)) # sorts the list in place ```
Limitations of TEMP directory in Windows?
1,683,831
4
2009-11-05T21:39:30Z
1,683,914
7
2009-11-05T21:52:52Z
[ "python", "windows", "temporary-files" ]
I have an application written in Python that's writing large amounts of data to the `%TEMP%` folder. Oddly, every once and awhile, it dies, returning `IOError: [Errno 28] No space left on device`. The drive has *plenty* of free space, `%TEMP%` is not its own partition, I'm an administrator, and the system has no quotas...
What is the exact error you encounter? Are you [creating too many temp files](http://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename%28VS.80%29.aspx)? > The GetTempFileName method will raise > an IOException if it is used to > create more than **65535** files without > deleting previous temporary file...
Is it possible to delete a method from an object (not class) in python?
1,684,099
5
2009-11-05T22:29:27Z
1,684,183
9
2009-11-05T22:44:35Z
[ "python" ]
I have a class with a few methods, some of which are only valid when the object is in a particular state. I would like to have the methods simply not be bound to the objects when they're not in a suitable state, so that I get something like: ``` >>> wiz=Wizard() >>> dir(wiz) ['__doc__', '__module__', 'addmana'] >>> wi...
This isn't directly answering your question, but I think a better approach to solving this problem would be to **not** add/remove the member method `domagic` on your `wiz` object: What I would do instead is within the `domagic` method, add a condition that checks for the relevant state of the `wiz` object, and then on...
Is it possible to delete a method from an object (not class) in python?
1,684,099
5
2009-11-05T22:29:27Z
1,684,267
8
2009-11-05T23:01:14Z
[ "python" ]
I have a class with a few methods, some of which are only valid when the object is in a particular state. I would like to have the methods simply not be bound to the objects when they're not in a suitable state, so that I get something like: ``` >>> wiz=Wizard() >>> dir(wiz) ['__doc__', '__module__', 'addmana'] >>> wi...
You can't delete a class method from an instance of that class because the instance doesn't *have* that method. The protocol is: if `o` is an instance of class `Foo`, and I call `o.bar()`, first `o` is examined to see if it has a method named `bar`. If it doesn't, then `Foo` is examined. The methods aren't bound to the...
BeautifulSoup - extracting attribute values
1,684,120
8
2009-11-05T22:32:52Z
1,684,140
9
2009-11-05T22:36:27Z
[ "python", "beautifulsoup" ]
If Beautiful Soup gives me an anchor tag like this: ``` <a class="blah blah" id="blah blah" href="link.html"></a> ``` How would I retrieve the value of the `href` attribute?
If you already have the anchor, grab the `href` attribute like this: ``` href = anchor["href"] ```
Call Ruby or Python API in C# .NET
1,684,145
8
2009-11-05T22:37:12Z
1,684,954
9
2009-11-06T02:01:16Z
[ "c#", ".net", "python", "ruby" ]
I have a lot of APIs/Classes that I have developed in Ruby and Python that I would like to use in my .NET apps. Is it possible to instantiate a Ruby or Python Object in C# and call its methods? It seems that libraries like IronPython do the opposite of this. Meaning, they allow Python to utilize .NET objects, but not ...
This is one of the two things that the [Dynamic Language Runtime](http://DLR.CodePlex.Com/) is supposed to do: everybody thinks that the DLR is only for language implementors to make it easier to implement dynamic languages on the CLI. But, it is also for application writers, to make it easier to host dynamic languages...
Acessing other py file's class
1,684,274
2
2009-11-05T23:02:43Z
1,684,280
10
2009-11-05T23:03:53Z
[ "python" ]
I have two files: a.py b.py How can I access my ABC123 class defined in a.py from b.py?
``` import a x = a.ABC123() ``` or ``` from a import ABC123 x = ABC123() ``` will do the job, as long as `a.py` and `b.py` are in the same directory, or if `a.py` is in a directory in `sys.path` or in a directory in your environment's `$PYTHONPATH`. If neither of those is the case, you might want to read up on relat...
How to set attributes using property decorators?
1,684,828
31
2009-11-06T01:27:33Z
1,684,851
71
2009-11-06T01:33:43Z
[ "python" ]
This code returns an error: AttributeError: can't set attribute This is really a pity because I would like to use properties instead of calling the methods. Does anyone know why this simple example is not working? ``` #!/usr/bin/python2.6 class Bar( object ): """ ... """ @property def value(): ...
Is this what you want? ``` class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value ``` Taken from <http://docs.python.org/library/functions.html#property>.
Python specify popen working directory via argument
1,685,157
86
2009-11-06T03:06:21Z
1,685,166
120
2009-11-06T03:10:03Z
[ "python", "subprocess", "popen" ]
Is there a way to specify the running directory of command in python's `subprocess.Popen()` ? For example: ``` Popen('c:\mytool\tool.exe',workingdir='d:\test\local') ``` My python script is located in `C:\programs\python` Is is possible to run `C:\mytool\tool.exe` in the directory `D:\test\local` ? How do I set th...
`subprocess.Popen` [takes a `cwd` argument](http://docs.python.org/library/subprocess.html#using-the-subprocess-module) to set the Current Working Directory; you'll also want to escape your backslashes (`'d:\\test\\local'`), or use `r'd:\test\local'` so that the backslashes aren't interpreted as escape sequences by Pyt...
accurately measure time python function takes
1,685,221
37
2009-11-06T03:25:04Z
1,685,245
8
2009-11-06T03:31:59Z
[ "python", "time", "profiling", "timeit" ]
I need to measure the time certain parts of my program take (not for debugging but as a feature in the output). Accuracy is important because the total time will be a fraction of a second. I was going to use the [time module](http://docs.python.org/library/time.html) when I came across [timeit](http://docs.python.org/...
The timeit module looks like it's designed for doing performance testing of algorithms, rather than as simple monitoring of an application. Your best option is probably to use the time module, call `time.time()` at the beginning and end of the segment you're interested in, and subtract the two numbers. Be aware that th...
accurately measure time python function takes
1,685,221
37
2009-11-06T03:25:04Z
1,685,263
23
2009-11-06T03:36:26Z
[ "python", "time", "profiling", "timeit" ]
I need to measure the time certain parts of my program take (not for debugging but as a feature in the output). Accuracy is important because the total time will be a fraction of a second. I was going to use the [time module](http://docs.python.org/library/time.html) when I came across [timeit](http://docs.python.org/...
According to the Python [documentation](http://docs.python.org/library/timeit.html) it has to do with the accuracy of the time function in different operating systems: > The default timer function is platform > dependent. On Windows, time.clock() > has microsecond granularity but > time.time()‘s granularity is 1/60t...
accurately measure time python function takes
1,685,221
37
2009-11-06T03:25:04Z
1,685,337
27
2009-11-06T04:05:56Z
[ "python", "time", "profiling", "timeit" ]
I need to measure the time certain parts of my program take (not for debugging but as a feature in the output). Accuracy is important because the total time will be a fraction of a second. I was going to use the [time module](http://docs.python.org/library/time.html) when I came across [timeit](http://docs.python.org/...
You could build a timing context (see [PEP 343](http://www.python.org/dev/peps/pep-0343/)) to measure blocks of code pretty easily. ``` from __future__ import with_statement import time class Timer(object): def __enter__(self): self.__start = time.time() def __exit__(self, type, value, traceback): ...
Why we should perfer to store the serialized data not the raw code to DB?
1,685,330
2
2009-11-06T04:03:15Z
1,685,493
10
2009-11-06T04:58:19Z
[ "python", "database", "serialization" ]
If we have some code(a data structure) which should be stored in DB, someone always suggests us to store the serialized data not the raw code string. So I'm not so sure why we should prefer the serialized data. Give a simple instance(in python): we've got a field which will store a dict of python, like ``` { "name"...
> Or we can store the dict string > directly to DB without serializing. There is no such thing as "the dict string". There are many ways to serialize a dict into a string; you may be thinking of `repr`, possibly as `eval` as the way to get the dict back (you mention `exec`, but that's simply absurd: what statement wou...
Possible to use more than one argument on __getitem__?
1,685,389
12
2009-11-06T04:21:49Z
1,685,412
27
2009-11-06T04:27:31Z
[ "python" ]
I am trying to use ``` __getitem__(self, x, y): ``` on my Matrix class, but it seems to me it doesn't work (I still don't know very well to use python). I'm calling it like this: ``` print matrix[0,0] ``` Is it possible at all to use more than one argument? Thanks. Maybe I can use only one argument but pass it as a...
`__getitem__` only accepts one argument (other than self), so you get passed a tuple. You can do this: ``` class matrix: def __getitem__(self, pos): x,y = pos return "fetching %s, %s" % (x, y) m = matrix() print m[1,2] ``` outputs ``` fetching 1, 2 ``` See [http://docs.python.org/reference/dat...
Possible to use more than one argument on __getitem__?
1,685,389
12
2009-11-06T04:21:49Z
1,685,450
19
2009-11-06T04:37:41Z
[ "python" ]
I am trying to use ``` __getitem__(self, x, y): ``` on my Matrix class, but it seems to me it doesn't work (I still don't know very well to use python). I'm calling it like this: ``` print matrix[0,0] ``` Is it possible at all to use more than one argument? Thanks. Maybe I can use only one argument but pass it as a...
Indeed, when you execute `bla[x,y]`, you're calling `type(bla).__getitem__(bla, (x, y))` -- Python automatically forms the tuple for you and passes it on to `__getitem__` as the second argument (the first one being its `self`). There's no good way[1] to express that `__getitem__` wants more arguments, but also no need ...