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
Inner Classes: How can I get the outer-class object at construction time?
2,278,426
5
2010-02-17T04:59:57Z
2,278,595
11
2010-02-17T05:47:31Z
[ "python" ]
Consider the following Python (runs in 2.x or 3.x): ``` class Outer(object): pass class Inner(object): def __init__(self): print("Inner.self", self) o = Outer() i = o.Inner() ``` I want to get my hands on `o` while inside `Inner.__init__()`. But: * I don't want `o` to be an explicit parameter to `Inn...
In Python 2.6, a class decorator that's also a custom descriptor matches the specs you give: ``` class InnerClassDescriptor(object): def __init__(self, cls): self.cls = cls def __get__(self, instance, outerclass): class Wrapper(self.cls): outer = instance Wrapper.__name__ = self.cls.__name__ ...
pycurl install :( already have min. libcurl version
2,279,014
3
2010-02-17T07:38:01Z
2,279,353
7
2010-02-17T08:57:44Z
[ "python", "osx", "libcurl", "pycurl" ]
I'm running python 2.6 on an Intel Mac OS X 10.5 I'm trying to install pycurl 7.16.2.1 (as recommended here <http://curl.haxx.se/mail/curlpython-2009-03/0009.html>), but for some reason, the installation sees my libcurl 7.16.3, yet it still insist I install 7.16.2 or greater (doesn't 7.16.3 satisfy that?) Here's the ...
If you are using the python.org Python 2.6, it is built using the 10.4 SDK so as to be able to run on multiple versions of OS X. In that case, the pycurl build is likely trying to link against the 10.4 version of libcurl, which appears to be 7.13.1. The thread you link to is talking about using the 10.5 Apple-supplied ...
Python function composition
2,279,423
9
2010-02-17T09:11:50Z
2,279,486
9
2010-02-17T09:22:02Z
[ "python", "function-composition" ]
I've tried to implement function composition with nice syntax and here is what I've got: ``` from functools import partial class _compfunc(partial): def __lshift__(self, y): f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) return _compfunc(f) def __rshift__(self, y): f = lam...
`append` does in-place addition, as Ignacio Vazquez-Abrams said (well, implied) -- so, while you could fix that by just adding a `return` to your function, it would have the side-effect of changing the argument it was passed, too: ``` @composable def f4(a): a.append(0) return a ``` It would be best to use the...
Bash alias to Python script -- is it possible?
2,279,749
2
2010-02-17T10:11:46Z
2,279,883
7
2010-02-17T10:33:17Z
[ "python", "bash", "curl", "scripting", "multiplatform" ]
The particular alias I'm looking to "class up" into a Python script happens to be one that makes use of the cUrl -o (output to file) option. I suppose I could as easily turn it into a BASH function, but someone advised me that I could avoid the quirks and pitfalls of the different versions and "flavors" of BASH by taki...
The [relevant section](http://www.gnu.org/software/bash/manual/bashref.html#Aliases) from the Bash manual states: > Aliases allow a string to be > substituted for a word when it is used > as the first word of a simple command. So, there should be nothing preventing you from doing e.g. ``` $ alias geturl="python /som...
Unit testing functions that access files
2,279,835
8
2010-02-17T10:25:55Z
2,279,931
7
2010-02-17T10:41:03Z
[ "python", "unit-testing" ]
I have two functions—one that builds the path to a set of files and another that reads the files. Below are the two functions: ``` def pass_file_name(self): self.log_files= [] file_name = self.path+"\\access_"+self.appliacation+".log" if os.path.isfile(file_name): self.log_files.append(file_name)...
You have two *units* here: * One that generate file paths * Second that reads them Thus there should be two unit-test-cases (i.e. classes with tests). First would test only file paths generation. Second would test reading from predefined set of files you prepared in special subdirectory of tests directory, it should ...
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
14
2010-02-17T11:56:18Z
2,280,351
14
2010-02-17T11:58:34Z
[ "python" ]
Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be). One solution would be to create a new class that has the attributes the code expects, but as I call other code that also needs objects ...
Use `collections.namedtuple`. It works well. ``` from collections import namedtuple Data = namedtuple( 'Data', [ 'do_good_stuff', 'do_bad_stuff' ] ) options = Data( True, False ) ```
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
14
2010-02-17T11:56:18Z
2,283,725
8
2010-02-17T19:22:45Z
[ "python" ]
Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be). One solution would be to create a new class that has the attributes the code expects, but as I call other code that also needs objects ...
This works in 2.5, 2.6, and 3.1: ``` class Struct(object): pass something = Struct() something.awesome = abs result = something.awesome(-42) ``` EDIT: I thought maybe giving the source would help out as well. <http://docs.python.org/tutorial/classes.html#odds-and-ends> EDIT: Added assignment to result, as I wa...
Shortest way of creating an object with arbitrary attributes in Python?
2,280,334
14
2010-02-17T11:56:18Z
2,284,238
17
2010-02-17T20:42:58Z
[ "python" ]
Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be). One solution would be to create a new class that has the attributes the code expects, but as I call other code that also needs objects ...
The original code can be streamlined a little by using `__dict__`: ``` In [1]: class data: ...: def __init__(self, **kwargs): ...: self.__dict__.update(kwargs) ...: In [2]: d = data(foo=1, bar=2) In [3]: d.foo Out[3]: 1 In [4]: d.bar Out[4]: 2 ```
A list vs. tuple situation in Python
2,280,881
8
2010-02-17T13:17:34Z
2,280,923
14
2010-02-17T13:23:17Z
[ "python", "list", "tuples" ]
Is there a situation where the use of a list leads to an error, and you must use a tuple instead? I know something about the properties of both tuples and lists, but not enough to find out the answer to this question. If the question would be the other way around, it would be that lists can be adjusted but tuples don'...
You can use tuples as dictionary keys, because they are immutable, but you can't use lists. Eg: ``` d = {(1, 2): 'a', (3, 8, 1): 'b'} # Valid. d = {[1, 2]: 'a', [3, 8, 1]: 'b'} # Error. ```
A list vs. tuple situation in Python
2,280,881
8
2010-02-17T13:17:34Z
2,287,849
9
2010-02-18T10:30:05Z
[ "python", "list", "tuples" ]
Is there a situation where the use of a list leads to an error, and you must use a tuple instead? I know something about the properties of both tuples and lists, but not enough to find out the answer to this question. If the question would be the other way around, it would be that lists can be adjusted but tuples don'...
Because of their immutable nature, tuples (unlike lists) are [hashable](http://docs.python.org/glossary.html). This is what allows tuples to be keys in dictionaries and also members of sets. Strictly speaking it is their hashability, not their immutability that counts. So in addition to the dictionary key answer alrea...
How to iterate over a the attributes of a class, in the order they were defined?
2,280,961
8
2010-02-17T13:28:48Z
2,281,001
7
2010-02-17T13:34:28Z
[ "python", "reflection" ]
Python comes with the handy `dir()` function that would list the content of a class for you. For example, for this class: ``` class C: i = 1 a = 'b' ``` `dir(C)` would return ``` ['__doc__', '__module__', 'a', 'i'] ``` This is great, but notice how the order of `'a'` and `'i'` is now different then the order ...
I don't think this is possible in Python 2.x. When the class members are provided to the `__new__` method they are given as a dictionary, so the order has already been lost at that point. Therefore even metaclasses can't help you here (unless there are additional features that I missed). In Python 3 you can use the ne...
Why/When in Python does `x==y` call `y.__eq__(x)`?
2,281,222
31
2010-02-17T14:00:16Z
2,282,795
27
2010-02-17T17:10:34Z
[ "python", "comparison", "operator-overloading" ]
The Python docs clearly state that `x==y` calls `x.__eq__(y)`. However it seems that under many circumstances, the opposite is true. Where is it documented when or why this happens, and how can I work out for sure whether my object's `__cmp__` or `__eq__` methods are going to get called. Edit: Just to clarify, I know ...
You're missing a key exception to the usual behaviour: when the right-hand operand is an instance of a subclass of the class of the left-hand operand, the special method for the right-hand operand is called first. See the documentation at: <http://docs.python.org/reference/datamodel.html#coercion-rules> and in parti...
Removing empty items from a list (Python)
2,281,263
2
2010-02-17T14:07:46Z
2,281,308
11
2010-02-17T14:13:28Z
[ "python", "regex", "list", "split" ]
I'm reading a file in Python that isn't well formatted, values are separated by multiple spaces and some tabs too so the lists returned has a lot of empty items, how do I remove/avoid those? This is my current code: ``` import re f = open('myfile.txt','r') for line in f.readlines(): if re.search(r'\bDeposit',...
Don't explicitly specify `' '` as the delimiter. `line.split()` will split on all whitespace. It's equivalent to using `re.split`: ``` >>> line = ' a b c \n\tg ' >>> line.split() ['a', 'b', 'c', 'g'] >>> import re >>> re.split('\s+', line) ['', 'a', 'b', 'c', 'g', ''] >>> re.split('\s+', line.strip()) ['a', 'b', '...
Enable or disable gtk.Button in PyGTK
2,281,373
6
2010-02-17T14:23:07Z
2,281,422
12
2010-02-17T14:29:18Z
[ "python", "pygtk" ]
How can I set a `gtk.Button` enabled or disabled in PyGTK?
``` my_button.set_sensitive(False) ``` True is enabled, False disabled. See the [gtk.Widget documentation](http://www.pygtk.org/docs/pygtk/class-gtkwidget.html#method-gtkwidget--set-sensitive).
Are there more ways to define a tuple with only one item?
2,281,409
5
2010-02-17T14:27:54Z
2,281,466
8
2010-02-17T14:33:57Z
[ "python", "singleton", "tuples" ]
I know this is one way, by placing a comma: ``` >>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',) ``` Source: <http://docs.python.org/tutorial/datastructures.html> Are there more ways to define a tuple with only 1 item?
``` >>> tuple(['hello']) ('hello',) ``` But the built-in syntax is there for a reason.
Is it a good idea to have a syntax sugar to function composition in Python?
2,281,693
17
2010-02-17T15:00:19Z
2,281,838
8
2010-02-17T15:20:30Z
[ "python", "function-composition" ]
Some time ago I looked over Haskell docs and found it's functional composition operator really nice. So I've implemented this tiny decorator: ``` from functools import partial class _compfunc(partial): def __lshift__(self, y): f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) return _comp...
IMHO: no, it's not. While I like Haskell, this just doesn't seem to fit in Python. Instead of `(f1 >> f2 >> f3)` you can do `compose(f1, f2, f3)` and that solves your problem -- you can use it with any callable without any overloading, decorating or changing the core (IIRC somebody already proposed `functools.compose` ...
Adding an entry to a python tuple
2,282,300
3
2010-02-17T16:14:48Z
2,282,335
10
2010-02-17T16:18:07Z
[ "python", "list", "tuples" ]
I have a list of tuples representing x,y points. I also have a list of values for each of these points. How do I combine them into a list of lists (i.e one entry for each point [x,y,val]) or a list of tuples? Thanks
You can't add entries to tuples, since tuples are immutable. But you can create a new list of lists: ``` new = [[x, y, val] for (x, y), val in zip(points, vals)] ```
How Do I Get the Module Name of an Object's Class Definition Rather Than the Module Name of the Object's Instantiation?
2,282,369
11
2010-02-17T16:22:02Z
2,282,648
7
2010-02-17T16:55:18Z
[ "python" ]
In python 2.5, I have the following code in a module called modtest.py: ``` def print_method_module(method): def printer(self): print self.__module__ return method(self) return printer class ModTest(): @print_method_module def testmethod(self): pass if __name__ == "__main__":...
When you execute a python source file directly, the module name of that file is `__main__`, even if it is known by another name when you execute some other file and import it. You probably want to do like you did in modtest2, and import the module containing the class definition instead of executing that file directly...
draw points using matplotlib.pyplot [[x1,y1],[x2,y2]]
2,282,727
28
2010-02-17T17:05:29Z
2,315,858
44
2010-02-23T03:04:10Z
[ "python", "matplotlib" ]
I want to draw graph using a list of `(x,y)` pairs instead of using two lists, one of X's and one of Y's. Something like this: ``` a = [[1,2],[3,3],[4,4],[5,2]] plt.plot(a, 'ro') ``` Rather than: ``` plt.plot([1,3,4,5], [2,3,4,2]) ``` Suggestions?
You can do something like this: ``` a=[[1,2],[3,3],[4,4],[5,2]] plt.plot(*zip(*a)) ``` Unfortunately, you can no longer pass 'ro'. You must pass marker and line style values as keyword parameters: ``` a=[[1,2],[3,3],[4,4],[5,2]] plt.plot(*zip(*a), marker='o', color='r', ls='') ``` The trick I used is [unpacking arg...
draw points using matplotlib.pyplot [[x1,y1],[x2,y2]]
2,282,727
28
2010-02-17T17:05:29Z
23,716,233
7
2014-05-17T21:26:46Z
[ "python", "matplotlib" ]
I want to draw graph using a list of `(x,y)` pairs instead of using two lists, one of X's and one of Y's. Something like this: ``` a = [[1,2],[3,3],[4,4],[5,2]] plt.plot(a, 'ro') ``` Rather than: ``` plt.plot([1,3,4,5], [2,3,4,2]) ``` Suggestions?
**list comprehensions** I highly suggest the liberal application of list comprehensions. Not only are they terse and powerful, they tend to make your code very readable. Try something like this: ``` list_of_lists = [[1,2],[3,3],[4,4],[5,2]] x_list = [x for [x, y] in list_of_lists] y_list = [y for [x, y] in list_...
How to see if code is backwards compatible for Python?
2,282,882
13
2010-02-17T17:21:35Z
2,283,054
9
2010-02-17T17:46:00Z
[ "python", "backwards-compatibility" ]
I have some code that I am trying to make it play nicely with ESRI's geoprocessor. However, ESRI's geoprocessor runs on Python 2.2, 2.3, 2.4, 2.5. We need to make our tools work on any version. So I've spent a lot of time working and coding workarounds for different versions, such that the wrapper geoprocessor has iden...
Try pyqver: <https://github.com/ghewgill/pyqver/> Gives you the minimum version for given python script analyzing the keywords and modules used. Also, you can compile locally python 2.2 and use virtualenv to create a python 2.2 environment with the --python flag.
How to see if code is backwards compatible for Python?
2,282,882
13
2010-02-17T17:21:35Z
2,283,061
10
2010-02-17T17:46:59Z
[ "python", "backwards-compatibility" ]
I have some code that I am trying to make it play nicely with ESRI's geoprocessor. However, ESRI's geoprocessor runs on Python 2.2, 2.3, 2.4, 2.5. We need to make our tools work on any version. So I've spent a lot of time working and coding workarounds for different versions, such that the wrapper geoprocessor has iden...
If you are actively developing a commercial product, and you -really- want to support all these versions properly, I would suggest: 1. Writing an automated test suite that can be run and tests functionality for your entire library/application/whatever. 2. Setting up a machine, or ideally virtual machine for each test ...
Python for a Perl programmer
2,283,034
43
2010-02-17T17:43:42Z
2,283,300
56
2010-02-17T18:19:07Z
[ "python", "perl" ]
I am an experienced Perl developer with some degree of experience and/or familiarity with other languages (working experience with C/C++, school experience with Java and Scheme, and passing familiarity with many others). I might need to get some web work done in Python (most immediately, related to Google App Engine)....
I've recently had to make a similar transition for work reasons, and it's been pretty painful. For better or worse, Python has a very different philosophy and way of working than Perl, and getting used to that can be frustrating. The things I've found most useful have been * Spend a few hours going through all the bas...
Python for a Perl programmer
2,283,034
43
2010-02-17T17:43:42Z
2,286,686
7
2010-02-18T06:16:46Z
[ "python", "perl" ]
I am an experienced Perl developer with some degree of experience and/or familiarity with other languages (working experience with C/C++, school experience with Java and Scheme, and passing familiarity with many others). I might need to get some web work done in Python (most immediately, related to Google App Engine)....
Being a hardcore Perl programmer, all I can say is **DO NOT BUY** O'Reilly's "Learning Python". It is nowhere NEAR as good as "Learning Perl", and there's no equivalent I know of to Larry Wall's "Programming Perl", which is simply unbeatable. I've had the most success taking past Perl programs and translating them int...
Python for a Perl programmer
2,283,034
43
2010-02-17T17:43:42Z
2,291,006
12
2010-02-18T18:12:42Z
[ "python", "perl" ]
I am an experienced Perl developer with some degree of experience and/or familiarity with other languages (working experience with C/C++, school experience with Java and Scheme, and passing familiarity with many others). I might need to get some web work done in Python (most immediately, related to Google App Engine)....
If you happen to be a fan of [The Perl Cookbook](http://en.wikipedia.org/wiki/Perl_Cookbook), you might be interested in checking out [PLEAC, the Programming Language Examples Alike Cookbook](http://pleac.sourceforge.net), specifically [the section that shows the Perl Cookbook code translated into Python](http://pleac....
App Engine, Python: how to filter query by ID?
2,283,149
6
2010-02-17T18:00:56Z
2,283,381
13
2010-02-17T18:31:36Z
[ "python", "google-app-engine" ]
I try to get data from app engine datastore. Filtering query by 'title' (or any other property) works: ``` obj = db.Query(PageModel).filter('title',title)[0] ``` But the same thing with ID - doesn't: ``` obj = db.Query(PageModel).filter('ID',page_id)[0] ``` I think there is something special about IDs and KEYs in ...
Try ``` obj = PageModel.get_by_id(page_id) ``` instead. This assumes that the ID you're working with is the numerical ID of a datastore key (ie, came from something like `obj.key().id()`) and not some arbitrary ID field you've added to your `PageModel`.
Python function pointer
2,283,210
41
2010-02-17T18:07:50Z
2,283,243
62
2010-02-17T18:11:21Z
[ "python", "function-pointers" ]
I have a function name stored in a variable like this: ``` myvar = 'mypackage.mymodule.myfunction' ``` and I now want to call myfunction like this ``` myvar(parameter1, parameter2) ``` What's the easiest way to achieve this?
``` funcdict = { 'mypackage.mymodule.myfunction': mypackage.mymodule.myfunction, .... } funcdict[myvar](parameter1, parameter2) ```
Python function pointer
2,283,210
41
2010-02-17T18:07:50Z
2,283,267
11
2010-02-17T18:15:22Z
[ "python", "function-pointers" ]
I have a function name stored in a variable like this: ``` myvar = 'mypackage.mymodule.myfunction' ``` and I now want to call myfunction like this ``` myvar(parameter1, parameter2) ``` What's the easiest way to achieve this?
``` def f(a,b): return a+b xx = 'f' print eval('%s(%s,%s)'%(xx,2,3)) ``` **OUTPUT** ``` 5 ```
Python function pointer
2,283,210
41
2010-02-17T18:07:50Z
2,283,574
25
2010-02-17T19:03:41Z
[ "python", "function-pointers" ]
I have a function name stored in a variable like this: ``` myvar = 'mypackage.mymodule.myfunction' ``` and I now want to call myfunction like this ``` myvar(parameter1, parameter2) ``` What's the easiest way to achieve this?
It's much nicer to be able to just store the function itself, since they're first-class objects in python. ``` import mypackage myfunc = mypackage.mymodule.myfunction myfunc(parameter1, parameter2) ``` But, if you have to import the package dynamically, then you can achieve this through: ``` mypackage = __import__(...
Sum of Square Differences (SSD) in numpy/scipy
2,284,611
6
2010-02-17T21:43:37Z
2,284,634
18
2010-02-17T21:47:11Z
[ "python", "image-processing", "numpy", "scipy" ]
I'm trying to use Python and Numpy/Scipy to implement an image processing algorithm. The profiler tells me a lot of time is being spent in the following function (called often), which tells me the sum of square differences between two images ``` def ssd(A,B): s = 0 for i in range(3): s += sum(pow(A[:,:...
Just ``` s = numpy.sum((A[:,:,0:3]-B[:,:,0:3])**2) ``` (which I expect is likely just `sum((A-B)**2)` if the shape is always (*,*,3)) You can also use the sum method: `((A-B)**2).sum()` Right?
Do all dynamic languages have the circular import issue?
2,284,968
2
2010-02-17T22:38:52Z
2,285,024
11
2010-02-17T22:48:05Z
[ "python", "ruby", "dynamic-languages" ]
For the following Python code: **first.py** ``` # first.py from second import Second class First: def __init__(self): print 'Second' ``` **second.py** ``` # second.py from first import First class Second: def __init__(self): print 'Second' ``` After creating the files and running the foll...
Python can handle circular imports to some extent. In cases where no sense can be made, the solution would probably still not make sense in another language. Most of the problems can be cleared up by using `import first` and later referring to `first.First` instead of `from first import First`. It would be better if y...
Python basics: How to read N ints until '\n' is found in stdin
2,285,284
3
2010-02-17T23:35:09Z
2,285,295
14
2010-02-17T23:37:15Z
[ "python", "stdin" ]
How can I read N `int`s from the input, and stop reading when I find `\n`? Also, how can I add them to an array that I can work with? I'm looking for something like this from C but in python ``` while(scanf("%d%c",&somearray[i],&c)!=EOF){ i++; if (c == '\n'){ break; } } ```
In Python 2: ``` lst = map(int, raw_input().split()) ``` `raw_input()` reads a whole line from the input (stopping at the `\n`) as a string. `.split()` creates a list of strings by splitting the input into words. `map(int, ...)` creates integers from those words. In Python 3 `raw_input` has been renamed to `input` a...
Python basics: How to read N ints until '\n' is found in stdin
2,285,284
3
2010-02-17T23:35:09Z
2,285,296
12
2010-02-17T23:37:43Z
[ "python", "stdin" ]
How can I read N `int`s from the input, and stop reading when I find `\n`? Also, how can I add them to an array that I can work with? I'm looking for something like this from C but in python ``` while(scanf("%d%c",&somearray[i],&c)!=EOF){ i++; if (c == '\n'){ break; } } ```
There is no direct equivalent of scanf in Python, but this should work ``` somearray = map(int, raw_input().split()) ``` In Python3 `raw_input` has been renamed to `input` ``` somearray = map(int, input().split()) ``` Here is a breakdown/explanation ``` >>> raw=raw_input() # raw_input waits for some i...
Python dictionary that maps strings to a set of strings?
2,285,874
11
2010-02-18T02:20:45Z
2,285,881
20
2010-02-18T02:22:52Z
[ "python", "dictionary", "set" ]
I would like to be able to make a Python dictionary with strings as keys and sets of strings as the values. E.g.: `{ "crackers" : ["crunchy", "salty"] }` It must be a set, not a list. However, when I try the following: ``` word_dict = dict() word_dict["foo"] = set() word_dict["foo"] = word_dict["foo"].add("baz"...
``` from collections import defaultdict word_dict = defaultdict(set) word_dict['banana'].add('yellow') word_dict['banana'].add('brown') word_dict['apple'].add('red') word_dict['apple'].add('green') for key,values in word_dict.iteritems(): print "%s: %s" % (key, values) ```
Python dictionary that maps strings to a set of strings?
2,285,874
11
2010-02-18T02:20:45Z
2,285,887
17
2010-02-18T02:24:11Z
[ "python", "dictionary", "set" ]
I would like to be able to make a Python dictionary with strings as keys and sets of strings as the values. E.g.: `{ "crackers" : ["crunchy", "salty"] }` It must be a set, not a list. However, when I try the following: ``` word_dict = dict() word_dict["foo"] = set() word_dict["foo"] = word_dict["foo"].add("baz"...
`set.add()` does not return a new `set`, it modifies the `set` it is called on. Use it this way: ``` word_dict = dict() word_dict["foo"] = set() word_dict["foo"].add("baz") word_dict["foo"].add("bang") ``` Also, if you use a `for` loop to iterate over a dict, you are iterating over...
Endless Recursion in Python
2,286,019
2
2010-02-18T03:03:56Z
2,286,080
7
2010-02-18T03:21:44Z
[ "python", "recursion" ]
Full disclosure, this is part of a homework assignment (though a small snippet, the project itself is a game playing AI). I have this function built into a tree node class: ``` def recursive_score_calc(self): current_score = self.board for c in self.children: child_score = c.recursive_...
This bit of your code: ``` class TreeNode: children = [] ``` means that *every* instance of the class shares the same `children` list. So, in this bit: ``` def add_child(self, child): self.children.append(child) ``` you're appending to the "class-global" list. So, of course, every node is a child of every o...
The origin of using # as a comment in Python?
2,286,120
4
2010-02-18T03:32:41Z
2,286,146
13
2010-02-18T03:39:40Z
[ "python", "linux", "shell" ]
So I just had like this mental explosion dude! I was looking at my Python source code and was reading some comments and then I looked a the comments again. When I came across this: ``` #!/usr/bin/env python # A regular comment ``` Which made me wonder, was `#` chosen as the symbol to start a comment because it would ...
Yes. Using # to start a comment is a convention followed by every major interpreted language designed to work on POSIX systems (i.e. not Windows). It also dovetails nicely with the fact that the sequence "#!" at the beginning of a file is recognized by the OS to mean "run the command on this line" when you try to run...
Removing duplicates in a string in Python
2,286,860
3
2010-02-18T07:09:36Z
2,286,870
18
2010-02-18T07:12:14Z
[ "python", "algorithm" ]
What is an efficient algorithm to removing all duplicates in a string? For example : **aaaabbbccdbdbcd** Required result: **abcd**
You use a hashtable to store currently discovered keys (access O(1)) and then loop through the array. If a character is in the hashtable, discard it. If it isn't add it to the hashtable and a result string. Overall: O(n) time (and space). The naive solution is to search for the character is the result string as you p...
How can I add a Picture to a QWidget in PyQt4
2,286,864
12
2010-02-18T07:11:01Z
2,286,888
9
2010-02-18T07:18:15Z
[ "python", "pyqt4" ]
How can I add or import a picture to a `QWidget`? I have found a clue. I can add a `Label` and add a `Picture` in that label. I need the arguments for the `QPicture()`. The probable I can use is, `QLabel.setPicture(self.QPicture)`.
`QPicture` is not what you want. `QPicture` records and replays `QPainter` commands. What you want is `QPixmap`. Give a filename to the `QPixmap` constructor, and set this pixmap to the label using `QLabel.setPixmap()`. An implementation example in python would be: ``` label = QLabel() pixmap = QPixmap('path_to_your...
How can I add a Picture to a QWidget in PyQt4
2,286,864
12
2010-02-18T07:11:01Z
2,308,718
16
2010-02-22T04:02:48Z
[ "python", "pyqt4" ]
How can I add or import a picture to a `QWidget`? I have found a clue. I can add a `Label` and add a `Picture` in that label. I need the arguments for the `QPicture()`. The probable I can use is, `QLabel.setPicture(self.QPicture)`.
Here is some code that does what you and @erelender described: ``` import os,sys from PyQt4 import QtGui app = QtGui.QApplication(sys.argv) window = QtGui.QMainWindow() window.setGeometry(0, 0, 400, 200) pic = QtGui.QLabel(window) pic.setGeometry(10, 10, 400, 100) #use full ABSOLUTE path to the image, not relative p...
Python : updating values in a dictionary
2,287,061
3
2010-02-18T08:04:54Z
2,287,104
7
2010-02-18T08:12:31Z
[ "python" ]
I have the following dictionary -> ``` key : (time,edge_list) ``` Now I want to increment all time values by 1. How do I do that? ``` dict_list = dict(key:(time+1,edge_list) for key:(time,edge_list) in dict_list) ```
``` dict((key, (time + 1, edge_list)) for (key, (time, edge_list)) in somedict.iteritems()) ```
Python : updating values in a dictionary
2,287,061
3
2010-02-18T08:04:54Z
2,287,124
8
2010-02-18T08:16:08Z
[ "python" ]
I have the following dictionary -> ``` key : (time,edge_list) ``` Now I want to increment all time values by 1. How do I do that? ``` dict_list = dict(key:(time+1,edge_list) for key:(time,edge_list) in dict_list) ```
``` >>> d={"key" : (100,"edge_list")} >>> for i,(time,edge_list) in d.items(): ... d[i] = time+1, edge_list ... >>> d {'key': (101, 'edge_list')} ```
How to do I integrate a 304 in Django?
2,287,387
5
2010-02-18T09:07:09Z
2,287,409
11
2010-02-18T09:10:50Z
[ "python", "django", "header", "http-status-code-304" ]
When a user requests the same page, with the same data...I'd like Django to return a 304, so that the browser doesn't have to load the page all over again. I'm new to this. How can this be done? Thanks.
There's extensive description in Django documentation: [Conditional view processing](https://docs.djangoproject.com/en/1.10/topics/conditional-view-processing/) Following tools are particularly useful: 1. `@last_modified` and `@etag` view decorators. You supply them with a function to compute the value from request a...
C++ - How to read Unicode characters( Hindi Script for e.g. ) using C++ or is there a better Way through some other programming language?
2,287,962
6
2010-02-18T10:51:32Z
2,289,918
7
2010-02-18T15:49:13Z
[ "c++", "python", "perl", "utf-8", "nlp" ]
I have a hindi script file like this: ``` 3. भारत का इतिहास काफी समृद्ध एवं विस्तृत है। ``` I have to write a program which adds a position to each and every word in each sentence. Thus the numbering for every line for a particular word position s...
Wow, already 6 answers and not a single one actually does what **mgj** wanted. **jkp** comes close, but then drops the ball by deleting the daṇḍa. Perl to the rescue. Less code, fewer bugs. ``` use utf8; use strict; use warnings; use Encode qw(decode); my $index; join ' ', map { $index++; "$_($index)" } split /\s...
python: two way partial credit card storing encrytion
2,288,448
2
2010-02-18T12:12:38Z
2,288,706
15
2010-02-18T12:57:28Z
[ "python", "django", "encryption", "credit-card" ]
For my ecommece site, I want to store partial credit card numbers as string, for this I need to encrypt the information to store at the database and decrypt when users want to reuse the already entered credit card info from earlier purchases without typing it all over again. I am using Django thus I need to solve this...
Before you go much further you should take a look at [PCI-DSS](https://www.pcisecuritystandards.org/), which governs exactly what processes you need to have in place to even consider storing encrypted card numbers. In short, you should seriously consider outsourcing to a 3rd party payment gateway. If once you've under...
What is the difference between running a script from the command line and from exec() with PHP?
2,289,046
6
2010-02-18T13:55:51Z
5,208,563
30
2011-03-06T03:49:37Z
[ "php", "python", "apache", "exec", "nltk" ]
I'm trying to run a Python script using exec() from within PHP. My command works fine when I run it directly using a `cmd` window, but it produces an error when I run it from `exec()` in PHP. My Python script uses [NTLK](http://www.nltk.org/) to find proper nouns. Example command: ``` "C:\Python25\python.exe" "C:\wam...
You have to run `nltk.download()` and choose 'maxent\_treebank\_pos\_tagger'. You must make a python script and in it put: ``` #!/usr/bin/python import nltk nltk.download('maxent_treebank_pos_tagger'); ``` then run it from command line. It will install the data files for the POS tagges, which you don't have installed...
Fast way to get N Min or Max elements from a list in Python
2,289,053
6
2010-02-18T13:56:41Z
2,289,108
8
2010-02-18T14:04:42Z
[ "python", "sorting" ]
I currently have a long list which is being sorted using a lambda function f. I then choose a random element from the first five elements. Something like: ``` f = lambda x: some_function_of(x, local_variable) my_list.sort(key=f) foo = choice(my_list[:4]) ``` This is a bottleneck in my program, according to the profil...
Use [`heapq.nlargest`](http://docs.python.org/library/heapq.html#heapq.nlargest) or [`heapq.nsmallest`](http://docs.python.org/library/heapq.html#heapq.nsmallest). For example: ``` import heapq elements = heapq.nsmallest(4, my_list, key=f) foo = choice(elements) ``` This will take O(N+KlogN) time (where K is the nu...
Complete django DB reset
2,289,187
14
2010-02-18T14:16:16Z
2,291,863
16
2010-02-18T20:13:13Z
[ "python", "django" ]
How do I completely reset my Django (1.2 alpha) DB (dropping all tables, rather than just clearing them)? `manage.py flush` does too little (won't work if there are schema changes) and `manage.py reset` requires me to specify all apps (and appears to take a format that is different from just " ".join(INSTALLED\_APPS))...
[This Snippet](http://www.djangosnippets.org/snippets/828/) gives you the code for a `manage.py reset_db` command you can install, it's the minimum change that solves your problem --- That said, from comments below: > You might as well just install Django command extensions to get > reset\_db and other goodies: > <h...
SQLAlchemy.declarative and deferred column loading
2,289,401
5
2010-02-18T14:44:38Z
2,291,351
10
2010-02-18T18:59:48Z
[ "python", "sqlalchemy" ]
is it possible to specify some columns in the SQLAlchemy to be deferred-loading? I am using the sqlalchemy.ext.declarative module to define my mapping, example: ``` from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class SomeClass(Base): __tablename__ = 'some_table' id = Colum...
Just add `deferred()` around the column declaration: ``` class SomeClass(Base): __tablename__ = 'some_table' id = Column(Integer, primary_key=True) name = deferred(Column(String(50))) ```
sort lines in text file, but only use the first N characters
2,289,870
9
2010-02-18T15:44:12Z
2,289,911
23
2010-02-18T15:48:27Z
[ "python", "datetime", "sorting" ]
I have a text file with lines like this: ``` 2010-02-18 11:46:46.1287 bla 2010-02-18 11:46:46.1333 foo 2010-02-18 11:46:46.1333 bar 2010-02-18 11:46:46.1467 bla ``` A simple sort would swap lines 2 and 3 (bar comes before foo), but I would like to keep lines (that have the same date/time) in their original order. Ho...
``` sorted(array, key=lambda x:x[:24]) ``` Example: ``` >>> a = ["wxyz", "abce", "abcd", "bcde"] >>> sorted(a) ['abcd', 'abce', 'bcde', 'wxyz'] >>> sorted(a, key=lambda x:x[:3]) ['abce', 'abcd', 'bcde', 'wxyz'] ```
Beginner extending C with Python (specifically Numpy)
2,290,007
6
2010-02-18T16:02:09Z
2,294,359
8
2010-02-19T05:53:47Z
[ "c++", "python", "c", "api", "numpy" ]
I am working on a real time audio processing dynamically linked library where I have a 2 dimensional C array of floating point data which represents the audio buffer. One dimension is time (samples) and the other is channel. I would like to pass this to a python script as a numpy array for the DSP processing and then I...
You may be able to avoid dealing with the NumPy C API entirely. Python can call C code using the `ctypes` module, and you can access pointers into the numpy data using the array's ctypes attribute. Here's a minimal example showing the process for a 1d sum-of-squares function. ## ctsquare.c ``` #include <stdlib.h> f...
How to solve this using regex?
2,290,859
2
2010-02-18T17:49:21Z
2,290,883
9
2010-02-18T17:53:49Z
[ "python", "regex" ]
Given that string: ``` \n \n text1\n \ttext2\n Message: 1st message\n some more text\n \n \n Message: 2dn message\n\n \t\t Message: 3rd message\n text3\n ``` I want to extract messages from a multiline string (token is 'Message: '). What regex expression should I use to capture those 3 groups: * group 1 : '1st m...
``` >>> re.findall('Message: (.+?)$', s, re.M) ['1st message', '2dn message', '3rd message'] ``` [`re.M` flag gives special meaning to `^` and `$`](http://docs.python.org/library/re.html#re.M): > When specified, the pattern character `'^'` matches at the beginning of the string and at the beginning of each line (imme...
is python variable assignment atomic?
2,291,069
13
2010-02-18T18:20:59Z
2,291,137
9
2010-02-18T18:30:09Z
[ "python", "signals" ]
Let's say I am using a `signal` handler for handling an interval timer. ``` def _aHandler(signum, _): global SomeGlobalVariable SomeGlobalVariable=True ``` Can I set `SomeGlobalVariable` without worrying that, in an unlikely scenario that whilst setting `SomeGlobalVariable` (i.e. the Python VM was executing bytec...
Simple assignment to simple variables is "atomic" AKA threadsafe (compound assignments such as `+=` or assignments to items or attributes of objects need not be, but your example is a simple assignment to a simple, albeit global, variable, thus safe).
django, python and link encryption
2,291,176
4
2010-02-18T18:36:19Z
2,291,403
7
2010-02-18T19:05:58Z
[ "python", "django", "encryption" ]
Hello I need to arrange some kind of encrpytion for generating user specific links. Users will be clicking this link and at some other view, related link with the crypted string will be decrypted and result will be returned. For this, I need some kind of encryption function that consumes a number(or a string) that is ...
There are no encryption algorithms, per se, built in to Python. However, you might want to look at the [Python Cryptography Toolkit](http://www.dlitz.net/software/pycrypto/) (PyCrypt). I've only tinkered with it, but it's referenced in Python's documentation on [cryptographic services](http://docs.python.org/library/cr...
Virtual Serial Device in Python?
2,291,772
21
2010-02-18T19:59:31Z
15,095,449
18
2013-02-26T17:29:44Z
[ "python", "serial-port", "pyserial", "virtual-serial-port" ]
I know that I can use e.g. pySerial to talk to serial devices, but what if I don't have a device right now but still need to write a client for it? How can I write a "virtual serial device" in Python and have pySerial talk to it, like I would, say, run a local web server? Maybe I'm just not searching well, but I've bee...
this is something I did and worked out for me so far: ``` import os, pty, serial master, slave = pty.openpty() s_name = os.ttyname(slave) ser = serial.Serial(s_name) # To Write to the device ser.write('Your text') # To read from the device os.read(master,1000) ``` If you create more virtual ports you will have no...
python timer mystery
2,292,054
7
2010-02-18T20:43:06Z
2,292,088
11
2010-02-18T20:48:58Z
[ "python", "timer", "signals" ]
Well, at least a mystery to me. Consider the following: ``` import time import signal def catcher(signum, _): print "beat!" signal.signal(signal.SIGALRM, catcher) signal.setitimer(signal.ITIMER_REAL, 2, 2) while True: time.sleep(5) ``` Works as expected i.e. delivers a "beat!" message every 2 seconds. Next...
From my system's man setitimer (emphasis mine): > The system provides each process with three interval timers, each decrementing in a **distinct time domain**. When any timer expires, a signal is sent to the process, and the timer (potentially) restarts. > > ITIMER\_REAL **decrements in real time**, and delivers SIGAL...
how can i get the executable's current directory in py2exe?
2,292,703
14
2010-02-18T22:24:54Z
2,293,106
20
2010-02-18T23:47:33Z
[ "python", "py2exe" ]
I use this bit of code in my script to pinpoint, in a cross-platform way, where exactly it's being run from: ``` SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) ``` Pretty simple. I then go on to use `SCRIPT_ROOT` in other areas of my script to make sure everything is properly relative. My problem occurs wh...
Here is the [py2exe documentation reference](http://www.py2exe.org/index.cgi/Py2exeEnvironment) and here are the relevant items: * `sys.executable` is set to the full pathname of the exe-file. * The first item in `sys.argv` is the full pathname of the executable, the rest are the command line arguments. * `sys.frozen`...
What Python/IronPython web development framework work on the Microsoft technology stack?
2,292,775
6
2010-02-18T22:39:10Z
2,292,863
7
2010-02-18T22:55:36Z
[ "python", "ironpython" ]
I started learning Python using the IronPython implementation. I'd like to do some web development now. I'm looking for a python web development framework that works on the Microsoft technology stack (IIS + MS SQL Server). Django looks like an interesting framework but based on what I have read, getting it to work on t...
Working with the full MS stack will be hard as not many FLOSS frameworks aim there. You'll have better luck with a WAMP (Windows/Apache/MySQL-PostgreSQL/Python) approach. That being said, Django works on Windows, and even [can be made to work under IIS](http://code.djangoproject.com/wiki/DjangoOnWindowsWithIISAndSQLSe...
Django memory usage going up with every request
2,293,333
20
2010-02-19T00:36:39Z
2,350,809
12
2010-02-28T10:50:55Z
[ "python", "django", "memory-leaks", "mod-wsgi" ]
I moved my first Django project from DjangoEurope to Webfaction, and that started an issue looking like a memory leak. With every single request memory usage of the server process goes up about 500kb. It never goes down. This goes on until Webfaction kills it for using too much memory. I can clearly see this when I re...
I'm afraid I haven't got any definite answers. Graham Dumpleton's tips were most helpfull, but unfortunately he didn't make an answer (just comments), so there is no way to accept his response. Although I still haven't fully resolved the issue, here are some basic tips for other people having similar problems: * Read...
How can I replace double and single quotations in a string efficiently?
2,293,854
2
2010-02-19T03:19:17Z
2,293,886
12
2010-02-19T03:28:53Z
[ "python", "database", "string" ]
I'm parsing a xml file and inserting it into database. However since some text containes double or single quotation I'm having problem with insertion. Currently I'm using the code shown below. But it seems it's inefficient. ``` s = s.replace('"', ' ') s = s.replace("'", ' ') ``` Is there any way I can insert text wit...
Why can't you insert strings containing quote marks into your database? Is there some weird data type that permits any character except a quote mark? Or are you building an `insert` statement with literal strings, rather than binding your strings to query parameters as you should be doing? If you're doing ``` cursor....
How do I define an array of custom types in WSDL?
2,293,873
8
2010-02-19T03:25:44Z
2,294,967
20
2010-02-19T08:43:04Z
[ "c#", "python", "web-services", "soap", "wsdl" ]
I'm very new to WSDL, but what I'm trying to do is very simple. I have gotten a web service working with python's ZSI library, but am stuck defining a service which returns an array of a custom type. In my WSDL I have the following: ``` <xsd:element name="ArtPiece"> <xsd:complexType> <xsd:sequence> ...
``` <xs:schema elementFormDefault="qualified" targetNamespace="http://schemas.datacontract.org/2004/07/Foo" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.datacontract.org/2004/07/Foo"> <xs:complexType name="ArtPiece"> <xs:sequence> <xs:...
Deferred evaluation in python
2,294,236
8
2010-02-19T05:18:34Z
2,294,285
13
2010-02-19T05:36:02Z
[ "python", "lambda", "interpreter", "evaluation" ]
I have heard of deferred evaluation in python (for example [here](http://wiki.python.org/moin/AlternateLambdaSyntax)), is it just referring to how lambdas are evaluated by the interpreter only when they are used? Or is this the proper term for describing how, due to python's dynamic design, it will not catch many error...
Deferred evaluation is when an expression isn't evaluated until it is needed. In most languages, you use something like `lambda` to make this work. Here's a contrived example that shows part of the concept: ``` def list_files(): for fn in os.listdir('.'): yield fn, lambda: open(fn, 'r').read() for fn, body...
Deferred evaluation in python
2,294,236
8
2010-02-19T05:18:34Z
2,294,489
7
2010-02-19T06:32:01Z
[ "python", "lambda", "interpreter", "evaluation" ]
I have heard of deferred evaluation in python (for example [here](http://wiki.python.org/moin/AlternateLambdaSyntax)), is it just referring to how lambdas are evaluated by the interpreter only when they are used? Or is this the proper term for describing how, due to python's dynamic design, it will not catch many error...
Dietrich's answer is a good one, but I just want to add that the simplest form of deferred evaluation is the `if` statement: ``` if True: x = 5 else: x = y # huh? what is y? ``` This code parses and runs correctly, although the `else` clause makes no sense - `y` is undefined. The `else` clause is only being pa...
How to get the position of a character in Python?
2,294,493
199
2010-02-19T06:32:57Z
2,294,502
244
2010-02-19T06:35:27Z
[ "python", "string" ]
How can I get the position of a character inside a string in python?
There are two string methods for this, `find` and `index`. Example: ``` >>> myString = "Position of a character" >>> myString.index('s') 2 ``` The difference is that `find` returns `-1` when what you're looking for isn't found. `index` throws an exception. > Function `str.find(sub[, start[, end]])` > Return the l...
How to get the position of a character in Python?
2,294,493
199
2010-02-19T06:32:57Z
2,294,510
26
2010-02-19T06:36:47Z
[ "python", "string" ]
How can I get the position of a character inside a string in python?
``` >>> s="mystring" >>> s.index("r") 4 >>> s.find("r") 4 ``` "Long winded" way ``` >>> for i,c in enumerate(s): ... if "r"==c: print i ... 4 ``` to get substring, ``` >>> s="mystring" >>> s[4:10] 'ring' ```
How to get the position of a character in Python?
2,294,493
199
2010-02-19T06:32:57Z
32,794,963
17
2015-09-26T07:59:52Z
[ "python", "string" ]
How can I get the position of a character inside a string in python?
Just for a sake of completeness, if you need to find all positions of a substring in a string, you can do the following: ``` s = 'shak#spea#e' c = '#' print [pos for pos, char in enumerate(s) if char == c] ``` which will return `[4, 9]`
Python : How to plot 3d graphs using Python?
2,294,588
19
2010-02-19T06:57:13Z
2,294,994
11
2010-02-19T08:51:33Z
[ "python", "matplotlib" ]
I am using matplotlib for doing this ``` from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib import matplotlib.pyplot as plt fig = plt.figure() ax = Axes3D(fig) x = [6,3,6,9,12,24] y = [3,5,78,12,23,56] ax.plot(x, y, zs=0, zdir='z', label='zs=0, zdir=z') plt.show() ``` Now this builds a g...
bp's answer might work fine, but there's a much simpler way. Your current graph is 'flat' on the z-axis, which is why it's horizontal. You want it to be vertical, which means that you want it to be 'flat' on the y-axis. This involves the tiniest modification to your code: ``` from mpl_toolkits.mplot3d import Axes3D i...
Python : How to plot 3d graphs using Python?
2,294,588
19
2010-02-19T06:57:13Z
4,042,582
7
2010-10-28T11:49:53Z
[ "python", "matplotlib" ]
I am using matplotlib for doing this ``` from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib import matplotlib.pyplot as plt fig = plt.figure() ax = Axes3D(fig) x = [6,3,6,9,12,24] y = [3,5,78,12,23,56] ax.plot(x, y, zs=0, zdir='z', label='zs=0, zdir=z') plt.show() ``` Now this builds a g...
Mayavi, in particular the [mlab](http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html) module, provides powerful 3D plotting that will work on large and or complex data, and should be easy to use on numpy arrays.
Python : How to plot 3d graphs using Python?
2,294,588
19
2010-02-19T06:57:13Z
12,330,848
7
2012-09-08T12:48:51Z
[ "python", "matplotlib" ]
I am using matplotlib for doing this ``` from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib import matplotlib.pyplot as plt fig = plt.figure() ax = Axes3D(fig) x = [6,3,6,9,12,24] y = [3,5,78,12,23,56] ax.plot(x, y, zs=0, zdir='z', label='zs=0, zdir=z') plt.show() ``` Now this builds a g...
You can set the view angle of the 3d plot with the view\_init() function. The example below is for version 1.1 of matplotlib. ``` from mpl_toolkits.mplot3d import axes3d import numpy as np import matplotlib import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = [6,3,6,9,12,...
assign multiple instances of a class to variables
2,294,823
2
2010-02-19T08:02:03Z
2,294,836
8
2010-02-19T08:06:16Z
[ "python" ]
Python. I need to assign multiple class instances to number of variables. First i tried this: ``` a = b = c = [] ``` but they all refer to the same object, which is not what I need. This works better: ``` (a, b, c) = [[] for i in range(3)] ``` but it seems a bit too verbose. Is there a shorter way to do this? UPDA...
simply: ``` a = [] b = [] c = [] ``` (python is not perl, there is no need for one-liners)
assign multiple instances of a class to variables
2,294,823
2
2010-02-19T08:02:03Z
2,294,847
9
2010-02-19T08:08:56Z
[ "python" ]
Python. I need to assign multiple class instances to number of variables. First i tried this: ``` a = b = c = [] ``` but they all refer to the same object, which is not what I need. This works better: ``` (a, b, c) = [[] for i in range(3)] ``` but it seems a bit too verbose. Is there a shorter way to do this? UPDA...
``` a, b, c = [], [], [] ```
What do (lambda) function closures capture in Python?
2,295,290
130
2010-02-19T09:46:31Z
2,295,368
87
2010-02-19T09:58:52Z
[ "python", "lambda", "closures" ]
Recently I started playing around with Python and I came around something peculiar in the way closures work. Consider the following code: ``` adders= [0,1,2,3] for i in [0,1,2,3]: adders[i]=lambda a: i+a print adders[1](3) ``` It builds a simple array of functions that take a single input and return that input ad...
Your second question has been answered, but as for your first: > what does the closure capture exactly? Scoping in Python is dynamic and lexical. A closure will always remember the name and scope of the variable, not the object it's pointing to. Since all the functions in your example are created in the same scope an...
What do (lambda) function closures capture in Python?
2,295,290
130
2010-02-19T09:46:31Z
2,295,372
94
2010-02-19T09:59:22Z
[ "python", "lambda", "closures" ]
Recently I started playing around with Python and I came around something peculiar in the way closures work. Consider the following code: ``` adders= [0,1,2,3] for i in [0,1,2,3]: adders[i]=lambda a: i+a print adders[1](3) ``` It builds a simple array of functions that take a single input and return that input ad...
you may force the capture of a variable using an argument with a default value: ``` >>> for i in [0,1,2,3]: ... adders[i]=lambda a,i=i: i+a # note the dummy parameter with a default value ... >>> print( adders[1](3) ) 4 ``` the idea is to declare a parameter (cleverly named `i`) and give it a default value of the...
What do (lambda) function closures capture in Python?
2,295,290
130
2010-02-19T09:46:31Z
2,295,659
9
2010-02-19T10:45:54Z
[ "python", "lambda", "closures" ]
Recently I started playing around with Python and I came around something peculiar in the way closures work. Consider the following code: ``` adders= [0,1,2,3] for i in [0,1,2,3]: adders[i]=lambda a: i+a print adders[1](3) ``` It builds a simple array of functions that take a single input and return that input ad...
Consider the following code: ``` x = "foo" def print_x(): print x x = "bar" print_x() # Outputs "bar" ``` I think most people won't find this confusing at all. It is the expected behaviour. So, why do people think it would be different when it is done in a loop? I know I did that mistake myself, but I don't k...
What do (lambda) function closures capture in Python?
2,295,290
130
2010-02-19T09:46:31Z
10,101,476
8
2012-04-11T07:11:57Z
[ "python", "lambda", "closures" ]
Recently I started playing around with Python and I came around something peculiar in the way closures work. Consider the following code: ``` adders= [0,1,2,3] for i in [0,1,2,3]: adders[i]=lambda a: i+a print adders[1](3) ``` It builds a simple array of functions that take a single input and return that input ad...
For completeness another answer to your second question: You could use [partial](http://docs.python.org/library/functools.html#functools.partial) in the [functools](http://docs.python.org/library/functools.html) module. With importing add from operator as Chris Lutz proposed the example becomes: ``` from functools im...
List minimum in Python with None?
2,295,461
13
2010-02-19T10:14:40Z
2,295,480
28
2010-02-19T10:16:54Z
[ "python", "list", "max", "minimum" ]
Is there any clever in-built function or something that will return `1` for the `min()` example below? (I bet there is a solid reason for it not to return anything, but in my particular case I need it to disregard `None` values really bad!) ``` >>> max([None, 1,2]) 2 >>> min([None, 1,2]) >>> ```
`None` is being returned ``` >>> print min([None, 1,2]) None >>> None < 1 True ``` If you want to return `1` you have to filter the `None` away: ``` >>> L = [None, 1, 2] >>> min(x for x in L if x is not None) 1 ```
Generating recurring dates using python?
2,295,765
15
2010-02-19T11:03:17Z
2,296,384
23
2010-02-19T12:59:26Z
[ "python", "date" ]
How can I generate recurring dates using Python? For example I want to generate recurring date for "Third Friday of every second month". I want to generate recurring dates for daily, weekly, monthly, yearly (i.e., same as the recurrence function in Outlook Express).
``` import dateutil.rrule as dr import dateutil.parser as dp import dateutil.relativedelta as drel start=dp.parse("19/02/2010") # Third Friday in Feb 2010 ``` This generates the third Friday of every month ``` rr = dr.rrule(dr.MONTHLY,byweekday=drel.FR(3),dtstart=start, count=10) ``` This prints every third Frida...
Python's equivalent to PHP's strip_tags?
2,295,942
16
2010-02-19T11:38:14Z
2,295,954
30
2010-02-19T11:40:07Z
[ "php", "python", "strip" ]
Python's equivalent to PHP's strip\_tags? <http://php.net/manual/en/function.strip-tags.php>
**There is no such thing in the Python standard library.** It's because Python is a general purpose language while PHP started as a Web oriented language. **Nevertheless, you have 3 solutions:** * You are in a hurry: just make your own. `re.sub(r'<[^>]*?>', '', value)` can be a quick and dirty solution. * Use a third...
Python's equivalent to PHP's strip_tags?
2,295,942
16
2010-02-19T11:38:14Z
2,295,964
15
2010-02-19T11:41:48Z
[ "php", "python", "strip" ]
Python's equivalent to PHP's strip\_tags? <http://php.net/manual/en/function.strip-tags.php>
Using [**BeautifulSoup**](http://www.crummy.com/software/BeautifulSoup/) ``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(htmltext) ''.join([e for e in soup.recursiveChildGenerator() if isinstance(e,unicode)]) ```
Highlighting python stack traces
2,297,044
18
2010-02-19T14:40:23Z
2,329,010
15
2010-02-24T19:54:15Z
[ "python", "debugging", "bash" ]
I'm working on quite complex project and time after time I have to narrow down problems looking at stack traces. They happen to be very long and involve “my” code, standard library code and 3rd party libraries code at same time. Most of time the real problem is in “my” code and locating it instantly in a stack ...
Actually, there is a great Python syntax highlighting library called [Pygments](http://pygments.org/), which is also able to highlight tracebacks. Here is an [example](http://paste.pocoo.org/show/182168/) (the pastebin here uses Pygments). So, all you have to do is: ``` $ easy_install pygments # downloads and install...
Python using derived class's method in parent class?
2,297,843
7
2010-02-19T16:25:38Z
2,297,875
8
2010-02-19T16:29:07Z
[ "python", "inheritance", "new-style-class" ]
Can I force a parent class to call a derived class's version of a function? ``` class Base(object): attr1 = '' attr2 = '' def virtual(self): pass # doesn't do anything in the parent class def func(self): print "%s, %s" % (self.attr1, self.attr2) self.virtual() ``...
If you instantiate a `Derived` (say `d = Derived()`), the `.virtual` that's called by `d.func()` **is** `Derived.virtual`. If there is no instance of `Derived` involved, then there's no suitable `self` for `Derived.virtual` and so of course it's impossible to call it.
Scripting language for trading strategy development
2,297,889
15
2010-02-19T16:31:00Z
2,297,994
8
2010-02-19T16:43:01Z
[ "python", "ruby", "scripting", "dsl", "trading" ]
I'm currently working on a component of a trading product that will allow a quant or strategy developer to write their own custom strategies. I obviously can't have them write these strategies in natively compiled languages (or even a language that compiles to a bytecode to run on a vm) since their dev/test cycles have...
It sounds like you might need to create some sort of Domain Specific Language (DSL) for your users that could be built loosely on top of the target language. Ruby, Python and Lua all have their various quirks regarding syntax, and to a degree some of these can be massaged with clever function definitions. An example o...
Scripting language for trading strategy development
2,297,889
15
2010-02-19T16:31:00Z
2,298,064
10
2010-02-19T16:51:50Z
[ "python", "ruby", "scripting", "dsl", "trading" ]
I'm currently working on a component of a trading product that will allow a quant or strategy developer to write their own custom strategies. I obviously can't have them write these strategies in natively compiled languages (or even a language that compiles to a bytecode to run on a vm) since their dev/test cycles have...
Mark-Jason Dominus, the author of Perl's [Text::Template](http://search.cpan.org/perldoc?Text%3a%3aTemplate) module, has some insights that might be relevant: > When people make a template module > like this one, they almost always > start by inventing a special syntax > for substitutions. For example, they > build it...
Creating a custom sys.stdout class?
2,297,933
5
2010-02-19T16:35:41Z
2,298,003
10
2010-02-19T16:44:19Z
[ "python", "stdout" ]
What I'm trying to do is simply have the output of some terminal commands print out to a wx.TextCtrl widget. I figured the easiest way to accomplish this is to create a custom stdout class and overload the write function to that of the widget. stdout class: ``` class StdOut(sys.stdout): def __init__(self,txtctrl)...
`sys.stdout` is **not** a `class`, it's an **instance** (of type `file`). So, just do: ``` class StdOut(object): def __init__(self,txtctrl): self.txtctrl = txtctrl def write(self,string): self.txtctrl.write(string) sys.stdout = StdOut(the_text_ctrl) ``` No need to inherit from `file`, just m...
Python's standard library - is there a module for balanced binary tree?
2,298,165
36
2010-02-19T17:06:42Z
2,298,197
12
2010-02-19T17:10:56Z
[ "python", "tree", "standard-library" ]
Is there a module for AVL or Red-Black or some other type of a balanced binary tree in the standard library of Python? I have tried to find one, but unsuccessfully (I'm relatively new to Python).
there is nothing of this sort in stdlib, [as far as I can see](http://docs.python.org/library/), but [quick look at pypi brings up a few alternative](http://pypi.python.org/pypi?%3Aaction=search&term=tree&submit=search): * [rbtree](http://pypi.python.org/pypi/rbtree) * [pyavl](http://pypi.python.org/pypi/pyavl) * [bli...
Python's standard library - is there a module for balanced binary tree?
2,298,165
36
2010-02-19T17:06:42Z
2,298,316
17
2010-02-19T17:26:14Z
[ "python", "tree", "standard-library" ]
Is there a module for AVL or Red-Black or some other type of a balanced binary tree in the standard library of Python? I have tried to find one, but unsuccessfully (I'm relatively new to Python).
No, there is not a balanced binary tree in the stdlib. However, from your comments, it sounds like you may have some other options: * You say that you want a BST instead of a list for `O(log n)` searches. If searching is all you need and your data are already sorted, the `bisect` module provides a binary search algori...
Fitting a line in 3D
2,298,390
11
2010-02-19T17:37:02Z
2,333,251
31
2010-02-25T10:28:15Z
[ "python", "numpy", "linear-algebra", "curve-fitting" ]
Are there any algorithms that will return the equation of a straight line from a set of 3D data points? I can find plenty of sources which will give the equation of a line from 2D data sets, but none in 3D. Thanks.
If you are trying to predict one value from the other two, then you should use `lstsq` with the `a` argument as your independent variables (plus a column of 1's to estimate an intercept) and `b` as your dependent variable. If, on the other hand, you just want to get the best fitting line to the data, i.e. the line whi...
Are any of these quad-tree libraries any good?
2,298,517
10
2010-02-19T17:59:45Z
13,362,187
7
2012-11-13T14:08:25Z
[ "python", "performance", "quadtree" ]
It appears that a certain project of mine will require the use of quad-trees, something that I have never worked with before. From what I have read they should allow substantial performance enhancements than a brute-force attempt at the problem would yield. Are any of these python modules any good? * [Quadtree 0.1.2](...
In [this comment](http://stackoverflow.com/questions/9810775/name-of-this-algorithm-and-is-there-a-numpy-scipy-implementation-of-it#comment12497888_9810817), [joferkington](http://stackoverflow.com/users/325565/joferkington) refers to the current question and says: > Just for whatever it's worth, scipy.spatial.KDTree ...
IRC bot can't join channel
2,299,210
3
2010-02-19T20:06:24Z
9,966,039
11
2012-04-01T16:23:32Z
[ "python", "irc" ]
``` import socket irc = 'irc.hack3r.com' port = 6667 channel = '#chat' sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect((irc, port)) sck.send('NICK supaBOT\r\n') sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n') sck.send('JOIN #chat' + '\r\n') data = '' while True: data = sck.recv(40...
Mike Graham is wrong. What's wrong is you send the JOIN command too early. It takes a while for the server to register your NICK and USER commands, hence the error "Nick not registered". See this reply: [Python IRC bot won't join](http://stackoverflow.com/questions/4770598/python-irc-bot-wont-join). I would also like ...
How to I extract floats from a file in Python?
2,299,609
2
2010-02-19T21:14:21Z
2,299,631
11
2010-02-19T21:16:16Z
[ "python", "list", "floating-point", "loops" ]
So, I have a file that looks like this: ``` # 3e98.mtz MR_AUTO with model 200la_.pdb SPACegroup HALL P 2yb #P 1 21 1 SOLU SET RFZ=3.0 TFZ=4.7 PAK=0 LLG=30 SOLU 6DIM ENSE 200la_ EULER 321.997 124.066 234.744 FRAC -0.14681 0.50245 -0.05722 SOLU SET RFZ=3.3 TFZ=4.2 PAK=0 LLG=30 SOLU 6DIM ENSE 200la_ EULER 329.492 34.325 ...
Here's one way. ``` def floats( aList ): for v in aList: try: yield float(v) except ValueError: pass a = list( floats( [....] ) ) ```
How to I extract floats from a file in Python?
2,299,609
2
2010-02-19T21:14:21Z
2,299,644
7
2010-02-19T21:17:16Z
[ "python", "list", "floating-point", "loops" ]
So, I have a file that looks like this: ``` # 3e98.mtz MR_AUTO with model 200la_.pdb SPACegroup HALL P 2yb #P 1 21 1 SOLU SET RFZ=3.0 TFZ=4.7 PAK=0 LLG=30 SOLU 6DIM ENSE 200la_ EULER 321.997 124.066 234.744 FRAC -0.14681 0.50245 -0.05722 SOLU SET RFZ=3.3 TFZ=4.2 PAK=0 LLG=30 SOLU 6DIM ENSE 200la_ EULER 329.492 34.325 ...
``` floats = [] all = ['#', '3e98.mtz', 'MR_AUTO', 'with', 'model', '200la_.pdb', 'SPACegroup', 'HALL', 'P', '2yb', '#P', '1', '21', '1', 'SOLU', 'SET', 'RFZ=3.0', 'TFZ=4.7', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '321.997', '124.066', '234.744', 'FRAC', '-0.14681', '0.50245', '-0.05722', 'SOLU',...
Get the nth item of a generator in Python
2,300,756
25
2010-02-20T02:11:36Z
2,300,766
24
2010-02-20T02:15:36Z
[ "python", "generator" ]
Is there a more syntactically concise way of writing the following? ``` gen = (i for i in xrange(10)) index = 5 for i, v in enumerate(gen): if i is index: return v ``` It seems almost natural that a generator should have a `gen[index]` expression, that acts as a list, but is functionally identical to the ...
one method would be to use `itertools.islice` ``` >>> next(itertools.islice(xrange(10), 5, 5 + 1)) 5 ```
Get the nth item of a generator in Python
2,300,756
25
2010-02-20T02:11:36Z
2,300,768
12
2010-02-20T02:17:31Z
[ "python", "generator" ]
Is there a more syntactically concise way of writing the following? ``` gen = (i for i in xrange(10)) index = 5 for i, v in enumerate(gen): if i is index: return v ``` It seems almost natural that a generator should have a `gen[index]` expression, that acts as a list, but is functionally identical to the ...
You could do this, using `count` as an example generator: ``` from itertools import islice, count next(islice(count(), n, n+1)) ```
PySerial App runs in shell, by not py script
2,301,127
4
2010-02-20T05:06:29Z
2,308,078
7
2010-02-22T00:14:32Z
[ "python", "shell", "serial-port", "arduino", "pyserial" ]
I have a very simple python script that uses pySerial to send data over the serial port to my Arduino. When I execute this line-by-line in the python shell, it works just fine, but when I put it in a ".py" file, and try to run it, nothing happens. Though the serial lights on my UART do flash. So something is getting th...
OK, I've figured it out! It's necessary to use code like this before performing the write: ``` time.sleep(1) ser.setDTR(level=0) time.sleep(1) ``` Otherwise, the arduino automatically resets upon receiving a serial connection for some reason. yay!
Creating HTML in python
2,301,163
19
2010-02-20T05:18:18Z
2,301,169
8
2010-02-20T05:21:27Z
[ "python", "html" ]
I am looking for a way to create html files dynamically in python. I am writing a gallery script, which iterates over directories, collecting file meta data. I intended to then use this data to automatically create a picture gallery, based on html. Something very simple, just a table of pictures. I really don't think ...
Use a templating engine such as [Genshi](http://genshi.edgewall.org/) or [Jinja2](http://jinja.pocoo.org/2/).
Creating HTML in python
2,301,163
19
2010-02-20T05:18:18Z
2,301,176
9
2010-02-20T05:22:29Z
[ "python", "html" ]
I am looking for a way to create html files dynamically in python. I am writing a gallery script, which iterates over directories, collecting file meta data. I intended to then use this data to automatically create a picture gallery, based on html. Something very simple, just a table of pictures. I really don't think ...
I think, if i understand you correct, you can see [here](http://wiki.python.org/moin/Templating).
Creating HTML in python
2,301,163
19
2010-02-20T05:18:18Z
23,926,002
9
2014-05-29T05:02:55Z
[ "python", "html" ]
I am looking for a way to create html files dynamically in python. I am writing a gallery script, which iterates over directories, collecting file meta data. I intended to then use this data to automatically create a picture gallery, based on html. Something very simple, just a table of pictures. I really don't think ...
[Dominate](https://github.com/Knio/dominate) is a Python library for creating HTML documents and fragments directly in code without using templating. You could create a simple image gallery with something like this: ``` import glob from dominate import document from dominate.tags import * photos = glob.glob('photos/*...
Python multiple threads accessing same file
2,301,458
10
2010-02-20T07:38:57Z
2,301,462
7
2010-02-20T07:40:59Z
[ "python", "file", "multithreading" ]
I have two threads, one which writes to a file, and another which periodically moves the file to a different location. The writes always calls `open` before writing a message, and calls `close` after writing the message. The mover uses shutil.move to do the move. I see that after the first move is done, the writer can...
When two threads access the same resources, weird things happen. To avoid that, always lock the resource. Python has the convenient `threading.Lock` for that, as well as some other tools (see documentation of the `threading` module).
Python multiple threads accessing same file
2,301,458
10
2010-02-20T07:38:57Z
2,302,427
22
2010-02-20T14:02:37Z
[ "python", "file", "multithreading" ]
I have two threads, one which writes to a file, and another which periodically moves the file to a different location. The writes always calls `open` before writing a message, and calls `close` after writing the message. The mover uses shutil.move to do the move. I see that after the first move is done, the writer can...
Locking is a possible solution, but I prefer the general architecture of having each external resource (including a file) dealt with by a single, separate thread. Other threads send work requests to the dedicated thread on a [Queue.Queue](http://docs.python.org/library/queue.html?highlight=queue.queue#Queue.Queue) inst...
Read a file in reverse order using python
2,301,789
59
2010-02-20T10:09:26Z
2,301,792
46
2010-02-20T10:10:52Z
[ "python", "file", "reverse" ]
How to read a file in reverse order using python? I want to read a file from last line to first line.
``` for line in reversed(open("filename").readlines()): print line.rstrip() ``` And in Python 3: ``` for line in reversed(list(open("filename"))): print(line.rstrip()) ```