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 run Python egg files directly without installing them?
1,264,447
30
2009-08-12T06:07:31Z
1,264,625
16
2009-08-12T07:05:03Z
[ "python", "egg" ]
Is it possible to run Python egg files directly as you can run jar files with Java? For example, with Java you might dos something like: ``` $ java -jar jar-file ```
A [python egg](http://peak.telecommunity.com/DevCenter/PythonEggs) is a "a single-file importable distribution format". Which is typically a python package. You can import the package in the egg as long as you know it's name and it's in your path. You can execute a package using the "-m" option and the package name. ...
How to run Python egg files directly without installing them?
1,264,447
30
2009-08-12T06:07:31Z
2,898,358
13
2010-05-24T16:08:31Z
[ "python", "egg" ]
Is it possible to run Python egg files directly as you can run jar files with Java? For example, with Java you might dos something like: ``` $ java -jar jar-file ```
As of Python 2.6, you can use `python some.egg` and it will be executed if it includes a module named `__main__`. For earlier versions of Python, you can use `PYTHONPATH=some.egg python -m some module`, and `somemodule` from the egg will be run as the main module. (Note: if you're on Windows, you'd need to do a separa...
Python Class Factory to Produce simple Struct-like classes
1,264,833
9
2009-08-12T07:57:57Z
1,264,843
16
2009-08-12T08:01:06Z
[ "python", "struct", "class-factory" ]
While investigating Ruby I came across this to create a simple Struct-like class: ``` Person = Struct.new(:forname, :surname) person1 = Person.new('John', 'Doe') puts person1 #<struct Person forname="John", surname="Doe"> ``` Which raised a few Python questions for me. I have written a [VERY] basic clone of this mec...
If you're using Python 2.6, try the standard library [namedtuple](http://docs.python.org/library/collections.html#collections.namedtuple) class. ``` >>> from collections import namedtuple >>> Person = namedtuple('Person', ('forename', 'surname')) >>> person1 = Person('John', 'Doe') >>> person2 = Person(forename='Adam'...
Python Class Factory to Produce simple Struct-like classes
1,264,833
9
2009-08-12T07:57:57Z
1,264,975
8
2009-08-12T08:43:38Z
[ "python", "struct", "class-factory" ]
While investigating Ruby I came across this to create a simple Struct-like class: ``` Person = Struct.new(:forname, :surname) person1 = Person.new('John', 'Doe') puts person1 #<struct Person forname="John", surname="Doe"> ``` Which raised a few Python questions for me. I have written a [VERY] basic clone of this mec...
If you're running python <2.6 or would like to extend your class to do more stuff, I would suggest using the `type()` builtin. This has the advantage over your solution in that the setting up of `__dict__` happens at class creation rather than instantiation. It also doesn't define an `__init__` method and thus doesn't ...
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
138
2009-08-12T11:46:13Z
1,265,696
235
2009-08-12T11:52:09Z
[ "python", "string", "integer" ]
Is there any way to tell whether a **string** represents an integer (e.g., `'3'`, `'-17'` but not `'3.14'` or `'asfasfas'`) Without using a try/except mechanism? ``` is_int('3.14') = False is_int('-7') = True ```
with positive integers you could use [`.isdigit`](http://docs.python.org/library/stdtypes.html#str.isdigit): ``` >>> '16'.isdigit() True ``` it doesn't work with negative integers though. suppose you could try the following: ``` >>> s = '-17' >>> s.startswith('-') and s[1:].isdigit() True ``` it won't work with `'1...
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
138
2009-08-12T11:46:13Z
1,265,709
16
2009-08-12T11:54:20Z
[ "python", "string", "integer" ]
Is there any way to tell whether a **string** represents an integer (e.g., `'3'`, `'-17'` but not `'3.14'` or `'asfasfas'`) Without using a try/except mechanism? ``` is_int('3.14') = False is_int('-7') = True ```
Use a regular expression: ``` import re def RepresentsInt(s): return re.match(r"[-+]?\d+$", s) is not None ``` If you must accept decimal fractions also: ``` def RepresentsInt(s): return re.match(r"[-+]?\d+(\.0*)?$", s) is not None ``` For improved performance if you're doing this often, compile the regular...
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
138
2009-08-12T11:46:13Z
1,267,145
137
2009-08-12T16:05:28Z
[ "python", "string", "integer" ]
Is there any way to tell whether a **string** represents an integer (e.g., `'3'`, `'-17'` but not `'3.14'` or `'asfasfas'`) Without using a try/except mechanism? ``` is_int('3.14') = False is_int('-7') = True ```
If you're really just annoyed at using `try/except`s all over the place, please just write a helper function: ``` def RepresentsInt(s): try: int(s) return True except ValueError: return False >>> print RepresentsInt("+123") True >>> print RepresentsInt("10.0") False ``` It's going to...
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
138
2009-08-12T11:46:13Z
4,894,182
7
2011-02-04T03:07:14Z
[ "python", "string", "integer" ]
Is there any way to tell whether a **string** represents an integer (e.g., `'3'`, `'-17'` but not `'3.14'` or `'asfasfas'`) Without using a try/except mechanism? ``` is_int('3.14') = False is_int('-7') = True ```
The proper RegEx solution would combine the ideas of Greg Hewgill and Nowell, but not use a global variable. You can accomplish this by attaching an attribute to the method. Also, I know that it is frowned upon to put imports in a method, but what I'm going for is a "lazy module" effect like <http://peak.telecommunity....
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
138
2009-08-12T11:46:13Z
9,859,202
40
2012-03-25T09:41:13Z
[ "python", "string", "integer" ]
Is there any way to tell whether a **string** represents an integer (e.g., `'3'`, `'-17'` but not `'3.14'` or `'asfasfas'`) Without using a try/except mechanism? ``` is_int('3.14') = False is_int('-7') = True ```
You know, I've found (and I've tested this over and over) that try/except does not perform all that well, for whatever reason. I frequently try several ways of doing things, and I don't think I've ever found a method that uses try/except to perform the best of those tested, in fact it seems to me those methods have usu...
Python non-trivial C++ Extension
1,266,570
4
2009-08-12T14:36:05Z
1,266,621
10
2009-08-12T14:42:17Z
[ "c++", "python", "swig", "distutils", "py++" ]
I have fairly large C++ library with several sub-libraries that support it, and I need to turn the whole thing into a python extension. I'm using distutils because it needs to be cross-platform, but if there's a better tool I'm open to suggestions. Is there a way to make distutils first compile the sub-libraries, and ...
I do just this with a massive C++ library in our product. There are several tools out there that can help you automate the task of writing bindings: the most popular is [SWIG](http://www.swig.org/), which has been around a while, is used in lots of projects, and generally works very well. The biggest thing against SWI...
Does PHP have an equivalent to Python's list comprehension syntax?
1,266,911
46
2009-08-12T15:26:07Z
1,266,942
56
2009-08-12T15:32:02Z
[ "php", "python", "arrays" ]
Python has syntactically sweet list comprehensions: ``` S = [x**2 for x in range(10)] print S; [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ``` In PHP I would need to do some looping: ``` $output = array(); $Nums = range(0,9); foreach ($Nums as $num) { $out[] = $num*=$num; } print_r($out); ``` to get: Array ( [0] =>...
Maybe something like this? ``` $out=array_map(function($x) {return $x*$x;}, range(0, 9)) ``` This will work in PHP 5.3+, in an older version you'd have to define the callback for [array\_map](http://php.net/array%5Fmap) separately ``` function sq($x) {return $x*$x;} $out=array_map('sq', range(0, 9)); ```
Python: remove lots of items from a list
1,267,260
10
2009-08-12T16:28:46Z
1,267,318
19
2009-08-12T16:40:11Z
[ "python" ]
I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around. I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple in ...
You'll have to measure, but I can imagine this to be more performant: ``` myList = filter(lambda x: myDict.get(x[1], None) != x[0], myList) ``` because the lookup happens in the dict, which is more suited for this kind of thing. Note, though, that this will create a new list before removing the old one; so there's a ...
Python: remove lots of items from a list
1,267,260
10
2009-08-12T16:28:46Z
1,274,668
9
2009-08-13T21:23:00Z
[ "python" ]
I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around. I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple in ...
To remove about 10,000 tuples from a list of about 1,000,000, if the values are hashable, the fastest approach should be: ``` totoss = set((v,k) for (k,v) in myDict.iteritems()) myList[:] = [x for x in myList if x not in totoss] ``` The preparation of the set is a small one-time cost, wich saves doing tuple unpacking...
What's the best way to do literate programming in Python on Windows?
1,267,280
31
2009-08-12T16:32:54Z
2,887,123
9
2010-05-22T06:01:40Z
[ "python", "windows", "literate-programming", "noweb" ]
I've been playing with various ways of doing literate programming in Python. I like [`noweb`](http://www.cs.tufts.edu/~nr/noweb/), but I have two main problems with it: first, it is hard to build on Windows, where I spend about half my development time; and second, it requires me to indent each chunk of code as it will...
I have written Pweave <http://mpastell.com/pweave>, that is aimed for dynamic report generation and uses noweb syntax. It is a pure python script so it also runs on Windows. It doesn't fix your indent problem, but maybe you can modify it for that, the code is really quite simple.
What's the best way to do literate programming in Python on Windows?
1,267,280
31
2009-08-12T16:32:54Z
11,155,300
7
2012-06-22T11:27:27Z
[ "python", "windows", "literate-programming", "noweb" ]
I've been playing with various ways of doing literate programming in Python. I like [`noweb`](http://www.cs.tufts.edu/~nr/noweb/), but I have two main problems with it: first, it is hard to build on Windows, where I spend about half my development time; and second, it requires me to indent each chunk of code as it will...
You could use org-mode and babel-tangle. That works quite well, since you can give :noweb-ref to source blocks. Here’s a minimal example: [Activate org-babel-tangle](http://orgmode.org/worg/org-contrib/babel/intro.html#literate-programming), then put this into the file `noweb-test.org`: ``` #+begin_src python :exp...
What's the best way to do literate programming in Python on Windows?
1,267,280
31
2009-08-12T16:32:54Z
22,131,669
8
2014-03-02T18:38:13Z
[ "python", "windows", "literate-programming", "noweb" ]
I've been playing with various ways of doing literate programming in Python. I like [`noweb`](http://www.cs.tufts.edu/~nr/noweb/), but I have two main problems with it: first, it is hard to build on Windows, where I spend about half my development time; and second, it requires me to indent each chunk of code as it will...
The de-facto standard in the community is IPython notebooks. Excellent example in which Peter Norvig demonstrates algorithms to solve the Travelling Salesman Problem: <http://nbviewer.ipython.org/url/norvig.com/ipython/TSPv3.ipynb> More examples listed at <https://github.com/ipython/ipython/wiki/A-gallery-of-interest...
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
455
2009-08-12T18:25:15Z
1,267,883
70
2009-08-12T18:26:57Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
I have two integer values `a` and `b`, but I need their ratio in floating point. I know that `a<b` and I want to calculate `a/b`, so if I use integer division I'll always get 0 with a remainder of `a`. How can I force `c` to be a floating point number in Python in the following? ``` c = a / b ```
``` c = a / (b * 1.0) ```
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
455
2009-08-12T18:25:15Z
1,267,890
523
2009-08-12T18:28:02Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
I have two integer values `a` and `b`, but I need their ratio in floating point. I know that `a<b` and I want to calculate `a/b`, so if I use integer division I'll always get 0 with a remainder of `a`. How can I force `c` to be a floating point number in Python in the following? ``` c = a / b ```
You can cast to float by doing `c = a / float(b)`. If the numerator or denominator is a float, then the result will be also. --- A caveat: as commenters have pointed out, this won't work if `b` might be something other than an integer or floating-point number (or a string representing one). If you might be dealing wi...
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
455
2009-08-12T18:25:15Z
1,267,892
508
2009-08-12T18:28:26Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
I have two integer values `a` and `b`, but I need their ratio in floating point. I know that `a<b` and I want to calculate `a/b`, so if I use integer division I'll always get 0 with a remainder of `a`. How can I force `c` to be a floating point number in Python in the following? ``` c = a / b ```
``` >>> from __future__ import division >>> a = 4 >>> b = 6 >>> c = a / b >>> c 0.66666666666666663 ```
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
455
2009-08-12T18:25:15Z
1,267,901
49
2009-08-12T18:30:30Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
I have two integer values `a` and `b`, but I need their ratio in floating point. I know that `a<b` and I want to calculate `a/b`, so if I use integer division I'll always get 0 with a remainder of `a`. How can I force `c` to be a floating point number in Python in the following? ``` c = a / b ```
In Python 3.x, the single slash (`/`) always means true (non-truncating) division. (The `//` operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this same behavior by putting a ``` from __future__ import division ``` at the top of your module.
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
455
2009-08-12T18:25:15Z
3,784,679
25
2010-09-24T06:22:39Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
I have two integer values `a` and `b`, but I need their ratio in floating point. I know that `a<b` and I want to calculate `a/b`, so if I use integer division I'll always get 0 with a remainder of `a`. How can I force `c` to be a floating point number in Python in the following? ``` c = a / b ```
Just making any of the parameters for division in floating-point format also produces the output in floating-point. Example: ``` >>> 4.0/3 1.3333333333333333 ``` or, ``` >>> 4 / 3.0 1.3333333333333333 ``` or, ``` >>> 4 / float(3) 1.3333333333333333 ``` or, ``` >>> float(4) / 3 1.3333333333333333 ```
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
455
2009-08-12T18:25:15Z
20,766,181
8
2013-12-24T19:58:41Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
I have two integer values `a` and `b`, but I need their ratio in floating point. I know that `a<b` and I want to calculate `a/b`, so if I use integer division I'll always get 0 with a remainder of `a`. How can I force `c` to be a floating point number in Python in the following? ``` c = a / b ```
This will also work ``` >>> u=1./5 >>> print u ``` > 0.2
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
455
2009-08-12T18:25:15Z
27,078,572
16
2014-11-22T14:39:24Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
I have two integer values `a` and `b`, but I need their ratio in floating point. I know that `a<b` and I want to calculate `a/b`, so if I use integer division I'll always get 0 with a remainder of `a`. How can I force `c` to be a floating point number in Python in the following? ``` c = a / b ```
Add a dot (`.`) to indicate floating point numbers ``` >>> 4/3. 1.3333333333333333 ``` or ``` >>> from __future__ import division >>> 4/3 1.3333333333333333 ```
How can I force division to be floating point in Python? Division keeps rounding down to 0
1,267,869
455
2009-08-12T18:25:15Z
32,657,822
31
2015-09-18T17:29:08Z
[ "python", "floating-point", "integer", "division", "python-2.x" ]
I have two integer values `a` and `b`, but I need their ratio in floating point. I know that `a<b` and I want to calculate `a/b`, so if I use integer division I'll always get 0 with a remainder of `a`. How can I force `c` to be a floating point number in Python in the following? ``` c = a / b ```
> # How can I force division to be floating point in Python? > > I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a/b, so if I use integer division I'll always get 0 with a remainder of a. > > How can I force c to be a floating point number in Python...
Python: Possible to share in-memory data between 2 separate processes
1,268,252
27
2009-08-12T19:33:11Z
1,268,264
12
2009-08-12T19:36:36Z
[ "python" ]
I have an xmlrpc server using Twisted. The server has a huge amount of data stored in-memory. Is it possible to have a secondary, separate xmlrpc server running which can access the object in-memory in the first server? So, serverA starts up and creates an object. serverB starts up and can read from the object in serv...
``` mmap.mmap(0, 65536, 'GlobalSharedMemory') ``` I think the tag ("GlobalSharedMemory") must be the same for all processes wishing to share the same memory. <http://docs.python.org/library/mmap.html>
Python: Possible to share in-memory data between 2 separate processes
1,268,252
27
2009-08-12T19:33:11Z
1,269,055
63
2009-08-12T22:20:42Z
[ "python" ]
I have an xmlrpc server using Twisted. The server has a huge amount of data stored in-memory. Is it possible to have a secondary, separate xmlrpc server running which can access the object in-memory in the first server? So, serverA starts up and creates an object. serverB starts up and can read from the object in serv...
Without some deep and dark rewriting of the Python core runtime (to allow forcing of an allocator that uses a given segment of shared memory and ensures compatible addresses between disparate processes) there is no way to "share objects in memory" in any general sense. That list will hold a million addresses of tuples,...
Calling a base class's classmethod in Python
1,269,217
56
2009-08-12T23:07:22Z
1,269,224
64
2009-08-12T23:09:50Z
[ "python", "class", "overriding", "class-method" ]
Consider the following code: ``` class Base(object): @classmethod def do(cls, a): print cls, a class Derived(Base): @classmethod def do(cls, a): print 'In derived!' # Base.do(cls, a) -- can't pass `cls` Base.do(a) if __name__ == '__main__': d = Derived() d.do...
``` super(Derived, cls).do(a) ``` *EDIT*: Oh, wait a minute... it's not clear exactly what you're asking. This is how you would invoke the code in the base class's version of the method, from the derived class.
Calling a base class's classmethod in Python
1,269,217
56
2009-08-12T23:07:22Z
5,682,347
8
2011-04-15T21:01:49Z
[ "python", "class", "overriding", "class-method" ]
Consider the following code: ``` class Base(object): @classmethod def do(cls, a): print cls, a class Derived(Base): @classmethod def do(cls, a): print 'In derived!' # Base.do(cls, a) -- can't pass `cls` Base.do(a) if __name__ == '__main__': d = Derived() d.do...
this has been a while, but I think I may have found an answer. When you decorate a method to become a classmethod the original unbound method is stored in a property named 'im\_func': ``` class Base(object): @classmethod def do(cls, a): print cls, a class Derived(Base): @classmethod def do(cl...
Differences between Smalltalk and python?
1,269,242
8
2009-08-12T23:17:31Z
1,269,258
16
2009-08-12T23:24:01Z
[ "python", "smalltalk" ]
I'm studying Smalltalk right now. It looks very similar to python (actually, the opposite, python is very similar to Smalltalk), so I was wondering, as a python enthusiast, if it's really worth for me to study it. Apart from message passing, what are other notable conceptual differences between Smalltalk and python wh...
In Python, the "basic" constructs such as `if/else`, short-circuiting boolean operators, and loops are part of the language itself. In Smalltalk, they are all just messages. In that sense, while both Python and Smalltalk agree that "everything is an object", Smalltalk goes further in that it also asserts that "everythi...
Differences between Smalltalk and python?
1,269,242
8
2009-08-12T23:17:31Z
1,269,259
7
2009-08-12T23:24:14Z
[ "python", "smalltalk" ]
I'm studying Smalltalk right now. It looks very similar to python (actually, the opposite, python is very similar to Smalltalk), so I was wondering, as a python enthusiast, if it's really worth for me to study it. Apart from message passing, what are other notable conceptual differences between Smalltalk and python wh...
Smalltalk historically has had an amazing IDE built in. I have missed this IDE on many languages. Smalltalk also has the lovely property that it is typically in a living system. You start up clean and start modifying things. This is basically an object persistent storage system. That being said, this is both good and ...
Differences between Smalltalk and python?
1,269,242
8
2009-08-12T23:17:31Z
1,271,000
9
2009-08-13T09:34:40Z
[ "python", "smalltalk" ]
I'm studying Smalltalk right now. It looks very similar to python (actually, the opposite, python is very similar to Smalltalk), so I was wondering, as a python enthusiast, if it's really worth for me to study it. Apart from message passing, what are other notable conceptual differences between Smalltalk and python wh...
As someone new to smalltalk, the two things that really strike me are the image-based system, and that reflection is everywhere. These two simple facts appear to give rise to everything else cool in the system: * The image means that you do everything by manipulating objects, including writing and compiling code * Ref...
Scale an image in GTK
1,269,320
11
2009-08-12T23:44:38Z
1,283,486
10
2009-08-16T05:06:11Z
[ "python", "user-interface", "image", "gtk", "pygtk" ]
In GTK, how can I scale an image? Right now I load images with PIL and scale them beforehand, but is there a way to do it with GTK?
Load the image from a file using gtk.gdk.Pixbuf for that: ``` import gtk pixbuf = gtk.gdk.pixbuf_new_from_file('/path/to/the/image.png') ``` then scale it: ``` pixbuf = pixbuf.scale_simple(width, height, gtk.gdk.INTERP_BILINEAR) ``` Then, if you want use it in a gtk.Image, crate the widget and set the image from th...
Unusual Speed Difference between Python and C++
1,269,795
35
2009-08-13T02:58:19Z
1,269,839
16
2009-08-13T03:14:40Z
[ "c++", "python", "algorithm", "performance" ]
I recently wrote a short algorithm to calculate [happy numbers](http://en.wikipedia.org/wiki/Happy%5FNumbers) in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of fro...
It looks like you're passing vectors by value to other functions. This will be a significant slowdown because the program will actually make a full copy of your vector before it passes it to your function. To get around this, pass a constant reference to the vector instead of a copy. So instead of: ``` int sum(vector<...
Unusual Speed Difference between Python and C++
1,269,795
35
2009-08-13T02:58:19Z
1,269,842
7
2009-08-13T03:15:41Z
[ "c++", "python", "algorithm", "performance" ]
I recently wrote a short algorithm to calculate [happy numbers](http://en.wikipedia.org/wiki/Happy%5FNumbers) in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of fro...
I can see that you have quite a few heap allocations that are unnecessary For example: ``` while(!next) { char* buffer = new char[10]; ``` This doesn't look very optimized. So, you probably want to have the array pre-allocated and using it inside your loop. This is a basic optimizing technique which is ea...
Unusual Speed Difference between Python and C++
1,269,795
35
2009-08-13T02:58:19Z
1,269,998
144
2009-08-13T04:14:59Z
[ "c++", "python", "algorithm", "performance" ]
I recently wrote a short algorithm to calculate [happy numbers](http://en.wikipedia.org/wiki/Happy%5FNumbers) in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of fro...
For 100000 elements, the Python code took 6.9 seconds while the C++ originally took above 37 seconds. I did some basic optimizations on your code and managed to get the C++ code above 100 times faster than the Python implementation. It now does 100000 elements in 0.06 seconds. That is 617 times faster than the origina...
Unusual Speed Difference between Python and C++
1,269,795
35
2009-08-13T02:58:19Z
1,271,927
19
2009-08-13T13:25:13Z
[ "c++", "python", "algorithm", "performance" ]
I recently wrote a short algorithm to calculate [happy numbers](http://en.wikipedia.org/wiki/Happy%5FNumbers) in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of fro...
**There's a new, radically faster version as [a separate answer](http://stackoverflow.com/questions/1269795/unusual-speed-difference-between-python-and-c/1275074#1275074), so this answer is deprecated.** --- I rewrote your algorithm by making it cache whenever it finds the number to be happy or unhappy. I also tried ...
Python standard library to POST multipart/form-data encoded data
1,270,518
17
2009-08-13T07:24:00Z
1,270,548
17
2009-08-13T07:31:14Z
[ "python", "encoding", "post", "urllib", "multipart" ]
I would like to POST multipart/form-data encoded data. I have found an external module that does it: <http://atlee.ca/software/poster/index.html> however I would rather avoid this dependency. Is there a way to do this using the standard libraries? thanks
The standard library [does not currently support that](http://bugs.python.org/issue3244). There is [cookbook recipe](http://code.activestate.com/recipes/146306/) that includes a fairly short piece of code that you just may want to copy, though, along with long discussions of alternatives.
Python standard library to POST multipart/form-data encoded data
1,270,518
17
2009-08-13T07:24:00Z
18,888,633
7
2013-09-19T07:28:28Z
[ "python", "encoding", "post", "urllib", "multipart" ]
I would like to POST multipart/form-data encoded data. I have found an external module that does it: <http://atlee.ca/software/poster/index.html> however I would rather avoid this dependency. Is there a way to do this using the standard libraries? thanks
It's an old thread but still a popular one, so here is my contribution using only standard modules. The idea is the same than [here](http://code.activestate.com/recipes/146306/) but support Python 2.x and Python 3.x. It also has a body generator to avoid unnecessarily memory usage. ``` import codecs import mimetypes ...
how to print python location(where python is install) in the output
1,270,537
8
2009-08-13T07:28:44Z
1,270,554
9
2009-08-13T07:33:33Z
[ "python", "path" ]
Lets say Python is installed in the location `"C:\TOOLS\COMMON\python\python252"` . I want to print this location in the output of my program. Please let me know which is the function for doing this.
you can use ``` import sys, os os.path.dirname(sys.executable) ``` but remember than in Unix systems the "installation" of a program is usually distributed along the following folders: * /usr/bin (this is what you'll probably get) * /usr/lib * /usr/share * etc.
Python Get Docstring Without Going into Interactive Mode
1,270,615
5
2009-08-13T07:49:52Z
1,270,621
7
2009-08-13T07:50:59Z
[ "python", "interactive" ]
I want to grab the docstring in my commandline application, but every time I call the builtin help() function, Python goes into interactive mode. How do I get the docstring of an object and **not** have Python grab focus?
Any docstring is available through the `.__doc__` property: ``` >>> print str.__doc__ ``` In python 3, you'll need parenthesis for printing: ``` >>> print(str.__doc__) ```
Why does import of ctypes raise ImportError?
1,270,738
3
2009-08-13T08:18:24Z
1,270,756
8
2009-08-13T08:23:35Z
[ "python", "ctypes", "python-2.6", "importerror" ]
``` Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import ctypes Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\lib\ctypes\__init__.py", line 17, in <module> ...
It seems you have another struct.py in your path somewhere. Try this to see where python finds your struct module: ``` >>> import inspect >>> import struct >>> inspect.getabsfile(struct) 'c:\\python26\\lib\\struct.py' ```
Most concise way to check whether a list is empty or contains only None?
1,270,920
6
2009-08-13T09:13:24Z
1,270,938
15
2009-08-13T09:19:45Z
[ "python", "list", "types" ]
Most concise way to check whether a list is empty or contains only None? I understand that I can test: ``` if MyList: pass ``` and: ``` if not MyList: pass ``` but what if the list has an item (or multiple items), but those item/s are None: ``` MyList = [None, None, None] if ???: pass ```
One way is to use [`all`](http://docs.python.org/3.1/library/functions.html#all) and a list comprehension: ``` if all(e is None for e in myList): print('all empty or None') ``` This works for empty lists as well. More generally, to test whether the list only contains things that evaluate to `False`, you can use [...
Most concise way to check whether a list is empty or contains only None?
1,270,920
6
2009-08-13T09:13:24Z
1,270,939
9
2009-08-13T09:19:47Z
[ "python", "list", "types" ]
Most concise way to check whether a list is empty or contains only None? I understand that I can test: ``` if MyList: pass ``` and: ``` if not MyList: pass ``` but what if the list has an item (or multiple items), but those item/s are None: ``` MyList = [None, None, None] if ???: pass ```
You can use the `all()` function to test is all elements are None: ``` a = [] b = [None, None, None] all(e is None for e in a) # True all(e is None for e in b) # True ```
Python - how to refer to relative paths of resources when working with code repository
1,270,951
89
2009-08-13T09:22:30Z
1,270,970
128
2009-08-13T09:27:28Z
[ "python", "path", "repository", "project", "relative" ]
We are working with a code repository which is deployed both to windows and linux, sometimes on different directories. How should one of the modules inside the project refer to one of the non-python resources in the project (CSV file, etc.)? If we do something like ``` thefile=open('test.csv') ``` or ``` thefile=ope...
Try to use a filename relative to the current files path. Example for './my\_file': ``` fn = os.path.join(os.path.dirname(__file__), 'my_file') ```
Python - how to refer to relative paths of resources when working with code repository
1,270,951
89
2009-08-13T09:22:30Z
9,177,940
23
2012-02-07T14:24:07Z
[ "python", "path", "repository", "project", "relative" ]
We are working with a code repository which is deployed both to windows and linux, sometimes on different directories. How should one of the modules inside the project refer to one of the non-python resources in the project (CSV file, etc.)? If we do something like ``` thefile=open('test.csv') ``` or ``` thefile=ope...
If you are using setup tools or distribute (a setup.py install) then the "right" way to access these packaged resources seem to be using package\_resources. In your case the example would be ``` import pkg_resources my_data = pkg_resources.resource_string(__name__, "foo.dat") ``` Which of course reads the resource a...
How to remove two chars from the beginning of a line
1,270,990
21
2009-08-13T09:31:53Z
1,271,003
19
2009-08-13T09:35:00Z
[ "python" ]
I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this: ``` #!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here ```
[String slicing](http://docs.python.org/tutorial/introduction.html#strings) will help you: ``` >>> a="Some very long string" >>> a[2:] 'me very long string' ```
How to remove two chars from the beginning of a line
1,270,990
21
2009-08-13T09:31:53Z
1,271,007
42
2009-08-13T09:36:11Z
[ "python" ]
I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this: ``` #!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here ```
You were off to a good start. Try this in your loop: ``` for line in lines: line = line[2:] # do something here ``` The [2:] is called "[slice](http://docs.python.org/tutorial/introduction.html#strings)" syntax, it essentially says "give me the part of this sequence which begins at index 2 and continues to th...
How to remove two chars from the beginning of a line
1,270,990
21
2009-08-13T09:31:53Z
1,271,029
10
2009-08-13T09:41:14Z
[ "python" ]
I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this: ``` #!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here ```
Instead of using a for loop, you might be happier with a a list comprehension: ``` [line[2:] for line in lines] ``` --- Just as a curiosity, do check the `cut` unix tool. ``` $ cut -c2- filename ``` The slicing syntax for -c is quite similar to python's.
How to remove two chars from the beginning of a line
1,270,990
21
2009-08-13T09:31:53Z
1,271,030
10
2009-08-13T09:41:37Z
[ "python" ]
I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this: ``` #!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here ```
Just as a tip, you can shorten your program to ``` for line in open('M:/file.txt'): line = line[2:] ``` And if you need to carry the line number too, use ``` for i, line in enumerate(open('M:/file.txt.')): line = line[2:] ```
Resize a figure automatically in matplotlib
1,271,023
20
2009-08-13T09:38:46Z
1,278,685
26
2009-08-14T15:57:48Z
[ "python", "matplotlib" ]
Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image? I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used. I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way?
Use **bbox\_inches='tight'** ``` import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm X = 10*np.random.rand(5,3) fig = plt.figure(figsize=(15,5),facecolor='w') ax = fig.add_subplot(111) ax.imshow(X, cmap=cm.jet) plt.savefig("image.png",bbox_inches='tight',dpi=100) ``` ...only works when s...
Resize a figure automatically in matplotlib
1,271,023
20
2009-08-13T09:38:46Z
10,448,306
10
2012-05-04T11:51:06Z
[ "python", "matplotlib" ]
Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image? I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used. I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way?
just use aspect='auto' when you call imshow ``` import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm X = 10*np.random.rand(5,3) plt.imshow(X, aspect='auto') ``` it works even if it is just for showing and not saving
What is the best way to map windows drives using Python?
1,271,317
11
2009-08-13T11:09:36Z
19,171,820
9
2013-10-04T01:39:49Z
[ "python", "windows", "mapping", "drive" ]
What is the best way to map a network share to a windows drive using Python? This share also requires a username and password.
Building off of @Anon's suggestion: ``` # Drive letter: M # Shared drive path: \\shared\folder # Username: user123 # Password: password import subprocess # Disconnect anything on M subprocess.call(r'net use m: /del', shell=True) # Connect to shared drive, use drive letter M subprocess.call(r'net use m: \\shared\fold...
Reseting generator object in Python
1,271,320
73
2009-08-13T11:10:48Z
1,271,353
71
2009-08-13T11:18:29Z
[ "python", "generator", "yield" ]
I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times. ``` y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) ``` Of course, I'm taking in mind c...
Generators can't be rewound. You have the following options: 1. Run the generator function again, restarting the generation: ``` y = FunctionWithYield() for x in y: print(x) y = FunctionWithYield() for x in y: print(x) ``` 2. Store the generator results in a data structure on memory or disk which yo...
Reseting generator object in Python
1,271,320
73
2009-08-13T11:10:48Z
1,271,459
16
2009-08-13T11:39:50Z
[ "python", "generator", "yield" ]
I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times. ``` y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) ``` Of course, I'm taking in mind c...
Probably the most simple solution is to wrap the expensive part in an object and pass that to the generator: ``` data = ExpensiveSetup() for x in FunctionWithYield(data): pass for x in FunctionWithYield(data): pass ``` This way, you can cache the expensive calculations. If you can keep all results in RAM at the same...
Reseting generator object in Python
1,271,320
73
2009-08-13T11:10:48Z
1,271,481
47
2009-08-13T11:44:17Z
[ "python", "generator", "yield" ]
I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times. ``` y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) ``` Of course, I'm taking in mind c...
Another option is to use the `itertools.tee()` function to create a second version of your generator: ``` y = FunctionWithYield() y, y_backup = tee(y) for x in y: print(x) for x in y_backup: print(x) ``` This could be beneficial from memory usage point of view if the original iteration might not process all t...
Reseting generator object in Python
1,271,320
73
2009-08-13T11:10:48Z
19,403,253
17
2013-10-16T12:21:14Z
[ "python", "generator", "yield" ]
I have generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse generator several times. ``` y = FunctionWithYield() for x in y: print(x) #here must be something to reset 'y' for x in y: print(x) ``` Of course, I'm taking in mind c...
``` >>> def gen(): ... def init(): ... return 0 ... i = init() ... while True: ... val = (yield i) ... if val=='restart': ... i = init() ... else: ... i += 1 >>> g = gen() >>> g.next() 0 >>> g.next() 1 >>> g.next() 2 >>> g.next() 3 >>> g.send('restart...
ImportError: no module named py2exe
1,271,337
9
2009-08-13T11:14:34Z
1,271,495
7
2009-08-13T11:47:55Z
[ "python", "py2exe" ]
I get this error when I try to use one of the py2exe samples with py2exe. ``` File "setup.py", line 22, in ? import py2exe ImportError: no module named py2exe ``` I've installed py2exe with the installer, and I use python 2.6. I have downloaded the correct installer from the site (The python 2.6 one.) My path is ...
Sounds like something has installed Python 2.4.3 behind your back, and set that to be the default. Short term, try running your script explicitly with Python 2.6 like this: ``` c:\Python26\python.exe setup.py ... ``` Long term, you need to check your system PATH (which it sounds like you've already done) and your fi...
Is there an equivalent of Pythons range(12) in C#?
1,271,378
31
2009-08-13T11:22:57Z
1,271,388
60
2009-08-13T11:24:19Z
[ "c#", "python", "range" ]
This crops up every now and then for me: I have some C# code badly wanting the `range()` function available in Python. I am aware of using ``` for (int i = 0; i < 12; i++) { // add code here } ``` But this brakes down in functional usages, as when I want to do a Linq `Sum()` instead of writing the above loop. Is...
You're looking for the [`Enumerable.Range`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx) method: ``` var mySequence = Enumerable.Range(0, 12); ```
Is there an equivalent of Pythons range(12) in C#?
1,271,378
31
2009-08-13T11:22:57Z
23,062,619
10
2014-04-14T14:22:09Z
[ "c#", "python", "range" ]
This crops up every now and then for me: I have some C# code badly wanting the `range()` function available in Python. I am aware of using ``` for (int i = 0; i < 12; i++) { // add code here } ``` But this brakes down in functional usages, as when I want to do a Linq `Sum()` instead of writing the above loop. Is...
Just to complement everyone's answers, I thought I should add that `Enumerable.Range(0, 12);` is closer to Python's `xrange(12)` because it's an enumerable. If anyone is looking specifically for a list or an array: ``` Enumerable.Range(0, 12).ToList(); ``` or ``` Enumerable.Range(0, 12).ToArray(); ``` are closer t...
How to check the TEMPLATE_DEBUG flag in a django template?
1,271,631
43
2009-08-13T12:25:06Z
1,271,914
51
2009-08-13T13:23:07Z
[ "python", "django", "templates" ]
Do you know if it is possible to know in a django template if the TEMPLATE\_DEBUG flag is set? I would like to disable my google analytics script when I am running my django app on my development machine. Something like a {% if debug %} template tag would be perfect. Unfortunately, I didn't find something like that in...
Assuming you haven't set `TEMPLATE_CONTEXT_PROCESSORS` to some other value in `settings.py`, Django will automatically load the `debug` context preprocessor (as noted [here](http://docs.djangoproject.com/en/dev/ref/templates/api/#id1)). This means that you will have access to a variable called `debug` in your templates...
How to check the TEMPLATE_DEBUG flag in a django template?
1,271,631
43
2009-08-13T12:25:06Z
13,609,888
41
2012-11-28T16:32:40Z
[ "python", "django", "templates" ]
Do you know if it is possible to know in a django template if the TEMPLATE\_DEBUG flag is set? I would like to disable my google analytics script when I am running my django app on my development machine. Something like a {% if debug %} template tag would be perfect. Unfortunately, I didn't find something like that in...
If modifying `INTERNAL_IPS` is not possible/suitable, you can do this with a context processor: in `myapp/context_processors.py`: ``` from django.conf import settings def debug(context): return {'DEBUG': settings.DEBUG} ``` in `settings.py`: ``` TEMPLATE_CONTEXT_PROCESSORS = ( ... 'myapp.context_processo...
BaseException.message deprecated in Python 2.6
1,272,138
121
2009-08-13T13:59:21Z
1,272,176
26
2009-08-13T14:06:51Z
[ "python", "exception", "deprecated" ]
I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception: ``` class MyException(Exception): def __init__(self, message): self.message = message def __str__(self): return repr(self.message) ``` This is the warning: ``` Deprecation...
Yes, it's deprecated in Python 2.6 because it's going away in Python 3.0 BaseException class does not provide a way to store error message anymore. You'll have to implement it yourself. You can do this with a subclass that uses a property for storing the message. ``` class MyException(Exception): def _get_message...
BaseException.message deprecated in Python 2.6
1,272,138
121
2009-08-13T13:59:21Z
1,272,197
8
2009-08-13T14:09:43Z
[ "python", "exception", "deprecated" ]
I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception: ``` class MyException(Exception): def __init__(self, message): self.message = message def __str__(self): return repr(self.message) ``` This is the warning: ``` Deprecation...
``` class MyException(Exception): def __str__(self): return repr(self.args[0]) e = MyException('asdf') print e ``` This is your class in Python2.6 style. The new exception takes an arbitrary number of arguments.
BaseException.message deprecated in Python 2.6
1,272,138
121
2009-08-13T13:59:21Z
6,029,838
107
2011-05-17T10:58:34Z
[ "python", "exception", "deprecated" ]
I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception: ``` class MyException(Exception): def __init__(self, message): self.message = message def __str__(self): return repr(self.message) ``` This is the warning: ``` Deprecation...
## Solution - almost no coding needed 1. Just inherit your exception class from `Exception` 2. and pass the message as the first parameter to the constructor Example: ``` class MyException(Exception): """My documentation""" try: raise MyException('my detailed description') except MyException as my: prin...
parsing CSV files backwards
1,272,315
2
2009-08-13T14:28:26Z
1,272,338
14
2009-08-13T14:32:41Z
[ "python", "parsing", "csv", "readline" ]
I have csv files with the following format: ``` CSV FILE "a" , "b" , "c" , "d" hello, world , 1 , 2 , 3 1,2,3,4,5,6,7 , 2 , 456 , 87 h,1231232,3 , 3 , 45 , 44 ``` The problem is that the first field has commas "," in it. I have no control over file generation, as that's t...
The `rsplit` string method splits a string starting from the right instead of the left, and so it's probably what you're looking for (it takes an argument specifying the max number of times to split): ``` line = "hello, world , 1 , 2 , 3" parts = line.rsplit(",", 3) print parts # prints ['hello, world '...
Can't import Numpy in Python
1,273,203
16
2009-08-13T16:48:29Z
1,273,217
19
2009-08-13T16:50:53Z
[ "python", "import", "numpy" ]
I'm trying to write some code that uses Numpy. However, I can't import it: ``` Python 2.6.2 (r262, May 15 2009, 10:22:27) [GCC 3.4.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: ...
Have you installed it? On debian/ubuntu: ``` aptitude install python-numpy ``` On windows: [`http://sourceforge.net/projects/numpy/files/NumPy/`](http://sourceforge.net/projects/numpy/files/NumPy/) On other systems: [`http://sourceforge.net/projects/numpy/files/NumPy/`](http://sourceforge.net/projects/numpy/files...
Disable assertions in Python
1,273,211
37
2009-08-13T16:49:37Z
1,273,225
7
2009-08-13T16:52:12Z
[ "python", "debugging", "assert" ]
How do I disable assertions in Python? That is, if an assertion fails, I don't want it to throw an `AssertionError`, but to keep going.
Use `python -O`: ``` $ python -O >>> assert False >>> ```
Disable assertions in Python
1,273,211
37
2009-08-13T16:49:37Z
1,273,233
46
2009-08-13T16:53:41Z
[ "python", "debugging", "assert" ]
How do I disable assertions in Python? That is, if an assertion fails, I don't want it to throw an `AssertionError`, but to keep going.
Call Python with the -O flag: test.py: ``` assert(False) print 'Done' ``` Output: ``` C:\temp\py>C:\Python26\python.exe test.py Traceback (most recent call last): File "test.py", line 1, in <module> assert(False) AssertionError C:\temp\py>C:\Python26\python.exe -O test.py Done ```
Disable assertions in Python
1,273,211
37
2009-08-13T16:49:37Z
21,325,317
9
2014-01-24T05:45:49Z
[ "python", "debugging", "assert" ]
How do I disable assertions in Python? That is, if an assertion fails, I don't want it to throw an `AssertionError`, but to keep going.
Both of the two answers already given are valid (call Python with either `-O` or `-OO` on the command line). Here is the difference between them: * `-O` Turn on basic optimizations. This changes the filename extension for compiled (bytecode) files from .pyc to .pyo. * `-OO` Discard docstrings *in addition* to the `...
Why isn't assertRaises catching my Attribute Error using python unittest?
1,274,047
18
2009-08-13T19:21:28Z
1,274,141
19
2009-08-13T19:38:39Z
[ "python", "django", "unit-testing" ]
I'm trying to run this test: `self.assertRaises(AttributeError, branch[0].childrennodes)`, and `branch[0`] does not have an attribute `childrennodes`, so it should be throwing an `AttributeError`, which the `assertRaises` should catch, but when I run the test, the test fails because it is throwing an `AttributeError`. ...
I think its because assert raises only accepts a callable. It evalutes to see if the callable raises an exception, not if the statement itself does. ``` self.assertRaises(AttributeError, getattr, branch[0], "childrennodes") ``` should work. EDIT: As THC4k correctly says it gathers the statements at collection time ...
Why isn't assertRaises catching my Attribute Error using python unittest?
1,274,047
18
2009-08-13T19:21:28Z
2,267,788
47
2010-02-15T17:41:07Z
[ "python", "django", "unit-testing" ]
I'm trying to run this test: `self.assertRaises(AttributeError, branch[0].childrennodes)`, and `branch[0`] does not have an attribute `childrennodes`, so it should be throwing an `AttributeError`, which the `assertRaises` should catch, but when I run the test, the test fails because it is throwing an `AttributeError`. ...
When the test is running, before calling self.assertRaises, Python needs to find the value of all the method's arguments. In doing so, it evaluates `branch[0].children_nodes`, which raises an AttributeError. Since we haven't invoked assertRaises yet, this exception is not caught, causing the test to fail. The solution...
How can I create a list of files in the current directory and its subdirectories with a given extension?
1,274,506
5
2009-08-13T20:52:27Z
1,274,528
11
2009-08-13T20:57:08Z
[ "python" ]
I'm trying to generate a text file that has a list of all files in the current directory and all of its sub-directories with the extension `".asp"`. What would be the best way to do this?
You'll want to use os.walk which will make that trivial. ``` import os asps = [] for root, dirs, files in os.walk(r'C:\web'): for file in files: if file.endswith('.asp'): asps.append(file) ```
Returning None or a tuple and unpacking
1,274,875
13
2009-08-13T22:03:19Z
1,274,887
14
2009-08-13T22:06:25Z
[ "python", "design", "return-value" ]
I am always annoyed by this fact: ``` $ cat foo.py def foo(flag): if flag: return (1,2) else: return None first, second = foo(True) first, second = foo(False) $ python foo.py Traceback (most recent call last): File "foo.py", line 8, in <module> first, second = foo(False) TypeError: 'Non...
Well, you could do... ``` first,second = foo(True) or (None,None) first,second = foo(False) or (None,None) ``` but as far as I know there's no simpler way to expand None to fill in the entirety of a tuple.
Returning None or a tuple and unpacking
1,274,875
13
2009-08-13T22:03:19Z
1,274,888
7
2009-08-13T22:07:16Z
[ "python", "design", "return-value" ]
I am always annoyed by this fact: ``` $ cat foo.py def foo(flag): if flag: return (1,2) else: return None first, second = foo(True) first, second = foo(False) $ python foo.py Traceback (most recent call last): File "foo.py", line 8, in <module> first, second = foo(False) TypeError: 'Non...
I don't think there's a trick. You can simplify your calling code to: ``` values = foo(False) if values: first, second = values ``` or even: ``` values = foo(False) first, second = values or (first_default, second_default) ``` where first\_default and second\_default are values you'd give to first and second as...
Returning None or a tuple and unpacking
1,274,875
13
2009-08-13T22:03:19Z
1,274,908
16
2009-08-13T22:14:14Z
[ "python", "design", "return-value" ]
I am always annoyed by this fact: ``` $ cat foo.py def foo(flag): if flag: return (1,2) else: return None first, second = foo(True) first, second = foo(False) $ python foo.py Traceback (most recent call last): File "foo.py", line 8, in <module> first, second = foo(False) TypeError: 'Non...
I don't see what is wrong with returning (None,None). It is much cleaner than the solutions suggested here which involve far more changes in your code. It also doesn't make sense that you want None to automagically be split into 2 variables.
Returning None or a tuple and unpacking
1,274,875
13
2009-08-13T22:03:19Z
1,275,055
11
2009-08-13T22:45:50Z
[ "python", "design", "return-value" ]
I am always annoyed by this fact: ``` $ cat foo.py def foo(flag): if flag: return (1,2) else: return None first, second = foo(True) first, second = foo(False) $ python foo.py Traceback (most recent call last): File "foo.py", line 8, in <module> first, second = foo(False) TypeError: 'Non...
I think there is a problem of **abstraction**. A function should maintain some level of abstraction, that helps in reducing complexity of the code. In this case, either the function is not maintaining the right abstraction, either the caller is not respecting it. The function could have been something like `get_poi...
collapsing whitespace in a string
1,274,906
3
2009-08-13T22:13:50Z
1,274,918
14
2009-08-13T22:15:59Z
[ "python", "regex" ]
I have a string that kind of looks like this: ``` "stuff . // : /// more-stuff .. .. ...$%$% stuff -> DD" ``` and I want to strip off all punctuation, make everything uppercase and collapse all whitespace so that it looks like this: ``` "STUFF MORE STUFF STUFF DD" ``` Is this possible with one regex or do I need...
Here's a single-step approach (but the uppercasing actually uses a string method -- much simpler!-): ``` rex = re.compile(r'\W+') result = rex.sub(' ', strarg).upper() ``` where `strarg` is the string argument (*don't* use names that shadow builtins or standard library modules, *please* ... pretty please?-)
Python 3 and static typing
1,275,646
52
2009-08-14T01:47:26Z
1,275,658
14
2009-08-14T01:53:23Z
[ "python", "python-3.x", "static-typing" ]
I didn't really pay as much attention to Python 3's development as I would have liked, and only just noticed some interesting new syntax changes. Specifically from [this SO answer](http://stackoverflow.com/questions/1269795/unusual-speed-difference-between-python-and-c/1271927#1271927) function parameter annotation: `...
As mentioned in that PEP, static type checking is one of the possible applications that function annotations can be used for, but they're leaving it up to third-party libraries to decide how to do it. That is, there isn't going to be an official implementation in core python. As far as third-party implementations are ...
Python 3 and static typing
1,275,646
52
2009-08-14T01:47:26Z
1,276,121
13
2009-08-14T05:01:33Z
[ "python", "python-3.x", "static-typing" ]
I didn't really pay as much attention to Python 3's development as I would have liked, and only just noticed some interesting new syntax changes. Specifically from [this SO answer](http://stackoverflow.com/questions/1269795/unusual-speed-difference-between-python-and-c/1271927#1271927) function parameter annotation: `...
"Static typing" in Python can only be implemented so that the type checking is done in run-time, which means it slows down the application. Therefore you don't want that as a generality. Instead you want some of your methods to check it's inputs. This can be easily done with plain asserts, or with decorators if you (mi...
Python 3 and static typing
1,275,646
52
2009-08-14T01:47:26Z
1,276,582
31
2009-08-14T07:53:55Z
[ "python", "python-3.x", "static-typing" ]
I didn't really pay as much attention to Python 3's development as I would have liked, and only just noticed some interesting new syntax changes. Specifically from [this SO answer](http://stackoverflow.com/questions/1269795/unusual-speed-difference-between-python-and-c/1271927#1271927) function parameter annotation: `...
Thanks for reading my code! Indeed, it's not hard to create a generic annotation enforcer in Python. Here's my take: ``` '''Very simple enforcer of type annotations. This toy super-decorator can decorate all functions in a given module that have annotations so that the type of input and output is enforced; an Asser...
Python 3 and static typing
1,275,646
52
2009-08-14T01:47:26Z
14,814,818
12
2013-02-11T15:05:33Z
[ "python", "python-3.x", "static-typing" ]
I didn't really pay as much attention to Python 3's development as I would have liked, and only just noticed some interesting new syntax changes. Specifically from [this SO answer](http://stackoverflow.com/questions/1269795/unusual-speed-difference-between-python-and-c/1271927#1271927) function parameter annotation: `...
This is not an answer to question directly, but I found out a Python fork that adds static typing: [mypy-lang.org](http://www.mypy-lang.org/), of course one can't rely on it as it's still small endeavor, but interesting.
how to access dictionary element in django template?
1,275,735
110
2009-08-14T02:24:58Z
1,275,751
9
2009-08-14T02:30:39Z
[ "python", "django" ]
I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object. ``` {% for choice in choices %} {{choice.choice}} - {{votes[choice.id]}} <br /> {% endfor %} ``` it raises an exception with this message "Could not parse the...
You need to find (or define) a 'get' template tag, for example, [here](http://push.cx/2007/django-template-tag-for-dictionary-access).
how to access dictionary element in django template?
1,275,735
110
2009-08-14T02:24:58Z
1,275,999
40
2009-08-14T04:07:47Z
[ "python", "django" ]
I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object. ``` {% for choice in choices %} {{choice.choice}} - {{votes[choice.id]}} <br /> {% endfor %} ``` it raises an exception with this message "Could not parse the...
To echo / extend upon Jeff's comment, what I think you should aim for is simply a property in your Choice class that calculates the number of votes associated with that object: ``` class Choice(models.Model): text = models.CharField(max_length=200) def calculateVotes(self): return Vot...
how to access dictionary element in django template?
1,275,735
110
2009-08-14T02:24:58Z
1,724,201
121
2009-11-12T18:01:40Z
[ "python", "django" ]
I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object. ``` {% for choice in choices %} {{choice.choice}} - {{votes[choice.id]}} <br /> {% endfor %} ``` it raises an exception with this message "Could not parse the...
you can use the dot notation: > Dot lookups can be summarized like > this: when the template system > encounters a dot in a variable name, > it tries the following lookups, in > this order: > > * Dictionary lookup (e.g., foo["bar"]) > * Attribute lookup (e.g., foo.bar) > * Method call (e.g., foo.bar()) > * List-index ...
how to access dictionary element in django template?
1,275,735
110
2009-08-14T02:24:58Z
6,285,769
180
2011-06-08T21:59:02Z
[ "python", "django" ]
I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object. ``` {% for choice in choices %} {{choice.choice}} - {{votes[choice.id]}} <br /> {% endfor %} ``` it raises an exception with this message "Could not parse the...
``` choices = {'key1':'val1', 'key2':'val2'} ``` Here's the template: ``` <ul> {% for key, value in choices.items %} <li>{{key}} - {{value}}</li> {% endfor %} </ul> ``` Basically, `.items` is a Django keyword that splits a dictionary into a list of (key, value) pairs. This enables iteration over a dictionary in ...
Stripping everything but alphanumeric chars from a string in Python
1,276,764
142
2009-08-14T08:54:47Z
1,276,774
116
2009-08-14T08:57:37Z
[ "python", "string" ]
What is the best way to strip all non alphanumeric characters from a string, using Python? The solutions presented in the [PHP variant of this question](http://stackoverflow.com/questions/840948) will probably work with some minor adjustments, but don't seem very 'pythonic' to me. For the record, I don't just want to...
Regular expressions to the rescue: ``` import re re.sub(r'\W+', '', your_string) ```
Stripping everything but alphanumeric chars from a string in Python
1,276,764
142
2009-08-14T08:54:47Z
1,276,782
8
2009-08-14T08:58:39Z
[ "python", "string" ]
What is the best way to strip all non alphanumeric characters from a string, using Python? The solutions presented in the [PHP variant of this question](http://stackoverflow.com/questions/840948) will probably work with some minor adjustments, but don't seem very 'pythonic' to me. For the record, I don't just want to...
How about: ``` def ExtractAlphanumeric(InputString): from string import ascii_letters, digits return "".join([ch for ch in InputString if ch in (ascii_letters + digits)]) ``` This works by using list comprehension to produce a list of the characters in `InputString` if they are present in the combined `ascii_...
Stripping everything but alphanumeric chars from a string in Python
1,276,764
142
2009-08-14T08:54:47Z
1,276,811
14
2009-08-14T09:02:28Z
[ "python", "string" ]
What is the best way to strip all non alphanumeric characters from a string, using Python? The solutions presented in the [PHP variant of this question](http://stackoverflow.com/questions/840948) will probably work with some minor adjustments, but don't seem very 'pythonic' to me. For the record, I don't just want to...
You could try: ``` print ''.join(ch for ch in some_string if ch.isalnum()) ```
Stripping everything but alphanumeric chars from a string in Python
1,276,764
142
2009-08-14T08:54:47Z
1,277,047
160
2009-08-14T10:03:32Z
[ "python", "string" ]
What is the best way to strip all non alphanumeric characters from a string, using Python? The solutions presented in the [PHP variant of this question](http://stackoverflow.com/questions/840948) will probably work with some minor adjustments, but don't seem very 'pythonic' to me. For the record, I don't just want to...
I just timed some functions out of curiosity. In these tests I'm removing non-alphanumeric characters from the string `string.printable` (part of the built-in `string` module). ``` $ python -m timeit -s \ "import string" \ "''.join(ch for ch in string.printable if ch.isalnum())" 10000 loops, best of 3: 57.6...
Stripping everything but alphanumeric chars from a string in Python
1,276,764
142
2009-08-14T08:54:47Z
1,280,823
52
2009-08-15T00:33:48Z
[ "python", "string" ]
What is the best way to strip all non alphanumeric characters from a string, using Python? The solutions presented in the [PHP variant of this question](http://stackoverflow.com/questions/840948) will probably work with some minor adjustments, but don't seem very 'pythonic' to me. For the record, I don't just want to...
Use the **str.translate()** method. Presuming you will be doing this often: (1) Once, create a string containing all the characters you wish to delete: ``` delchars = ''.join(c for c in map(chr, range(256)) if not c.isalnum()) ``` (2) Whenever you want to scrunch a string: ``` scrunched = s.translate(None, delchar...
How do you install lxml on OS X Leopard without using MacPorts or Fink?
1,277,124
34
2009-08-14T10:22:27Z
1,277,421
33
2009-08-14T11:40:39Z
[ "python", "osx", "shell", "lxml", "osx-leopard" ]
I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works? Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.
Thanks to @jessenoller on Twitter I have an answer that fits my needs - you can compile lxml with static dependencies, hence avoiding messing with the libxml2 that ships with OS X. Here's what worked for me: ``` cd /tmp curl -O http://lxml.de/files/lxml-3.6.0.tgz tar -xzvf lxml-3.6.0.tgz cd lxml-3.6.0 python setup.py...
How do you install lxml on OS X Leopard without using MacPorts or Fink?
1,277,124
34
2009-08-14T10:22:27Z
5,785,013
16
2011-04-26T01:32:08Z
[ "python", "osx", "shell", "lxml", "osx-leopard" ]
I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works? Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.
I've had excellent luck with [Homebrew](http://mxcl.github.com/homebrew/) to install the `libxml2` dependency: ``` brew install libxml2 ``` Homebrew doesn't seem to have `libxslt` available, but I've not yet had a need for XSLT. YMMV. Once you have the dependency(s), then the usual methods work just fine: ``` pip i...
How do you install lxml on OS X Leopard without using MacPorts or Fink?
1,277,124
34
2009-08-14T10:22:27Z
6,545,556
30
2011-07-01T08:38:34Z
[ "python", "osx", "shell", "lxml", "osx-leopard" ]
I've tried this and run in to problems a bunch of times in the past. Does anyone have a recipe for installing lxml on OS X without MacPorts or Fink that definitely works? Preferably with complete 1-2-3 steps for downloading and building each of the dependencies.
This worked for me (10.6.8): ``` sudo env ARCHFLAGS="-arch i386 -arch x86_64" easy_install lxml ```
Python: zip-like function that pads to longest length?
1,277,278
70
2009-08-14T11:04:09Z
1,277,286
41
2009-08-14T11:06:13Z
[ "python", "list", "zip" ]
Is there a built-in function that works like `zip()` but that will pad the results so that the length of the resultant list is the length of the *longest* input rather than the *shortest* input? ``` >>> a=['a1'] >>> b=['b1','b2','b3'] >>> c=['c1','c2'] >>> zip(a,b,c) [('a1', 'b1', 'c1')] >>> What command goes here? ...
For Python 2.6x use `itertools` module's [`izip_longest`](http://docs.python.org/library/itertools.html#itertools.izip_longest). For Python 3 use [`zip_longest`](http://docs.python.org/3.1/library/itertools.html#itertools.zip_longest) instead (no leading `i`). ``` >>> list(itertools.izip_longest(a, b, c)) [('a1', 'b1...
Python: zip-like function that pads to longest length?
1,277,278
70
2009-08-14T11:04:09Z
1,277,311
98
2009-08-14T11:10:44Z
[ "python", "list", "zip" ]
Is there a built-in function that works like `zip()` but that will pad the results so that the length of the resultant list is the length of the *longest* input rather than the *shortest* input? ``` >>> a=['a1'] >>> b=['b1','b2','b3'] >>> c=['c1','c2'] >>> zip(a,b,c) [('a1', 'b1', 'c1')] >>> What command goes here? ...
You can either use [`itertools.izip_longest`](https://docs.python.org/2/library/itertools.html#itertools.izip_longest) (Python 2.6+), or you can use `map` with `None`. It is a little known [feature of `map`](https://docs.python.org/2/library/functions.html#map) (but `map` changed in Python 3.x, so this only works in Py...
How can I pass my locals and access the variables directly from another function?
1,277,519
3
2009-08-14T12:08:57Z
1,278,351
9
2009-08-14T14:54:55Z
[ "python", "variables", "function", "language-features" ]
Let's say I have this : ``` def a(dict): locals().update(dict) print size def b(): size = 20 f(locals()) ``` What do I have to do to access the `size` variable directly from the `a` function? I know of : ``` size = dict["size"] ``` but I think there should be a more direct way. I tried using `locals().upda...
The Python compiler optimizes access to local variables by recognizing at compile time whether the barenames a function is accessing are local (i.e., barenames assigned or otherwise bound within the function). So if you code: ``` def lv1(d): locals().update(d) print zap ``` the compiler "knows" that barename `zap...
Python and dictionary like object
1,277,881
10
2009-08-14T13:37:53Z
1,278,070
11
2009-08-14T14:08:58Z
[ "python", "dictionary", "duck-typing" ]
I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary). But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using **`isinstan...
Check out the (new in 3.x) abstract base classes (ABC's) in the collections module: <http://docs.python.org/3.1/library/collections.html> I would consider checking with isinstance against Mapping like in the following: ``` >>> import collections >>> isinstance({},collections.Mapping) True ``` Then, if you make your...
Is there a way to output the numbers only from a python list?
1,277,914
5
2009-08-14T13:42:47Z
1,277,940
12
2009-08-14T13:46:19Z
[ "python" ]
Simple Question: ``` list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ] ``` I want to create a `list_2` such that it only contains the numbers: ``` list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ] ``` Is there simplistic way of doing this, or do I have ...
List comprehensions. ``` list_2 = [num for num in list_1 if isinstance(num, (int,float))] ```
Is there a way to output the numbers only from a python list?
1,277,914
5
2009-08-14T13:42:47Z
1,277,993
13
2009-08-14T13:56:52Z
[ "python" ]
Simple Question: ``` list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ] ``` I want to create a `list_2` such that it only contains the numbers: ``` list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ] ``` Is there simplistic way of doing this, or do I have ...
This should be the most efficent and shortest: ``` import operator filter(operator.isNumberType, list_1) ``` Edit: this in python 3000: ``` import numbers [x for x in list_1 if isinstance(x, numbers.Number)] ```
Python When I catch an exception, how do I get the type, file, and line number?
1,278,705
115
2009-08-14T16:02:14Z
1,278,740
161
2009-08-14T16:09:05Z
[ "python", "exception", "exception-handling", "stack-trace" ]
Catching an exception that would print like this: ``` Traceback (most recent call last): File "c:/tmp.py", line 1, in <module> 4 / 0 ZeroDivisionError: integer division or modulo by zero ``` I want to format it into: ``` ZeroDivisonError, tmp.py, 1 ```
``` import sys, os try: raise NotImplementedError("No error") except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) ```