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
Multiple Unpacking Assignment in Python when you don't know the sequence length
2,531,776
5
2010-03-28T03:17:54Z
2,531,790
10
2010-03-28T03:23:49Z
[ "python", "variable-assignment" ]
The textbook examples of multiple unpacking assignment are something like: ``` import numpy as NP M = NP.arange(5) a, b, c, d, e = M # so of course, a = 0, b = 1, etc. M = NP.arange(20).reshape(5, 4) # numpy 5x4 array a, b, c, d, e = M # here, a = M[0,:], b = M[1,:], etc. (ie, a single row of M is assigned each t...
Python 3.x can do this easily: ``` a, b, *c = someseq ``` Python 2.x needs a bit more work: ``` (a, b), c = someseq[:2], someseq[2:] ```
How to use a custom comparison function in Python 3?
2,531,952
34
2010-03-28T05:04:35Z
2,531,971
20
2010-03-28T05:15:53Z
[ "python", "sorting", "python-3.x" ]
In **Python 2.x**, I could pass custom function to sorted and .sort functions ``` >>> x=['kar','htar','har','ar'] >>> >>> sorted(x) ['ar', 'har', 'htar', 'kar'] >>> >>> sorted(x,cmp=customsort) ['kar', 'htar', 'har', 'ar'] ``` Because, in *My* language, consonents are comes with this order ``` "k","kh",....,"ht",.....
Use the `key` argument (and follow the [recipe](http://code.activestate.com/recipes/576653-convert-a-cmp-function-to-a-key-function/) on how to convert your old `cmp` function to a `key` function).
How to use a custom comparison function in Python 3?
2,531,952
34
2010-03-28T05:04:35Z
2,532,009
9
2010-03-28T05:35:35Z
[ "python", "sorting", "python-3.x" ]
In **Python 2.x**, I could pass custom function to sorted and .sort functions ``` >>> x=['kar','htar','har','ar'] >>> >>> sorted(x) ['ar', 'har', 'htar', 'kar'] >>> >>> sorted(x,cmp=customsort) ['kar', 'htar', 'har', 'ar'] ``` Because, in *My* language, consonents are comes with this order ``` "k","kh",....,"ht",.....
Instead of a customsort(), you need a function that translates each word into something that Python already knows how to sort. For example, you could translate each word into a list of numbers where each number represents where each letter occurs in your alphabet. Something like this: ``` my_alphabet = ['a', 'b', 'c']...
How to use a custom comparison function in Python 3?
2,531,952
34
2010-03-28T05:04:35Z
23,756,830
7
2014-05-20T10:08:22Z
[ "python", "sorting", "python-3.x" ]
In **Python 2.x**, I could pass custom function to sorted and .sort functions ``` >>> x=['kar','htar','har','ar'] >>> >>> sorted(x) ['ar', 'har', 'htar', 'kar'] >>> >>> sorted(x,cmp=customsort) ['kar', 'htar', 'har', 'ar'] ``` Because, in *My* language, consonents are comes with this order ``` "k","kh",....,"ht",.....
Use the `key` keyword and [functools.cmp\_to\_key](https://docs.python.org/3/library/functools.html#functools.cmp_to_key) to transform your comparison function: ``` sorted(x, key=functools.cmp_to_key(customsort)) ```
Validate a hostname string
2,532,053
16
2010-03-28T05:58:52Z
2,532,344
31
2010-03-28T08:52:51Z
[ "python", "regex", "validation", "hostname", "fqdn" ]
Following up to [Regular expression to match hostname or IP Address?](http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address) and using [Restrictions on valid host names](http://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names) as a reference, what is the most readab...
``` import re def is_valid_hostname(hostname): if len(hostname) > 255: return False if hostname[-1] == ".": hostname = hostname[:-1] # strip exactly one dot from the right, if present allowed = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE) return all(allowed.match(x) for x in h...
Python: How do sets work
2,532,365
25
2010-03-28T08:59:30Z
2,532,368
37
2010-03-28T09:01:05Z
[ "python", "hash", "set" ]
I have a list of objects which I want to turn into a set. My objects contain a few fields that some of which are `o.id` and `o.area`. I want two objects to be equal if these two fields are the same. ie: `o1==o2` if and only if `o1.area==o2.area and o1.id==o2.id`. I tried over-writing `__eq__` and `__cmp__` but I get t...
Define the `__hash__` method to return a meaningful hash based on the id and area fields. E.g.: ``` def __hash__(self): return hash(self.id) ^ hash(self.area) ```
Python: How do sets work
2,532,365
25
2010-03-28T08:59:30Z
2,533,387
9
2010-03-28T15:19:51Z
[ "python", "hash", "set" ]
I have a list of objects which I want to turn into a set. My objects contain a few fields that some of which are `o.id` and `o.area`. I want two objects to be equal if these two fields are the same. ie: `o1==o2` if and only if `o1.area==o2.area and o1.id==o2.id`. I tried over-writing `__eq__` and `__cmp__` but I get t...
"TypeError: unhashable instance." error is probably due to old-style class definition i.e.: ``` class A: pass ``` Use new style instead: ``` class A(object): pass ``` If you override \_\_cmp\_\_ function you **should** override \_\_hash\_\_ for using your object in sets. In the other case hash considers all obj...
Django: Paginator + raw SQL query
2,532,475
9
2010-03-28T09:54:59Z
2,532,552
7
2010-03-28T10:31:37Z
[ "python", "sql", "django", "pagination" ]
I'm using Django Paginator everywhere on my website and even wrote a special template tag, to make it more convenient. But now I got to a state, where I need to make a complex custom raw SQL query, that without a `LIMIT` will return about 100K records. **How can I use Django Pagintor with custom query?** Simplified e...
Looking at Paginator's source code, [page() function](http://code.djangoproject.com/browser/django/tags/releases/1.1.1/django/core/paginator.py#L35) in particular, I think that it's only matter of implementing [slicing](http://docs.python.org/reference/datamodel.html#object.__getslice__) on your side, and translating t...
mod_cgi , mod_fastcgi, mod_scgi , mod_wsgi, mod_python, FLUP. I don't know how many more. what is mod_php equivalent?
2,532,477
10
2010-03-28T09:56:30Z
2,532,642
9
2010-03-28T11:01:11Z
[ "php", "python", "apache" ]
I recently learnt Python. I liked it. I just wanted to use it for web development. This thought caused all the troubles. But I like these troubles :) Coming from PHP world where there is only one way standardized. I expected the same and searched for python & apache. <http://stackoverflow.com/questions/449055/setting...
The standard way to deploy a Python application to the web is via WSGI. These days there's no reason to use anything else. mod\_wsgi is the Apache module that supports WSGI. Other web servers will have different names for their WSGI modules.
Show default value for editing on Python input possible?
2,533,120
35
2010-03-28T13:51:45Z
2,533,134
14
2010-03-28T13:57:33Z
[ "python", "input" ]
Is it possible for python to accept input like this: ``` Folder name: Download ``` But instead of the user typing "Download" it is already there as a initial value. If the user wants to edit it as "Downloads" all he has to do is add a 's' and press enter. Using normal input command: ``` folder=input('Folder name: '...
I'm assuming you mean from the command-line. I've never seen initial values for command line prompts, they're usually of the form: ``` Folder [default] : ``` which in code is simply: ``` res = raw_input('Folder [default] : ') res = res or 'default' ``` Alternatively, you can try to do something using...
Show default value for editing on Python input possible?
2,533,120
35
2010-03-28T13:51:45Z
2,533,142
43
2010-03-28T14:01:02Z
[ "python", "input" ]
Is it possible for python to accept input like this: ``` Folder name: Download ``` But instead of the user typing "Download" it is already there as a initial value. If the user wants to edit it as "Downloads" all he has to do is add a 's' and press enter. Using normal input command: ``` folder=input('Folder name: '...
The standard library functions `input()` and `raw_input()` don't have this functionality. If you're using Linux you can use the [`readline`](http://docs.python.org/library/readline.html) module to define an input function that uses a prefill value and advanced line editing: ``` def rlinput(prompt, prefill=''): read...
Show default value for editing on Python input possible?
2,533,120
35
2010-03-28T13:51:45Z
5,888,246
7
2011-05-04T18:33:34Z
[ "python", "input" ]
Is it possible for python to accept input like this: ``` Folder name: Download ``` But instead of the user typing "Download" it is already there as a initial value. If the user wants to edit it as "Downloads" all he has to do is add a 's' and press enter. Using normal input command: ``` folder=input('Folder name: '...
This works in windows. ``` import win32console _stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) def input_def(prompt, default=''): keys = [] for c in unicode(default): evt = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT) evt.Char = c evt.RepeatCount = 1 ...
how to convert Python 3 to Python 2 code?
2,533,217
14
2010-03-28T14:23:29Z
2,533,224
20
2010-03-28T14:24:40Z
[ "python", "python-3.x" ]
I had written a program in Python 3, but now want to convert it into Python 2 code. Are there any utilities to do that automatically?
You want [`3to2`](http://wiki.python.org/moin/3to2) for that.
How to setup and teardown temporary django db for unit testing?
2,533,457
8
2010-03-28T15:41:27Z
2,533,957
7
2010-03-28T18:13:39Z
[ "python", "django", "unit-testing", "mercurial" ]
I would like to have a python module containing some unit tests that I can pass to `hg bisect --command`. The unit tests are testing some functionality of a django app, but I don't think I can use `hg bisect --command manage.py test mytestapp` because `mytestapp` would have to be enabled in settings.py, and the edits ...
Cracked it. I now have one python file completely independent of any django app that can run unit tests with a test database: ``` #!/usr/bin/env python """Run a unit test and return result. This can be used with `hg bisect`. It is assumed that this file resides in the same dir as settings.py """ import os from os.p...
Why are dates calculated from January 1st, 1970?
2,533,563
28
2010-03-28T16:18:46Z
2,533,567
33
2010-03-28T16:21:11Z
[ "java", "python", "programming-languages" ]
Is there any reason behind using date(January 1st, 1970) as default standard for time manipulation? I have seen this standard in Java as well as in Python. These two languages I am aware of. Are there other popular languages which follows the same standard? Please describe.
It is the standard of [Unix time.](http://en.wikipedia.org/wiki/Unix_time) > Unix time, or POSIX time, is a system for describing points in time, defined as the number of seconds elapsed since midnight proleptic Coordinated Universal Time (UTC) of January 1, 1970, not counting leap seconds.
Why are dates calculated from January 1st, 1970?
2,533,563
28
2010-03-28T16:18:46Z
26,391,999
10
2014-10-15T20:59:15Z
[ "java", "python", "programming-languages" ]
Is there any reason behind using date(January 1st, 1970) as default standard for time manipulation? I have seen this standard in Java as well as in Python. These two languages I am aware of. Are there other popular languages which follows the same standard? Please describe.
The Question makes two false assumptions: * All time-tracking in computing is done as a count-since-1970. * Such tracking is standard. # Two Dozen Epochs Time in computing is *not always* tracked from the beginning of 1970 [UTC](http://en.wikipedia.org/wiki/Coordinated_Universal_Time). While that [epoch](http://en.w...
Proper way to reload a python module from the console
2,534,480
13
2010-03-28T20:43:27Z
2,534,513
20
2010-03-28T20:53:06Z
[ "python" ]
I'm debugging from the python console and would like to reload a module every time I make a change so I don't have to exit the console and re-enter it. I'm doing: ``` >>> from project.model.user import * >>> reload(user) ``` but I receive: ``` >>>NameError: name 'user' is not defined ``` What is the proper way to r...
As asked, the best you can do is ``` >>> from project.models.user import * >>> import project # get module reference for reload >>> reload(project.models.user) # reload step 1 >>> from project.models.user import * # reload step 2 ``` it would be better and cleaner if you used the user module directly, rather than doi...
Rest Web Service with App Engine and Webapp
2,534,947
10
2010-03-28T23:06:30Z
2,534,984
14
2010-03-28T23:21:01Z
[ "python", "google-app-engine", "rest", "web-applications" ]
I want to build a REST web service on app engine. Currently i have this: ``` from google.appengine.ext import webapp from google.appengine.ext.webapp import util class UsersHandler(webapp.RequestHandler): def get(self, name): self.response.out.write('Hello '+ name+'!') def main(): util.run_wsgi_app(applicati...
Sure, you can -- change your handler's `get` method to ``` def get(self, name=None): if name is None: """deal with the /rest/users case""" else: # deal with the /rest/users/(.*) case self.response.out.write('Hello '+ name+'!') ``` and your application to ``` application = webapp.WSGIA...
Catching a python app before it exits
2,535,403
7
2010-03-29T01:54:55Z
2,535,418
8
2010-03-29T02:01:40Z
[ "python", "crash" ]
I have a python app which is supposed to be very long-lived, but sometimes the process just disappears and I don't know why. Nothing gets logged when this happens, so I'm at a bit of a loss. Is there some way in code I can hook in to an exit event, or some other way to get some of my code to run just before the proces...
[`atexit`](http://docs.python.org/library/atexit.html) is pronounced "at exit". The first times I read that function name, I read it as "a texit", which doesn't make *nearly* as much sense.
passing an argument to a custom save() method
2,535,435
4
2010-03-29T02:09:29Z
2,535,481
10
2010-03-29T02:26:18Z
[ "python", "django", "django-models" ]
How do I pass an argument to my custom save method, preserving proper `*args`, `**kwargs` for passing to te super method? I was trying something like: ``` form.save(my_value) ``` and ``` def save(self, my_value=None, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) print my_value ``` But this do...
Keyword arguments must follow the positional arguments. Try this instead: ``` def save(self, my_value, *args, **kwargs): .... ``` or: ``` def save(self, *args, **kwargs): my_value = kwargs.pop('my_value', None) ```
How to change the value of None in Python?
2,535,477
8
2010-03-29T02:25:20Z
2,535,491
13
2010-03-29T02:30:21Z
[ "python", "syntax" ]
I'm currently reading chapter 5.8 of Dive Into Python and Mark Pilgrim says: > There are no constants in Python. Everything can be changed if you try hard enough. This fits with one of the core principles of Python: bad behavior should be discouraged but not banned. If you really want to change the value of None, you ...
You first have to install an *old* version of Python (I think it needs to be 2.2 or older). In 2.4 and newer for certain (and I believe in 2.3) the assignment in question is a syntax error. Mark's excellent book is, alas, a bit dated by now.
Python try...except comma vs 'as' in except
2,535,760
170
2010-03-29T04:16:56Z
2,535,764
17
2010-03-29T04:18:29Z
[ "python", "python-2.6" ]
What is the difference between ',' and 'as' in except statements, eg: ``` try: pass except Exception, exception: pass ``` and: ``` try: pass except Exception as exception: pass ``` Is the second syntax legal in 2.6? It works in CPython 2.6 on Windows but the 2.5 interpreter in cygwin complains that ...
the "as" syntax is the preferred one going forward, however if your code needs to work with older Python versions (2.6 is the first to support the new one) then you'll need to use the comma syntax.
Python try...except comma vs 'as' in except
2,535,760
170
2010-03-29T04:16:56Z
2,535,770
189
2010-03-29T04:19:44Z
[ "python", "python-2.6" ]
What is the difference between ',' and 'as' in except statements, eg: ``` try: pass except Exception, exception: pass ``` and: ``` try: pass except Exception as exception: pass ``` Is the second syntax legal in 2.6? It works in CPython 2.6 on Windows but the 2.5 interpreter in cygwin complains that ...
The definitive document is [PEP-3110: Catching Exceptions](http://www.python.org/dev/peps/pep-3110/) Summary: * In Python 3.x, using `as` is *required*. * In Python 2.6+, use the `as` syntax, since it is far less ambiguous and forward compatible with Python 3.x. * In Python 2.5 and earlier, use the comma version, sin...
Python try...except comma vs 'as' in except
2,535,760
170
2010-03-29T04:16:56Z
2,535,882
30
2010-03-29T05:07:56Z
[ "python", "python-2.6" ]
What is the difference between ',' and 'as' in except statements, eg: ``` try: pass except Exception, exception: pass ``` and: ``` try: pass except Exception as exception: pass ``` Is the second syntax legal in 2.6? It works in CPython 2.6 on Windows but the 2.5 interpreter in cygwin complains that ...
Yes it's legal. I'm running Python 2.6 ``` try: [] + 3 except Exception as x: print "woo hoo" >>> woo hoo ``` **Update**: There is another reason to use the `as` syntax. Using `,` makes things a lot more ambiguous, as others have pointed out; and here's what makes the difference. As of Python 2.6, there is ...
Copy **kwargs to self?
2,535,917
12
2010-03-29T05:21:06Z
2,535,926
11
2010-03-29T05:25:08Z
[ "python", "syntax" ]
Given ``` class ValidationRule: def __init__(self, **kwargs): # code here ``` Is there a way that I can define `__init__` such that if I were to initialize the class with something like `ValidationRule(other='email')` then `self.other` would be "added" to class without having to explicitly name every poss...
You could do something like this: ``` class ValidationRule: def __init__(self, **kwargs): for (k, v) in kwargs.items(): setattr(self, k, v) ```
Copy **kwargs to self?
2,535,917
12
2010-03-29T05:21:06Z
2,535,952
15
2010-03-29T05:35:55Z
[ "python", "syntax" ]
Given ``` class ValidationRule: def __init__(self, **kwargs): # code here ``` Is there a way that I can define `__init__` such that if I were to initialize the class with something like `ValidationRule(other='email')` then `self.other` would be "added" to class without having to explicitly name every poss...
I think somewhere on the stackoverflow I've seen such solution Anyway it can look like: ``` class ValidationRule: __allowed = ("other", "same", "different") def __init__(self, **kwargs): for k, v in kwargs.iteritems(): assert( k in self.__class__.__allowed ) setattr(self, k, v) ...
Copy **kwargs to self?
2,535,917
12
2010-03-29T05:21:06Z
2,535,964
7
2010-03-29T05:39:49Z
[ "python", "syntax" ]
Given ``` class ValidationRule: def __init__(self, **kwargs): # code here ``` Is there a way that I can define `__init__` such that if I were to initialize the class with something like `ValidationRule(other='email')` then `self.other` would be "added" to class without having to explicitly name every poss...
This may not be the cleanest way, but it works: ``` class ValidationRule: def __init__(self, **kwargs): self.__dict__.update(kwargs) ``` I think I prefer [ony's solution](http://stackoverflow.com/questions/2535917/copy-kwargs-to-self/2535952#2535952) because it restricts available properties to keep you...
Simple way to create possible case
2,535,924
2
2010-03-29T05:24:04Z
2,535,934
11
2010-03-29T05:28:11Z
[ "python", "methods", "module", "case" ]
I have lists of data such as ``` a = [1,2,3,4] b = ["a","b","c","d","e"] c = ["001","002","003"] ``` And I want to create new another list that was mixed from all possible case of a,b,c like this ``` d = ["1a001","1a002","1a003",...,"4e003"] ``` Is there any module or method to generate d without write many for loo...
``` [''.join(str(y) for y in x) for x in itertools.product(a, b, c)] ```
decorators in the python standard lib (@deprecated specifically)
2,536,307
27
2010-03-29T07:14:57Z
2,536,365
7
2010-03-29T07:31:13Z
[ "python", "decorator" ]
I need to mark routines as deprecated, but apparently there's no standard library decorator for deprecation. I am aware of recipes for it and the warnings module, but my question is: why is there no standard library decorator for this (common) task ? Additional question: are there standard decorators in the standard l...
[`classmethod()`](http://docs.python.org/library/functions.html#classmethod), [`staticmethod()`](http://docs.python.org/library/functions.html#staticmethod), and the various [`property`](http://docs.python.org/library/functions.html#property) decorators are the important ones. There's also one in [`contextlib`](http://...
decorators in the python standard lib (@deprecated specifically)
2,536,307
27
2010-03-29T07:14:57Z
30,253,848
8
2015-05-15T07:24:28Z
[ "python", "decorator" ]
I need to mark routines as deprecated, but apparently there's no standard library decorator for deprecation. I am aware of recipes for it and the warnings module, but my question is: why is there no standard library decorator for this (common) task ? Additional question: are there standard decorators in the standard l...
Here's some snippet, modified from those cited by Leandro: ``` import warnings import functools def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.""" @functools.wraps(func) def new_f...
How to write Unix end of line characters in Windows using Python
2,536,545
38
2010-03-29T08:17:22Z
2,536,560
39
2010-03-29T08:19:59Z
[ "python", "newline" ]
How can I write to files using Python (on Windows) and use the Unix end of line character? e.g. When doing: ``` f = open('file.txt', 'w') f.write('hello\n') f.close() ``` Python automatically replaces \n with \r\n.
Open the file as binary to prevent the translation of end-of-line characters: ``` f = open('file.txt', 'wb') ``` Quoting the Python manual: > On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and ...
How to write Unix end of line characters in Windows using Python
2,536,545
38
2010-03-29T08:17:22Z
23,434,608
35
2014-05-02T18:25:12Z
[ "python", "newline" ]
How can I write to files using Python (on Windows) and use the Unix end of line character? e.g. When doing: ``` f = open('file.txt', 'w') f.write('hello\n') f.close() ``` Python automatically replaces \n with \r\n.
## The modern way: use newline='' Use the `newline=` keyword parameter to [io.open()](https://docs.python.org/2/library/io.html#io.open) to use Unix-style LF end-of-line terminators: ``` import io f = io.open('file.txt', 'w', newline='') # newline='' means don't convert \n ``` This works in Python 2.6+. In Python ...
How do I join the values of nested Python dictionary?
2,536,625
3
2010-03-29T08:32:37Z
2,536,686
7
2010-03-29T08:45:36Z
[ "python" ]
Suppose I have a dictionary, and it's nested with dictionaries inside. I want to join all the values of that dictionary, recursively? ``` ' '.join(d.values()) ``` That works if there are no nests.
The following works for any non-recursive nested dicts: ``` def flatten_dict_values(d): values = [] for value in d.itervalues(): if isinstance(value, dict): values.extend(flatten_dict_values(value)) else: values.append(value) return values >>> " ".join(flatten_dict_...
Python Introspection: How to get varnames of class methods?
2,536,879
3
2010-03-29T09:28:33Z
2,536,979
9
2010-03-29T09:47:55Z
[ "python", "class", "introspection" ]
I want to get the names of the keyword arguments of the methods of a class. I think I understood how to get the names of the methods and how to get the variable names of a specific method, but I don't get how to combine these: ``` class A(object): def A1(self, test1=None): self.test1 = test1 def A2(sel...
``` import inspect for name, method in inspect.getmembers(a, inspect.ismethod): print name (args, varargs, varkw, defaults) = inspect.getargspec(method) for arg in args: print arg ```
method of iterating over sqlalchemy model's defined columns?
2,537,471
55
2010-03-29T11:27:43Z
2,537,548
49
2010-03-29T11:42:07Z
[ "python", "sqlalchemy" ]
I've been trying to figure out how to iterate over the list of columns defined in a SqlAlchemy model. I want it for writing some serialization and copy methods to a couple of models. I can't just iterate over the obj.**dict** since it contains a lot of SA specific items. Anyone know of a way to just get the id, and de...
You can get the list of defined properties from the mapper. For your case you're interested in only ColumnProperty objects. ``` from sqlalchemy.orm import class_mapper import sqlalchemy def attribute_names(cls): return [prop.key for prop in class_mapper(cls).iterate_properties if isinstance(prop, sqlalche...
method of iterating over sqlalchemy model's defined columns?
2,537,471
55
2010-03-29T11:27:43Z
2,540,598
44
2010-03-29T19:14:55Z
[ "python", "sqlalchemy" ]
I've been trying to figure out how to iterate over the list of columns defined in a SqlAlchemy model. I want it for writing some serialization and copy methods to a couple of models. I can't just iterate over the obj.**dict** since it contains a lot of SA specific items. Anyone know of a way to just get the id, and de...
You could use the following function: ``` def __unicode__(self): return "[%s(%s)]" % (self.__class__.__name__, ', '.join('%s=%s' % (k, self.__dict__[k]) for k in sorted(self.__dict__) if '_sa_' != k[:4])) ``` It will exclude SA *magic* attributes, but will not exclude the relations. So basically it might load the...
method of iterating over sqlalchemy model's defined columns?
2,537,471
55
2010-03-29T11:27:43Z
12,631,974
17
2012-09-28T00:24:21Z
[ "python", "sqlalchemy" ]
I've been trying to figure out how to iterate over the list of columns defined in a SqlAlchemy model. I want it for writing some serialization and copy methods to a couple of models. I can't just iterate over the obj.**dict** since it contains a lot of SA specific items. Anyone know of a way to just get the id, and de...
I realise that this is an old question, but I've just come across the same requirement and would like to offer an alternative solution to future readers. As Josh notes, full SQL field names will be returned by `JobStatus.__table__.columns`, so rather than the original field name *id*, you will get *jobstatus.id*. Not ...
method of iterating over sqlalchemy model's defined columns?
2,537,471
55
2010-03-29T11:27:43Z
13,752,442
7
2012-12-06T20:58:58Z
[ "python", "sqlalchemy" ]
I've been trying to figure out how to iterate over the list of columns defined in a SqlAlchemy model. I want it for writing some serialization and copy methods to a couple of models. I can't just iterate over the obj.**dict** since it contains a lot of SA specific items. Anyone know of a way to just get the id, and de...
`self.__table__.columns` will "only" give you the columns defined in that particular class, i.e. without inherited ones. if you need all, use `self.__mapper__.columns`. in your example i'd probably use something like this: ``` class JobStatus(Base): ... def __iter__(self): values = vars(self) ...
Using urllib2 with SOCKS proxy
2,537,726
13
2010-03-29T12:17:38Z
2,570,384
15
2010-04-03T05:54:34Z
[ "python", "urllib2", "socks" ]
Is it possible to fetch pages with urllib2 through a SOCKS proxy on a one socks server per opener basic? I've seen the solution using setdefaultproxy method, but I need to have different socks in different openers. So there is SocksiPy library, which works great, but it has to be used this way: ``` import socks impor...
Try with [pycurl](http://pycurl.sourceforge.net/): ``` import pycurl c1 = pycurl.Curl() c1.setopt(pycurl.URL, 'http://www.google.com') c1.setopt(pycurl.PROXY, 'localhost') c1.setopt(pycurl.PROXYPORT, 8080) c1.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5) c2 = pycurl.Curl() c2.setopt(pycurl.URL, 'http://www.yahoo....
Using urllib2 with SOCKS proxy
2,537,726
13
2010-03-29T12:17:38Z
8,478,479
10
2011-12-12T17:43:59Z
[ "python", "urllib2", "socks" ]
Is it possible to fetch pages with urllib2 through a SOCKS proxy on a one socks server per opener basic? I've seen the solution using setdefaultproxy method, but I need to have different socks in different openers. So there is SocksiPy library, which works great, but it has to be used this way: ``` import socks impor...
Yes, you can. I repeat my answer on [How can I use a SOCKS 4/5 proxy with urllib2?](http://stackoverflow.com/a/8100870/88231) You need to create an opener for every proxy like you do with an http proxy. The code for adding this feature to SocksiPy is available in GitHub <https://gist.github.com/869791> and is as simple...
Sans-serif math with latex in matplotlib
2,537,868
12
2010-03-29T12:39:38Z
20,709,149
15
2013-12-20T17:43:00Z
[ "python", "latex", "matplotlib" ]
The following script: ``` import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as mpl mpl.rc('font', family='sans-serif') mpl.rc('text', usetex=True) fig = mpl.figure() ax = fig.add_subplot(1,1,1) ax.text(0.2,0.5,r"Math font: $451^\circ$") ax.text(0.2,0.7,r"Normal font (except for degree symbol): 451$^\c...
I always have `text.usetex = True` in my matplotlibrc file. In addition to that, I use this as well: ``` mpl.rcParams['text.latex.preamble'] = [ r'\usepackage{siunitx}', # i need upright \micro symbols, but you need... r'\sisetup{detect-all}', # ...this to force siunitx to actually use your fonts ...
Sans-serif math with latex in matplotlib
2,537,868
12
2010-03-29T12:39:38Z
20,791,035
7
2013-12-26T20:47:27Z
[ "python", "latex", "matplotlib" ]
The following script: ``` import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as mpl mpl.rc('font', family='sans-serif') mpl.rc('text', usetex=True) fig = mpl.figure() ax = fig.add_subplot(1,1,1) ax.text(0.2,0.5,r"Math font: $451^\circ$") ax.text(0.2,0.7,r"Normal font (except for degree symbol): 451$^\c...
The easiest way is to use matplotlib's internal TeX, e.g.: ``` import pylab as plt params = {'text.usetex': False, 'mathtext.fontset': 'stixsans'} plt.rcParams.update(params) ``` If you use an external LaTeX, you can use, e.g., CM Bright fonts: ``` params = {'text.usetex': True, 'text.latex.preamble': [r'...
Is it possible to temporarily disable Python's string interpolation?
2,537,929
5
2010-03-29T12:49:28Z
2,537,969
7
2010-03-29T12:55:38Z
[ "python", "string-interpolation" ]
I have a python logger set up, using python's logging module. I want to store the string I'm using with the logging Formatter object in a configuration file using the ConfigParser module. The format string is stored in a dictionary of settings in a separate file that handles the reading and writing of the config file....
Did you try to escape percents with `%%`?
Is it possible to temporarily disable Python's string interpolation?
2,537,929
5
2010-03-29T12:49:28Z
2,538,141
8
2010-03-29T13:21:17Z
[ "python", "string-interpolation" ]
I have a python logger set up, using python's logging module. I want to store the string I'm using with the logging Formatter object in a configuration file using the ConfigParser module. The format string is stored in a dictionary of settings in a separate file that handles the reading and writing of the config file....
You might wanna use `ConfigParser.RawConfigParser` instead of `ConfigParser.ConfigParser`. Only the latter does magical interpolation on config values. **EDIT:** Actually, using `ConfigParser.SafeConfigParser` you'll able to escape format strings with an additional `%` percent sign. This example should be working the...
Sunrise / set calculations
2,538,190
5
2010-03-29T13:29:45Z
2,539,597
10
2010-03-29T16:31:20Z
[ "python", "math", "astronomy" ]
I'm trying to calculate the sunset / rise times using python based on the link provided below. My results done through excel and python do not match the real values. Any ideas on what I could be doing wrong? My Excel sheet can be found under .. <http://transpotools.com/sun_time.xls> ``` # Created on 2010-03-28 # @a...
You could use [`ephem`](http://pypi.python.org/pypi/pyephem/) python module: ``` #!/usr/bin/env python import datetime import ephem # to install, type$ pip install pyephem def calculate_time(d, m, y, lat, long, is_rise, utc_time): o = ephem.Observer() o.lat, o.long, o.date = lat, long, datetime.date(y, m, d) ...
How can I format strings to query with mysqldb in Python?
2,538,311
6
2010-03-29T13:47:50Z
2,538,362
8
2010-03-29T13:55:11Z
[ "python", "string", "mysql" ]
How do I do this correctly: I want to do a query like this: ``` query = """SELECT * FROM sometable order by %s %s limit %s, %s;""" conn = app_globals.pool.connection() cur = conn.cursor() cur.execute(query, (sortname, sortorder, limit1, limit2) ) results = cur.fetchall() ```...
> [paramstyle > Parameter placeholders can **only** be used to insert column values. They can **not** be used for other parts of SQL, such as table names, statements, etc.](http://mysql-python.sourceforge.net/MySQLdb.html#functions-and-attributes)
python: image to 2-dimensional list
2,539,002
2
2010-03-29T15:11:58Z
2,539,014
12
2010-03-29T15:13:29Z
[ "python" ]
Is there a python lib that could make a 2-dimensional list of (R,G,B) data out of an image file?
You might want to take a look at the [Python Imaging Library](http://www.pythonware.com/library/pil/handbook/image.htm). It has the ability to be directly converted to a 2 by 2 by 3 [numpy array](http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html): ``` from PIL import Image import numpy im = Image....
Logging users out of a Django site after N minutes of inactivity
2,539,109
9
2010-03-29T15:24:57Z
2,539,307
20
2010-03-29T15:50:00Z
[ "python", "django", "authentication" ]
I'm working on a website that requires us to log a user out after N minutes of inactivity. Are there any best practices for this using Django?
Take a look at the [session middleware](http://docs.djangoproject.com/en/dev/topics/http/sessions/#topics-http-sessions) and its settings. Specifically these two: > SESSION\_COOKIE\_AGE > > Default: 1209600 (2 weeks, in seconds) > > The age of session cookies, in > seconds. > > SESSION\_SAVE\_EVERY\_REQUEST > > Defaul...
Python if statement efficiency
2,539,116
8
2010-03-29T15:25:38Z
2,539,148
23
2010-03-29T15:31:24Z
[ "python", "performance" ]
A friend (fellow low skill level recreational python scripter) asked me to look over some code. I noticed that he had 7 separate statements that basically said. ``` if ( a and b and c): do something ``` the statements a,b,c all tested their equality or lack of to set values. As I looked at it I found that because...
`if` statements will skip everything in an `else` bracket if it evaluates to true. It should be noted that worrying about this sort of problem, unless it's done millions of times per program execution, is called "premature optimization" and should be avoided. If your code is clearer with three `if (a and b and c)` stat...
Python if statement efficiency
2,539,116
8
2010-03-29T15:25:38Z
2,539,153
8
2010-03-29T15:32:09Z
[ "python", "performance" ]
A friend (fellow low skill level recreational python scripter) asked me to look over some code. I noticed that he had 7 separate statements that basically said. ``` if ( a and b and c): do something ``` the statements a,b,c all tested their equality or lack of to set values. As I looked at it I found that because...
At least in python, efficiency is second to readability and "Flat is better than nested". See [The Zen of Python](http://www.python.org/dev/peps/pep-0020/)
Python if statement efficiency
2,539,116
8
2010-03-29T15:25:38Z
2,539,157
21
2010-03-29T15:32:22Z
[ "python", "performance" ]
A friend (fellow low skill level recreational python scripter) asked me to look over some code. I noticed that he had 7 separate statements that basically said. ``` if ( a and b and c): do something ``` the statements a,b,c all tested their equality or lack of to set values. As I looked at it I found that because...
I would say the single test is as fast as the separate tests. Python also makes use of so called [**short-circuit evaluation**](http://en.wikipedia.org/wiki/Short-circuit_evaluation). That means for `(a and b and c)`, that `b` or `c` would not be tested anymore if `a` is `false`. Similar, if you have an `OR` expressi...
Python if statement efficiency
2,539,116
8
2010-03-29T15:25:38Z
2,539,161
11
2010-03-29T15:32:46Z
[ "python", "performance" ]
A friend (fellow low skill level recreational python scripter) asked me to look over some code. I noticed that he had 7 separate statements that basically said. ``` if ( a and b and c): do something ``` the statements a,b,c all tested their equality or lack of to set values. As I looked at it I found that because...
Code: ``` import dis def foo(): if ( a and b and c): pass else: pass def bar(): if a: if b: if c: pass print 'foo():' dis.dis(foo) print 'bar():' dis.dis(bar) ``` Output: ``` foo(): 4 0 LOAD_GLOBAL 0 (a) 3 JUMP_IF_FALSE 18 (to 24) ...
How do I set a matplotlib colorbar extents?
2,539,331
4
2010-03-29T15:53:27Z
2,539,590
7
2010-03-29T16:30:28Z
[ "python", "matplotlib" ]
I'd like to display a colorbar representing an image's raw values along side a matplotlib imshow subplot which displays that image, normalized. I've been able to draw the image and a colorbar successfully like this, but the colorbar min and max values represent the normalized (0,1) image instead of the raw (0,99) imag...
It looks like you passed the wrong object to the colorbar constructor. This should work: ``` # make namespace explicit from matplotlib import pyplot as PLT cbar = fig.colorbar(result) ``` The snippet above is based on the code in your answer; here's a complete, stand-alone example: ``` import numpy as NP from matp...
How to create a draggable legend in matplotlib?
2,539,477
31
2010-03-29T16:15:47Z
2,546,149
21
2010-03-30T14:50:24Z
[ "python", "matplotlib", "draggable", "legend" ]
I'm drawing a legend on an axes object in matplotlib but the default positioning which claims to place it in a smart place doesn't seem to work. Ideally, I'd like to have the legend be draggable by the user. How can this be done?
Note: This is now built into matplotlib ``` leg = plt.legend() if leg: leg.draggable() ``` will work as expected --- Well, I found bits and pieces of the solution scattered among mailing lists. I've come up with a nice modular chunk of code that you can drop in and use... here it is: ``` class DraggableLegend:...
How to create a draggable legend in matplotlib?
2,539,477
31
2010-03-29T16:15:47Z
7,477,491
11
2011-09-19T21:25:50Z
[ "python", "matplotlib", "draggable", "legend" ]
I'm drawing a legend on an axes object in matplotlib but the default positioning which claims to place it in a smart place doesn't seem to work. Ideally, I'd like to have the legend be draggable by the user. How can this be done?
In newer versions of Matplotlib (v1.0.1), this is built-in. ``` def draw(self): ax = self.figure.add_subplot(111) scatter = ax.scatter(np.random.randn(100), np.random.randn(100)) legend = ax.legend() legend.draggable(state=True) ``` If you are using matplotlib interactively (for example, in IPython's...
Return current 11-digit timestamp in Python
2,540,043
8
2010-03-29T17:46:33Z
2,540,058
17
2010-03-29T17:48:40Z
[ "python", "timestamp" ]
How can I return the current time of the local machine?
Do you mean this: [time.time()](http://docs.python.org/library/time.html#time.time)? From the docs: *Return the time as a floating point number expressed in seconds since the epoch, in UTC* ``` >>> import time >>> time.time() 1269884900.480978 >>> ```
Scipy sparse... arrays?
2,540,059
25
2010-03-29T17:48:57Z
6,754,832
24
2011-07-19T22:23:11Z
[ "python", "matrix", "numpy", "scipy", "sparse-matrix" ]
So, I'm doing some Kmeans classification using numpy arrays that are quite sparse-- lots and lots of zeroes. I figured that I'd use scipy's 'sparse' package to reduce the storage overhead, but I'm a little confused about how to create arrays, not matrices. I've gone through this tutorial on how to create sparse matric...
Use a `scipy.sparse` format that is row or column based: `csc_matrix` and `csr_matrix`. These use efficient, C implementations under the hood (including multiplication), and transposition is a no-op (esp. if you call `transpose(copy=False)`), just like with numpy arrays. EDIT: some timings via [ipython](http://ipytho...
How can I check for unused import in many Python files?
2,540,202
24
2010-03-29T18:12:06Z
2,540,211
8
2010-03-29T18:13:33Z
[ "python" ]
I remember when I was developing in C++ or Java, the compiler usually complains for unused methods, functions or imports. In my Django project, I have a bunch of Python files which have gone through a number of iterations. Some of those files have a few lines of import statement at the top of the page and some of those...
Use a tool like [pylint](http://www.logilab.org/857) which will signal these code defects (among a lot of others). Doing these kinds of 'pre-runtime' checks is hard in a language with dynamic typing, but pylint does a terrific job at catching these typos / leftovers from refactoring etc ...
How can I check for unused import in many Python files?
2,540,202
24
2010-03-29T18:12:06Z
2,540,221
22
2010-03-29T18:15:18Z
[ "python" ]
I remember when I was developing in C++ or Java, the compiler usually complains for unused methods, functions or imports. In my Django project, I have a bunch of Python files which have gone through a number of iterations. Some of those files have a few lines of import statement at the top of the page and some of those...
[PyFlakes](https://launchpad.net/pyflakes) (similar to lint) will give you this information.
how to handle an asymptote/discontinuity with Matplotlib
2,540,294
18
2010-03-29T18:27:09Z
2,542,065
10
2010-03-30T00:05:24Z
[ "python", "numpy", "matplotlib", "equation", "sympy" ]
When plotting a graph with a discontinuity/asymptote/singularity/whatever, is there any automatic way to prevent Matplotlib from 'joining the dots' across the 'break'? (please see code/image below). I read that Sage has a [detect\_poles] facility that looked good, but I really want it to work with Matplotlib. ``` im...
This may not be the elegant solution you are looking for, but if just want results for most cases, you can "clip" large and small values of your plotted data to `+∞` and `-∞` respectively. Matplotlib does not plot these. Of course you have to be careful not to make your resolution too low or your clipping threshold...
how to handle an asymptote/discontinuity with Matplotlib
2,540,294
18
2010-03-29T18:27:09Z
2,543,391
17
2010-03-30T07:06:17Z
[ "python", "numpy", "matplotlib", "equation", "sympy" ]
When plotting a graph with a discontinuity/asymptote/singularity/whatever, is there any automatic way to prevent Matplotlib from 'joining the dots' across the 'break'? (please see code/image below). I read that Sage has a [detect\_poles] facility that looked good, but I really want it to work with Matplotlib. ``` im...
By using [masked arrays](http://docs.scipy.org/doc/numpy/reference/maskedarray.html) you can avoid plotting selected regions of a curve. To remove the singularity at x=2: ``` import matplotlib.numerix.ma as M # for older versions, prior to .98 #import numpy.ma as M # for newer versions of matplotlib...
Tell if a given login exists in Linux using Python
2,540,460
8
2010-03-29T18:54:02Z
2,540,487
8
2010-03-29T18:57:47Z
[ "python", "login" ]
In Python under Linux, what is the easiest way to check the existence of a user, given his/her login? Anything better than issuing 'ls ~login-name' and checking the exit code? And if running under Windows?
To look up my userid (`bagnew`) under Unix: ``` import pwd pw = pwd.getpwnam("bagnew") uid = pw.pw_uid ``` See the [pwd](http://docs.python.org/library/pwd.html) module info for more.
Tell if a given login exists in Linux using Python
2,540,460
8
2010-03-29T18:54:02Z
15,168,560
11
2013-03-01T23:23:45Z
[ "python", "login" ]
In Python under Linux, what is the easiest way to check the existence of a user, given his/her login? Anything better than issuing 'ls ~login-name' and checking the exit code? And if running under Windows?
This answer builds upon the [answer by Brian](http://stackoverflow.com/a/2540487/832230). It adds the necessary `try...except` block. Check if a user exists: ``` import pwd try: pwd.getpwnam('someusr') except KeyError: print('User someusr does not exist.') ``` Check if a group exists: ``` import grp try: ...
What is the Python equivalent of Perl's FindBin?
2,540,481
6
2010-03-29T18:57:09Z
2,540,559
12
2010-03-29T19:08:41Z
[ "python", "perl", "path" ]
In Perl, the [`FindBin`](http://perldoc.perl.org/FindBin.html) module is used to locate the directory of the original script. What's the canonical way to get this directory in Python? Some of the options I've seen: * `os.path.dirname(os.path.realpath(sys.argv[0]))` * `os.path.abspath(os.path.dirname(sys.argv[0]))` * ...
You can try this: ``` import os bindir = os.path.abspath(os.path.dirname(__file__)) ``` That will give you the absolute path of the current file's directory.
Is there a Python equivalent to Perl's Data::Dumper?
2,540,567
25
2010-03-29T19:09:48Z
2,540,660
21
2010-03-29T19:26:23Z
[ "python", "module", "object-dumper" ]
Is there a Python module that can be used in the same way as Perl's [`Data::Dumper`](http://search.cpan.org/~smueller/Data-Dumper-2.125/Dumper.pm) module? **Edit:** Sorry, I should have been clearer. I was mainly after a module for inspecting data rather than persisting. BTW Thanks for the answers. This is one awesom...
Data::Dumper has two main uses: data persistence and debugging/inspecting objects. As far as I know, there isn't anything that's going to work exactly the same as Data::Dumper. I use [pickle](http://docs.python.org/library/pickle.html) for data persistence. I use [pprint](http://docs.python.org/library/pprint.html) t...
Pairwise crossproduct in Python
2,541,401
47
2010-03-29T21:27:38Z
2,541,412
68
2010-03-29T21:29:02Z
[ "python", "list" ]
How can I get the list of cross product *pairs* from a list of arbitrarily long lists in Python? ## Example ``` a = [1, 2, 3] b = [4, 5, 6] ``` `crossproduct(a,b)` should yield `[[1, 4], [1, 5], [1, 6], ...]`.
You're looking for [itertools.product](http://docs.python.org/library/itertools.html#itertools.product) if you're on (at least) Python 2.6. ``` >>> import itertools >>> a=[1,2,3] >>> b=[4,5,6] >>> itertools.product(a,b) <itertools.product object at 0x10049b870> >>> list(itertools.product(a,b)) [(1, 4), (1, 5), (1, 6),...
Pairwise crossproduct in Python
2,541,401
47
2010-03-29T21:27:38Z
2,541,422
54
2010-03-29T21:30:37Z
[ "python", "list" ]
How can I get the list of cross product *pairs* from a list of arbitrarily long lists in Python? ## Example ``` a = [1, 2, 3] b = [4, 5, 6] ``` `crossproduct(a,b)` should yield `[[1, 4], [1, 5], [1, 6], ...]`.
Since you asked for a list: ``` [(x, y) for x in a for y in b] ``` But you can avoid the overhead of a list if you're just looping through these by using generators instead: ``` ((x, y) for x in a for y in b) ``` Behaves identically in a `for` loop but doesn't result in the creation of a `list`.
Pairwise crossproduct in Python
2,541,401
47
2010-03-29T21:27:38Z
19,832,454
8
2013-11-07T09:39:33Z
[ "python", "list" ]
How can I get the list of cross product *pairs* from a list of arbitrarily long lists in Python? ## Example ``` a = [1, 2, 3] b = [4, 5, 6] ``` `crossproduct(a,b)` should yield `[[1, 4], [1, 5], [1, 6], ...]`.
Using generators there is no need for itertools, simply: ``` gen = ((x, y) for x in a for y in b) for u, v in gen: print u, v ```
Exposing a pointer in Boost.Python
2,541,446
10
2010-03-29T21:34:41Z
2,541,549
17
2010-03-29T21:55:41Z
[ "c++", "python", "boost", "boost-python" ]
I have this very simple C++ class: ``` class Tree { public: Node *head; }; BOOST_PYTHON_MODULE(myModule) { class_<Tree>("Tree") .def_readwrite("head",&Tree::head) ; } ``` I want to access the head variable from Python, but the message I see is: ``` No to_python (by-value) converter found...
Of course, I find the answer ten minutes after asking the question...here's how it's done: ``` class_<Tree>("Tree") .add_property("head", make_getter(&Tree::head, return_value_policy<reference_existing_object>()), make_setter(&Tree::head, return_value_policy<reference_existing_object>())) ; ```
iterating through a list removing items, some items are not removed
2,541,528
7
2010-03-29T21:51:47Z
2,541,537
8
2010-03-29T21:53:09Z
[ "python", "list" ]
I'm trying to transfer the contents of one list to another, but it's not working and I don't know why not. My code looks like this: ``` list1 = [1, 2, 3, 4, 5, 6] list2 = [] for item in list1: list2.append(item) list1.remove(item) ``` But if I run it my output looks like this: ``` >>> list1 [2, 4, 6] >>> li...
You're deleting items from list1 while you're iterating over it. That's asking for trouble. Try this: ``` >>> list1 = [1,2,3,4,5,6] >>> list2 = [] >>> list2 = list1[:] # we copy every element from list1 using a slice >>> del list1[:] # we delete every element from list1 ```
iterating through a list removing items, some items are not removed
2,541,528
7
2010-03-29T21:51:47Z
2,541,557
8
2010-03-29T21:57:11Z
[ "python", "list" ]
I'm trying to transfer the contents of one list to another, but it's not working and I don't know why not. My code looks like this: ``` list1 = [1, 2, 3, 4, 5, 6] list2 = [] for item in list1: list2.append(item) list1.remove(item) ``` But if I run it my output looks like this: ``` >>> list1 [2, 4, 6] >>> li...
The reason is that you're (appending and) **removing** from the first list whereby it gets smaller. So the iterator stops before the whole list could be walked through. To achieve what you want, do this: ``` list1 = [1, 2, 3, 4, 5, 6] list2 = [] # You couldn't just make 'list1_copy = list1', # because this would jus...
Why am I getting a " instance has no attribute '__getitem__' " error?
2,541,718
11
2010-03-29T22:38:11Z
2,541,775
22
2010-03-29T22:48:17Z
[ "python" ]
Here's the code: ``` class BinaryTree: def __init__(self,rootObj): self.key = rootObj self.left = None self.right = None root = [self.key, self.left, self.right] def getRootVal(root): return root[0] def setRootVal(newVal): root[0] = newVal def getLeftC...
Because you declared your methods wrong: Lets have a look what happens if you call `tree.getRootVal()`. `.getRootVal()` is declared this way: ``` def getRootVal(root): return root[0] ``` As you probably know, the first parameter passed to a method is always the instance and it is provided implicitly. So you basi...
Most secure way to generate a random session ID for a cookie?
2,541,742
6
2010-03-29T22:42:53Z
2,541,800
7
2010-03-29T22:51:54Z
[ "python", "cookies", "session", "security" ]
I'm writing my own sessions controller that issues a unique id to a user once logged in, and then verifies and authenticates that unique id at every page load. What is the most secure way to generate such an id? Should the unique id be completely random? Is there any downside to including the user id as part of the uni...
Go buy Bruce Schneier's [Secrets and Lies](http://www.schneier.com/book-sandl.html) and his [Practical Cryptography](http://www.schneier.com/book-practical.html). Go ahead and order Ross Anderson's [Security Engineering 2nd Ed.](http://www.cl.cam.ac.uk/~rja14/book.html) while you're at it. Now, read Secrets and Lies --...
how best do I find the intersection of multiple sets in python?
2,541,752
98
2010-03-29T22:44:19Z
2,541,807
7
2010-03-29T22:53:30Z
[ "python", "set", "set-intersection" ]
I have a list of sets: ``` setlist = [s1,s2,s3...] ``` I want s1 ∩ s2 ∩ s3 ... I can write a function to do it by performing a series of pairwise `s1.intersection(s2)`, etc. Is there a recommended, better, or built-in way?
If you don't have Python 2.6 or higher, the alternative is to write an explicit for loop: ``` def set_list_intersection(set_list): if not set_list: return set() result = set_list[0] for s in set_list[1:]: result &= s return result set_list = [set([1, 2]), set([1, 3]), set([1, 4])] print set_list_inter...
how best do I find the intersection of multiple sets in python?
2,541,752
98
2010-03-29T22:44:19Z
2,541,814
186
2010-03-29T22:55:34Z
[ "python", "set", "set-intersection" ]
I have a list of sets: ``` setlist = [s1,s2,s3...] ``` I want s1 ∩ s2 ∩ s3 ... I can write a function to do it by performing a series of pairwise `s1.intersection(s2)`, etc. Is there a recommended, better, or built-in way?
From Python version 2.6 on you can use multiple arguments to [`set.intersection()`](http://docs.python.org/library/stdtypes.html#set.intersection), like ``` u = set.intersection(s1, s2, s3) ``` If the sets are in a list, this translates to: ``` u = set.intersection(*setlist) ``` where `*a_list` is [list expansion](...
how best do I find the intersection of multiple sets in python?
2,541,752
98
2010-03-29T22:44:19Z
2,541,823
19
2010-03-29T22:58:49Z
[ "python", "set", "set-intersection" ]
I have a list of sets: ``` setlist = [s1,s2,s3...] ``` I want s1 ∩ s2 ∩ s3 ... I can write a function to do it by performing a series of pairwise `s1.intersection(s2)`, etc. Is there a recommended, better, or built-in way?
As of 2.6, `set.intersection` takes arbitrarily many iterables. ``` >>> s1 = set([1, 2, 3]) >>> s2 = set([2, 3, 4]) >>> s3 = set([2, 4, 6]) >>> s1 & s2 & s3 set([2]) >>> s1.intersection(s2, s3) set([2]) >>> sets = [s1, s2, s3] >>> set.intersection(*sets) set([2]) ```
Copying 2D lists in python
2,541,865
12
2010-03-29T23:10:34Z
2,541,874
24
2010-03-29T23:11:48Z
[ "python" ]
Hi I want to copy a 2D list, so that if I modify 1 list, the other is not modified. For 1 D list, I just do this: ``` a = [1,2] b = a[:] ``` And now if I modify b, a is not modified. But this doesn't work for 2D list: ``` a = [[1,2],[3,4]] b = a[:] ``` If I modify b, a gets modified as well. How do I fix this?
``` b = [x[:] for x in a] ```
Copying 2D lists in python
2,541,865
12
2010-03-29T23:10:34Z
2,541,882
26
2010-03-29T23:13:01Z
[ "python" ]
Hi I want to copy a 2D list, so that if I modify 1 list, the other is not modified. For 1 D list, I just do this: ``` a = [1,2] b = a[:] ``` And now if I modify b, a is not modified. But this doesn't work for 2D list: ``` a = [[1,2],[3,4]] b = a[:] ``` If I modify b, a gets modified as well. How do I fix this?
For a more general solution that works regardless of the number of dimensions, use `copy.deepcopy()`: ``` import copy b = copy.deepcopy(a) ```
Python 3: receive user input including newline characters
2,542,171
4
2010-03-30T00:37:11Z
2,542,182
8
2010-03-30T00:39:35Z
[ "python", "input", "python-3.x" ]
I'm trying to read in the following text from the command-line in Python 3 (copied verbatim, newlines and all): ``` lcbeika rraobmlo grmfina ontccep emrlin tseiboo edosrgd mkoeys eissaml knaiefr ``` Using `input`, I can only read in the first word as once it reads the first newline it stops reading. Is there a way I...
You can `import sys` and use the methods on `sys.stdin` for example: ``` text = sys.stdin.read() ``` or: ``` lines = sys.stdin.readlines() ``` or: ``` for line in sys.stdin: # Do something with line. ```
Python-daemon doesn't kill its kids
2,542,610
19
2010-03-30T02:59:56Z
2,610,911
30
2010-04-09T21:04:08Z
[ "python", "daemon", "multiprocessing", "children", "zombie-process" ]
When using [python-daemon](http://pypi.python.org/pypi/python-daemon/), I'm creating subprocesses likeso: ``` import multiprocessing class Worker(multiprocessing.Process): def __init__(self, queue): self.queue = queue # we wait for things from this in Worker.run() ... q = multiprocessing.Queue() with d...
Your options are a bit limited. If doing `self.daemon = True` in the constructor for the `Worker` class does not solve your problem and trying to catch signals in the Parent (ie, `SIGTERM, SIGINT`) doesn't work, you may have to try the opposite solution - instead of having the parent kill the children, you can have the...
How do you determine which file is imported in Python with an "import" statement?
2,542,809
4
2010-03-30T04:02:18Z
2,542,850
9
2010-03-30T04:17:20Z
[ "python", "import" ]
How do you determine which file is imported in Python with an "import" statement? I want to determine that I am loading the correct version of a locally modified .py file. Basically the equivalent of "which" in a POSIX environment.
Start python with the `-v` parameter to enable debugging output. When you then import a module, Python will print out where the module was imported from: ``` $ python -v ... >>> import re # /usr/lib/python2.6/re.pyc matches /usr/lib/python2.6/re.py import re # precompiled from /usr/lib/python2.6/re.pyc ... ``` If you...
What python libraries can tell me approximate location and time zone given an IP address?
2,543,018
37
2010-03-30T05:22:48Z
2,543,112
12
2010-03-30T05:55:24Z
[ "python", "geolocation", "timezone" ]
Looking to implement better geo-location with Python.
It is not a Python lib. But <http://ipinfodb.com/> provides a webservice that can be easily wrapped by Python code with urllib for example. ``` http://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&ip=74.125.45.100 http://api.ipinfodb.com/v3/ip-country/?key=<your_api_key>&ip=74.125.45.100 ``` You need to request a f...
What python libraries can tell me approximate location and time zone given an IP address?
2,543,018
37
2010-03-30T05:22:48Z
2,543,132
38
2010-03-30T05:59:44Z
[ "python", "geolocation", "timezone" ]
Looking to implement better geo-location with Python.
**[Hostip.info](http://www.hostip.info/)** is an open-source project with the goal to build/maintain a database ***mapping IP addresses to cities***. Their *about* page explains the data sources relied on to populate this database. Using HostIP, there are two ways to get location data from an IP address: They also ha...
What python libraries can tell me approximate location and time zone given an IP address?
2,543,018
37
2010-03-30T05:22:48Z
2,543,677
7
2010-03-30T08:12:51Z
[ "python", "geolocation", "timezone" ]
Looking to implement better geo-location with Python.
You may find these modules useful: [MaxMind's GeoIP](http://www.maxmind.com/app/python) and its [pure version](http://code.google.com/p/pygeoip/), as well [pytz](http://pytz.sourceforge.net/).
python: what are efficient techniques to deal with deeply nested data in a flexible manner?
2,544,055
7
2010-03-30T09:23:33Z
2,544,413
11
2010-03-30T10:26:35Z
[ "python", "dictionary", "nested" ]
My question is not about a specific code snippet but more general, so please bear with me: How should I organize the data I'm analyzing, and which tools should I use to manage it? I'm using python and numpy to analyse data. Because the python documentation indicates that dictionaries are very optimized in python, and...
> "I stored it in a deeply nested dictionary" And, as you've seen, it doesn't work out well. What's the alternative? 1. Composite keys and a shallow dictionary. You have an 8-part key: ( individual, imaging session, Region imaged, timestamp of file, properties of file, regions of interest in image, format of data...
Filtering by entity key name in Google App Engine on Python
2,544,565
14
2010-03-30T10:57:29Z
2,544,614
16
2010-03-30T11:08:23Z
[ "python", "google-app-engine", "gae-datastore" ]
On Google App Engine to query the data store with Python, one can use GQL or Entity.all() and then filter it. So for example these are equivalent ``` gql = "SELECT * FROM User WHERE age >= 18" db.GqlQuery(gql) ``` and ``` query = User.all() query.filter("age >=", 18) ``` Now, it's also possible to query things by k...
``` from google.appengine.api.datastore import Key query.filter("__key__ >=", Key.from_path('User', 'abc')) ```
How I can get rid of None values in dictionary?
2,544,710
7
2010-03-30T11:27:00Z
2,544,761
18
2010-03-30T11:35:38Z
[ "python" ]
Something like: ``` for (a,b) in kwargs.iteritems(): if not b : del kwargs[a] ``` This code raise exception because changing of dictionary when iterating. I discover only non pretty solution with another dictionary: ``` res ={} res.update((a,b) for a,b in kwargs.iteritems() if b is not None) ``` Thanks
Another way to write it is ``` res = dict((k,v) for k,v in kwargs.iteritems() if v is not None) ``` In Python3, this becomes ``` res = {k:v for k,v in kwargs.items() if v is not None} ```
How can get Python isidentifer() functionality in Python 2.6?
2,544,972
13
2010-03-30T12:14:29Z
2,545,164
11
2010-03-30T12:37:44Z
[ "python", "python-3.x", "python-2.6", "identifier" ]
Python 3 has a string method called [`str.isidentifier`](http://docs.python.org/py3k/library/stdtypes.html#str.isidentifier) How can I get similar functionality in Python 2.6, short of rewriting my own regex, etc.?
the tokenize module defines a regexp called Name ``` import re, tokenize, keyword re.match(tokenize.Name + '$', somestr) and not keyword.iskeyword(somestr) ```
Converting a string into a list in Python
2,545,397
6
2010-03-30T13:11:45Z
2,545,417
16
2010-03-30T13:14:00Z
[ "python" ]
I have a text document that contains a list of numbers and I want to convert it to a list. Right now I can only get the entire list in the 0th entry of the list, but I want each number to be an element of a list. Does anyone know of an easy way to do this in Python? ``` 1000 2000 3000 4000 ``` to ``` ['1000','2000',...
To convert a Python string into a list use the `str.split` method: ``` >>> '1000 2000 3000 4000'.split() ['1000', '2000', '3000', '4000'] ``` `split` has some options: look them up for advanced uses. You can also read the file into a list with the `readlines()` method of a file object - it returns a list of lines. F...
Python analog of natsort function (sort a list using a "natural order" algorithm)
2,545,532
12
2010-03-30T13:29:12Z
3,033,342
27
2010-06-13T18:11:14Z
[ "python", "sorting", "natsort" ]
I would like to know if there is something similar to [PHP natsort](http://www.php.net/manual/en/function.natsort.php) function in Python? ``` l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg'] l.sort() ``` gives: ``` ['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg'] ``` but I would like to get...
From [my answer](http://stackoverflow.com/questions/34518/natural-sorting-algorithm/341745#341745) to [Natural Sorting algorithm](http://stackoverflow.com/questions/34518/natural-sorting-algorithm): ``` import re def natural_key(string_): """See http://www.codinghorror.com/blog/archives/001018.html""" return [...
Python analog of natsort function (sort a list using a "natural order" algorithm)
2,545,532
12
2010-03-30T13:29:12Z
18,415,343
9
2013-08-24T05:41:05Z
[ "python", "sorting", "natsort" ]
I would like to know if there is something similar to [PHP natsort](http://www.php.net/manual/en/function.natsort.php) function in Python? ``` l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg'] l.sort() ``` gives: ``` ['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg'] ``` but I would like to get...
You can check out the third-party [natsort](https://pypi.python.org/pypi/natsort) library on PyPI: ``` >>> import natsort >>> l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg'] >>> natsort.natsorted(l) ['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg'] ``` Full disclosure, I am the author.
Optimization Techniques in Python
2,545,820
9
2010-03-30T14:07:48Z
2,545,889
11
2010-03-30T14:14:43Z
[ "python" ]
Recently i have developed a billing application for my company with Python/Django. For few months everything was fine but now i am observing that the performance is dropping because of more and more users using that applications. Now the problem is that the application is now very critical for the finance team. Now the...
As I said in comment, you must start by finding what part of your code is slow. Nobody can help you without this information. You can profile your code with the [Python profilers](http://docs.python.org/library/profile.html) then go back to us with the result. If it's a Web app, the first suspect is generally the da...
How to synchronize a python dict with multiprocessing
2,545,961
21
2010-03-30T14:26:33Z
2,556,974
47
2010-03-31T22:39:23Z
[ "python", "multiprocessing", "dictionary" ]
I am using Python 2.6 and the multiprocessing module for multi-threading. Now I would like to have a synchronized dict (where the only atomic operation I really need is the += operator on a value). Should I wrap the dict with a multiprocessing.sharedctypes.synchronized() call? Or is another way the way to go?
## Intro There seems to be a lot of arm-chair suggestions and no working examples. None of the answers listed here even suggest using multiprocessing and this is quite a bit disappointing and disturbing. As python lovers we should support our built-in libraries, and while parallel processing and synchronization is nev...
Does SQLAlchemy have an equivalent of Django's get_or_create?
2,546,207
86
2010-03-30T14:57:31Z
2,587,041
47
2010-04-06T17:47:06Z
[ "python", "django", "sqlalchemy" ]
I want to get an object from the database if it already exists (based on provided parameters) or create it if it does not. Django's [`get_or_create`](https://docs.djangoproject.com/en/1.10/ref/models/querysets/#get-or-create) (or [source](https://github.com/django/django/blob/master/django/db/models/query.py#L462)) do...
That's basically the way to do it, there is no shortcut readily available AFAIK. You could generalize it ofcourse: ``` def get_or_create(session, model, defaults=None, **kwargs): instance = session.query(model).filter_by(**kwargs).first() if instance: return instance, False else: params = ...
Does SQLAlchemy have an equivalent of Django's get_or_create?
2,546,207
86
2010-03-30T14:57:31Z
6,078,058
55
2011-05-20T22:08:41Z
[ "python", "django", "sqlalchemy" ]
I want to get an object from the database if it already exists (based on provided parameters) or create it if it does not. Django's [`get_or_create`](https://docs.djangoproject.com/en/1.10/ref/models/querysets/#get-or-create) (or [source](https://github.com/django/django/blob/master/django/db/models/query.py#L462)) do...
Following the solution of @WoLpH, this is the code that worked for me (simple version): ``` def get_or_create(session, model, **kwargs): instance = session.query(model).filter_by(**kwargs).first() if instance: return instance else: instance = model(**kwargs) session.add(instance) ...
Does SQLAlchemy have an equivalent of Django's get_or_create?
2,546,207
86
2010-03-30T14:57:31Z
21,146,492
24
2014-01-15T19:30:23Z
[ "python", "django", "sqlalchemy" ]
I want to get an object from the database if it already exists (based on provided parameters) or create it if it does not. Django's [`get_or_create`](https://docs.djangoproject.com/en/1.10/ref/models/querysets/#get-or-create) (or [source](https://github.com/django/django/blob/master/django/db/models/query.py#L462)) do...
I've been playing with this problem and have ended up with a fairly robust solution: ``` def get_one_or_create(session, model, create_method='', create_method_kwargs=None, **kwargs): try: return session.query(model).fil...
Python Process won't call atexit
2,546,276
16
2010-03-30T15:07:18Z
2,546,397
15
2010-03-30T15:20:16Z
[ "python", "multiprocessing", "terminate", "atexit" ]
I'm trying to use `atexit` in a `Process`, but unfortunately it doesn't seem to work. Here's some example code: ``` import time import atexit import logging import multiprocessing logging.basicConfig(level=logging.DEBUG) class W(multiprocessing.Process): def run(self): logging.debug("%s Started" % self.n...
As [the docs](http://docs.python.org/library/multiprocessing.html?highlight=terminate#multiprocessing.Process.terminate) say, > On Unix this is done using the SIGTERM > signal; on Windows TerminateProcess() > is used. Note that exit handlers and > finally clauses, etc., will not be > executed. If you're on Unix, you ...
How can I draw a log-normalized imshow plot with a colorbar representing the raw data in matplotlib
2,546,475
11
2010-03-30T15:29:23Z
2,546,622
21
2010-03-30T15:52:12Z
[ "python", "matplotlib", "normalize" ]
I'm using matplotlib to plot log-normalized images but I would like the original raw image data to be represented in the colorbar rather than the [0-1] interval. I get the feeling there's a more matplotlib'y way of doing this by using some sort of normalization object and not transforming the data beforehand... in any ...
Yes, there is! Use `LogNorm`. Here is a code excerpt from a utility that I wrote to display confusion matrices on a log scale. ``` from pylab import figure, cm from matplotlib.colors import LogNorm # C = some matrix f = figure(figsize=(6.2,5.6)) ax = f.add_axes([0.17, 0.02, 0.72, 0.79]) axcolor = f.add_axes([0.90, 0.0...
Create static instances of a class inside said class in Python
2,546,608
5
2010-03-30T15:49:41Z
2,546,626
7
2010-03-30T15:52:50Z
[ "python" ]
Apologies if I've got the terminology wrong here—I can't think what this particular idiom would be called. I've been trying to create a Python 3 class that statically declares instances of itself inside itself—sort of like an enum would work. Here's a simplified version of the code I wrote: ``` class Test: A ...
After you defined the class, just add these two lines: ``` Test.A = Test("A") Test.B = Test("B") ``` A class in Python is an object like any other and you can add new variables at any time. You just can't do it inside the class since it's not defined at that time (it will be added to the symbol table only after the w...
Python - animation with matplotlib.pyplot
2,546,780
15
2010-03-30T16:16:12Z
2,547,625
17
2010-03-30T18:28:02Z
[ "python", "matplotlib" ]
How can one create animated diagrams using popular matplotlib library? I am particularly interested in animated gifs.
The matplotlib docs provide an entire section of examples on [animation](http://matplotlib.sourceforge.net/examples/animation/index.html) (see this [scipy](http://www.scipy.org/Cookbook/Matplotlib/Animations) tutorial also). Most, however, involve using the various GUI widget backends. There is one in there, "movie dem...