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
Is using eval in Python a bad practice?
1,832,940
41
2009-12-02T13:34:07Z
1,834,754
17
2009-12-02T18:08:39Z
[ "python", "eval" ]
I am using the following class to easily store data of my songs. ``` class Song: """The class to store the details of each song""" attsToStore=('Name', 'Artist', 'Album', 'Genre', 'Location') def __init__(self): for att in self.attsToStore: exec 'self.%s=None'%(att.lower()) in locals() ...
Using `eval` is weak, not a clearly *bad* practice. 1. It violates the "Fundamental Principle of Software". Your source is not the sum total of what's executable. In addition to your source, there are the arguments to `eval`, which must be clearly understood. For this reason, it's the tool of last resort. 2. It's usua...
What does Python's builtin __build_class__ do?
1,832,997
13
2009-12-02T13:42:23Z
1,833,013
13
2009-12-02T13:44:54Z
[ "python", "python-3.x" ]
In Python 3.1, there is a new builtin function I don't know in the `builtins` module: ``` __build_class__(...) __build_class__(func, name, *bases, metaclass=None, **kwds) -> class Internal helper function used by the class statement. ``` What does this function do? Why must it be in builtins if it's internal...
**Compiling the [PEP 3115](http://www.python.org/dev/peps/pep-3115/) metaclass** [Guido van Rossum said:](http://mail.python.org/pipermail/python-3000/2007-March/006338.html) > The PEP proposes that the class > statement accepts keyword arguments, > `*args`, and `**kwds` syntax as well as positional bases. This is a ...
Simple way to simulate a slow network in python
1,833,563
6
2009-12-02T15:18:55Z
1,833,954
8
2009-12-02T16:12:49Z
[ "python", "networking", "network-programming" ]
Scenario. I have a client with two network connections to a server. One connection uses a mobile phone, and the other is using a wlan connection. The way that I have solved this is by having the server listen at two ports. But, the mobile connection should be slower than the wlan connection. The data that is sent, is ...
Aside from using an external tool to simulate the kind of network you're interested in, one good approach is to use a substitute implementation of socket. This involves making the socket construction a parameter to your function, instead of importing the socket module and using it directly. For normal operation, you w...
Does a File Object Automatically Close when its Reference Count Hits Zero?
1,834,556
23
2009-12-02T17:35:39Z
1,834,570
19
2009-12-02T17:39:04Z
[ "python" ]
I was under the impression that file objects are immediately closed when their reference counts hit 0, hence the line: ``` foo = open('foo').read() ``` would get you the file's contents and immediately close the file. However, after reading the answer to <http://stackoverflow.com/questions/1832528/is-close-necessary-...
If you want to be sure, I'd write the code like this: ``` from __future__ import with_statement with open('foo') as f: foo = f.read() ``` That way, your file closes as expected, even with exceptions. --- Much later: here is some code with `import dis` to show how the compiler treats these differently. ``` >>>...
Does a File Object Automatically Close when its Reference Count Hits Zero?
1,834,556
23
2009-12-02T17:35:39Z
1,834,757
20
2009-12-02T18:08:59Z
[ "python" ]
I was under the impression that file objects are immediately closed when their reference counts hit 0, hence the line: ``` foo = open('foo').read() ``` would get you the file's contents and immediately close the file. However, after reading the answer to <http://stackoverflow.com/questions/1832528/is-close-necessary-...
The answer is in the link you provided. Garbage collector will close file when it destroys file object, but: * you don't really have control over when it happens. While CPython uses reference counting to deterministically release resources (so you can predict when object will be destroyed) other versions don't h...
Does a File Object Automatically Close when its Reference Count Hits Zero?
1,834,556
23
2009-12-02T17:35:39Z
1,834,791
7
2009-12-02T18:15:38Z
[ "python" ]
I was under the impression that file objects are immediately closed when their reference counts hit 0, hence the line: ``` foo = open('foo').read() ``` would get you the file's contents and immediately close the file. However, after reading the answer to <http://stackoverflow.com/questions/1832528/is-close-necessary-...
**For the cpython implementation of python:** yes, it is guaranteed to be closed when its reference count goes to zero. **For python as an abstract language (e.g., including Jython, IronPython, etc):** no, it is not guaranteed to be closed. In particular, an implementation of Python may choose not to use reference cou...
split a comma separated list with links in with beautifulsoup
1,834,779
2
2009-12-02T18:12:02Z
1,834,884
10
2009-12-02T18:30:36Z
[ "python", "beautifulsoup", "html-parsing" ]
I've got a comma separated list in a table cell in an HTML document, but some of items in the list are linked: ``` <table> <tr> <td>Names</td> <td>Fred, John, Barry, <a href="http://www.example.com/">Roger</a>, James</td> </tr> </table> ``` I've been using beautiful soup to parse the html, and I can get t...
This is one way you could do it: ``` import BeautifulSoup soup = BeautifulSoup.BeautifulSoup('''<table> <tr> <td>Names</td> <td>Fred, John, Barry, <a href="http://www.example.com/">Roger</a>, James</td> </tr> </table>''') result = [] for tag in soup.table.findAll('td')[1]: if isinstance(tag, BeautifulS...
error: can't start new thread
1,834,919
12
2009-12-02T18:36:44Z
1,835,043
15
2009-12-02T18:56:42Z
[ "python", "django", "multithreading", "mod-wsgi", "httplib" ]
I have a site that runs with follow configuration: Django + mod-wsgi + apache In one of user's request, I send another HTTP request to another service, and solve this by httplib library of python. But sometimes this service don't get answer too long, and timeout for httplib doesn't work. So I creating thread, in thi...
The "can't start new thread" error almost certainly due to the fact that you have already have too many threads running within your python process, and due to a resource limit of some kind the request to create a new thread is refused. You should probably look at the number of threads you're creating; the maximum numb...
Python: check if an object is a list or tuple (but not string)
1,835,018
257
2009-12-02T18:53:07Z
1,835,044
208
2009-12-02T18:56:51Z
[ "python", "list", "types", "assert" ]
This is what I normally do in order to ascertain that the input is a `list`/`tuple` - but not a `str`. Because many times I stumbled upon bugs where a function passes a `str` object by mistake, and the target function does `for x in lst` assuming that `lst` is actually a `list` or `tuple`. ``` assert isinstance(lst, (...
I think ``` assert not isinstance(lst, basestring) ``` Is actually what you want, otherwise you'll miss out on a lot of things which act like lists, but aren't subclasses of `list` or `tuple`.
Python: check if an object is a list or tuple (but not string)
1,835,018
257
2009-12-02T18:53:07Z
1,835,259
121
2009-12-02T19:30:13Z
[ "python", "list", "types", "assert" ]
This is what I normally do in order to ascertain that the input is a `list`/`tuple` - but not a `str`. Because many times I stumbled upon bugs where a function passes a `str` object by mistake, and the target function does `for x in lst` assuming that `lst` is actually a `list` or `tuple`. ``` assert isinstance(lst, (...
Remember that in Python we want to use "duck typing". So, anything that acts like a list can be treated as a list. So, don't check for the type of a list, just see if it acts like a list. But strings act like a list too, and often that is not what we want. There are times when it is even a problem! So, check explicitl...
Python: check if an object is a list or tuple (but not string)
1,835,018
257
2009-12-02T18:53:07Z
5,971,720
16
2011-05-11T23:30:04Z
[ "python", "list", "types", "assert" ]
This is what I normally do in order to ascertain that the input is a `list`/`tuple` - but not a `str`. Because many times I stumbled upon bugs where a function passes a `str` object by mistake, and the target function does `for x in lst` assuming that `lst` is actually a `list` or `tuple`. ``` assert isinstance(lst, (...
Python with PHP flavor: ``` def is_array(var): return isinstance(var, (list, tuple)) ```
Python: check if an object is a list or tuple (but not string)
1,835,018
257
2009-12-02T18:53:07Z
21,522,971
32
2014-02-03T08:48:45Z
[ "python", "list", "types", "assert" ]
This is what I normally do in order to ascertain that the input is a `list`/`tuple` - but not a `str`. Because many times I stumbled upon bugs where a function passes a `str` object by mistake, and the target function does `for x in lst` assuming that `lst` is actually a `list` or `tuple`. ``` assert isinstance(lst, (...
``` H = "Hello" if type(H) is list or type(H) is tuple: ## Do Something. else ## Do Something. ```
Using try vs if in python
1,835,756
67
2009-12-02T20:58:37Z
1,835,844
108
2009-12-02T21:10:28Z
[ "python" ]
Is there a rationale to decide which one of `try` or `if` constructs to use, when testing variable to have a value? For example, there is a function that returns either a list or doesn't return a value. I want to check result before processing it. Which of the following would be more preferable and why? ``` result = ...
You often hear that Python encourages EAFP style ("it's easier to ask for forgiveness than permission") over LBYL style ("look before you leap"). To me, it's a matter of efficiency and readability. In your example (say that instead of returning a list or an empty string, the function were to return a list or `None`), ...
Using try vs if in python
1,835,756
67
2009-12-02T20:58:37Z
1,835,853
10
2009-12-02T21:11:16Z
[ "python" ]
Is there a rationale to decide which one of `try` or `if` constructs to use, when testing variable to have a value? For example, there is a function that returns either a list or doesn't return a value. I want to check result before processing it. Which of the following would be more preferable and why? ``` result = ...
Your function should not return mixed types (i.e. list or empty string). It should return a list of values or just an empty list. Then you wouldn't need to test for anything, i.e. your code collapses to: ``` for r in function(): # process items ```
Using try vs if in python
1,835,756
67
2009-12-02T20:58:37Z
1,836,111
8
2009-12-02T21:57:37Z
[ "python" ]
Is there a rationale to decide which one of `try` or `if` constructs to use, when testing variable to have a value? For example, there is a function that returns either a list or doesn't return a value. I want to check result before processing it. Which of the following would be more preferable and why? ``` result = ...
Please ignore my solution if the code I provide is not obvious at first glance and you have to read the explanation after the code sample. Can I assume that the "no value returned" means the return value is None? If yes, or if the "no value" is False boolean-wise, you can do the following, since your code essentially ...
What is the range of values a float can have in Python?
1,835,787
21
2009-12-02T21:02:28Z
1,835,805
11
2009-12-02T21:05:52Z
[ "python", "floating-point" ]
What are its smallest and biggest values in python?
See this [post](http://groups.google.com/group/comp.lang.python/msg/fa7a761411ced62b?pli=1). Relevant parts of the post: ``` In [2]: import kinds In [3]: kinds.default_float_kind.M kinds.default_float_kind.MAX kinds.default_float_kind.MIN kinds.default_float_kind.MAX_10_EXP kinds.default_float_kind.MIN_10...
What is the range of values a float can have in Python?
1,835,787
21
2009-12-02T21:02:28Z
1,839,009
45
2009-12-03T10:22:39Z
[ "python", "floating-point" ]
What are its smallest and biggest values in python?
``` >>> import sys >>> sys.float_info sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.2204460492503131e-16, radix=2, rounds=1) ``` The smallest is `sys.float_info.min` (2.2250738585072014e-308) and the ...
Python long multiplication
1,835,857
4
2009-12-02T21:11:44Z
1,836,200
8
2009-12-02T22:10:14Z
[ "python", "biginteger", "multiplication" ]
I'm in need of an algorithm faster than the current normal Python long multiplication. I tried to find a decent Karatsuba implementation, but I can't. ``` def main(): a=long(raw_input()) if(a<0): a=a*-1 a=((a*(a+1)/2)-1) print(-a) else: a=(a*(a+1))/2 print(a) main()...
15.9 ms on my slow notebook. It is the print that is slowing you down. Converting to binary numbers to decimal is quite slow, which is a required step of printing it out. If you need to output the number you should try the DecInt ChristopheD mentioned already. DecInt will be slower doing the multiply but make the prin...
Python long multiplication
1,835,857
4
2009-12-02T21:11:44Z
1,845,764
21
2009-12-04T09:06:59Z
[ "python", "biginteger", "multiplication" ]
I'm in need of an algorithm faster than the current normal Python long multiplication. I tried to find a decent Karatsuba implementation, but I can't. ``` def main(): a=long(raw_input()) if(a<0): a=a*-1 a=((a*(a+1)/2)-1) print(-a) else: a=(a*(a+1))/2 print(a) main()...
I'm the author of the DecInt (Decimal Integer) library so I'll make a few comments. The DecInt library was specifically designed to work with very large integers that needed to be converted to decimal format. The problem with converting to decimal format is that most arbitrary-precision libraries store values in binar...
Similarity Between Users Based On Votes
1,836,352
6
2009-12-02T22:34:53Z
1,836,432
10
2009-12-02T22:49:31Z
[ "python", "mysql", "database", "information-retrieval", "similarity" ]
lets say i have a set of users, a set of songs, and a set of votes on each song: ``` =========== =========== ======= User Song Vote =========== =========== ======= user1 song1 [score] user1 song2 [score] user1 song3 [score] user2 song1 [score] user2 s...
There are two common metrics that can be used to find similarities between users: 1. **Euclidean Distance**, that is exactly what you are thinking: imagine a n-dimensional graph that has for each axis a song that is reviewed by two involved users (*u1* and \*u2) and the value on its axis is the score. You can easily c...
how to update a Django page without a page reload?
1,836,861
13
2009-12-03T00:20:55Z
1,837,016
7
2009-12-03T01:06:55Z
[ "javascript", "python", "ajax", "django" ]
My Django app displays data from a database. This data changes without user intervention, i.e. behind the scenes. Whenever it changes, I would like the webpage to update the changed sections without a full page reload. Obviously AJAX springs to mind. When the page is loaded initially (or manually, fully re-loaded late...
You have two choices 1. Have the browser poll using setTimeout() 2. Look into Comet -- this is a technique for pushing data from the server to the browser. Here's an article on [Comet in Django](http://www.rkblog.rk.edu.pl/w/p/django-and-comet/)
Compressing UTF-8(or other 8-bit encoding) to 7 or fewer bits
1,837,686
2
2009-12-03T04:43:05Z
1,837,697
18
2009-12-03T04:46:09Z
[ "python", "c", "utf-8", "compression" ]
I wish to take a file encoded in UTF-8 that doesn't use more than 128 different characters, then move it to a 7-bit encoding to save the 1/8 of space. For example, if I have a 16 MB text file that only uses the first 128(ascii) characters, I would like to shave off the extra bit to reduce the file to 14MB. How would I...
Just use gzip compression, and save 60-70% with 0% effort!
Invalid Token when using Octal numbers
1,837,874
28
2009-12-03T05:39:29Z
1,837,896
45
2009-12-03T05:45:23Z
[ "python", "syntax", "python-3.x", "octal" ]
I'm a beginner in python and I'm trying to use a octal number in my script, but when I try it, it returns me that error: ``` >>> a = 010 SyntaxError: invalid token (<pyshell#0>, line 1) >>> 01 SyntaxError: invalid token (<pyshell#1>, line 1) ``` There's something wrong with my code? I'm using Python3 (and reading a p...
Try `0o10`, may be because of python 3, or pyshell itself. PEP says, > octal literals must now be specified > with a leading "0o" or "0O" instead of > "0"; <http://www.python.org/dev/peps/pep-3127/>
What is internal representation of string in Python 3.x
1,838,170
13
2009-12-03T06:57:36Z
9,079,985
15
2012-01-31T13:03:36Z
[ "python", "string", "unicode", "python-3.x" ]
In Python 3.x, a string consists of items of Unicode ordinal. (See the quotation from the language reference below.) What is the internal representation of Unicode string? Is it UTF-16? > The items of a string object are > Unicode code units. A Unicode code > unit is represented by a string object > of one item and ca...
The internal representation will change in Python 3.3 which implements [PEP 393](http://www.python.org/dev/peps/pep-0393/). The new representation will pick one or several of ascii, latin-1, utf-8, utf-16, utf-32, generally trying to get a compact representation. Implicit conversions into surrogate pairs will only be ...
Python Spliting a string
1,838,674
5
2009-12-03T09:16:03Z
1,838,686
13
2009-12-03T09:18:29Z
[ "python", "string" ]
I looking to split a string up with python, I have read the documentation but don't fully understand how to do it, I understand that I need to have some kind of identifier in the string so that the functions can find where the string(unless I can target the first space in the sentence?) So for example how would I spli...
Use [`partition(' ')`](http://docs.python.org/library/stdtypes.html#str.partition) which always returns three items in the tuple - the first bit up until the separator, the separator, and then the bits after. Slots in the tuple that have are not applicable are still there, just set to be empty strings. Examples: `"Sic...
Python Spliting a string
1,838,674
5
2009-12-03T09:16:03Z
1,838,693
18
2009-12-03T09:19:14Z
[ "python", "string" ]
I looking to split a string up with python, I have read the documentation but don't fully understand how to do it, I understand that I need to have some kind of identifier in the string so that the functions can find where the string(unless I can target the first space in the sentence?) So for example how would I spli...
Use the [`split`](http://docs.python.org/3.1/library/stdtypes.html#str.split) method on strings: ``` >>> "Sico87 is an awful python developer".split(' ', 1) ['Sico87', 'is an awful python developer'] ``` **How it works:** 1. Every string is an object. String objects have certain methods defined on them, such as `spl...
Why should functions always return the same type?
1,839,289
14
2009-12-03T11:15:27Z
1,839,350
14
2009-12-03T11:29:08Z
[ "python", "function", "return-type" ]
I read somewhere that functions should always return only one type so the following code is considered as bad code: ``` def x(foo): if 'bar' in foo: return (foo, 'bar') return None ``` I guess the better solution would be ``` def x(foo): if 'bar' in foo: return (foo, 'bar') return () ``` Wouldn't it be chea...
Why should functions return values of a consistent type? To meet the following two rules. Rule 1 -- a function has a "type" -- inputs mapped to outputs. It must return a consistent type of result, or it isn't a function. It's a mess. Mathematically, we say some function, F, is a mapping from domain, D, to range, R. `...
Why should functions always return the same type?
1,839,289
14
2009-12-03T11:15:27Z
1,840,291
8
2009-12-03T14:42:41Z
[ "python", "function", "return-type" ]
I read somewhere that functions should always return only one type so the following code is considered as bad code: ``` def x(foo): if 'bar' in foo: return (foo, 'bar') return None ``` I guess the better solution would be ``` def x(foo): if 'bar' in foo: return (foo, 'bar') return () ``` Wouldn't it be chea...
It's not so clear that a function must always return objects of a limited type, or that returning None is wrong. For instance, re.search can return a `_sre.SRE_Match` object or a `NoneType` object: ``` import re match=re.search('a','a') type(match) # <type '_sre.SRE_Match'> match=re.search('a','b') type(match) # <t...
Why should functions always return the same type?
1,839,289
14
2009-12-03T11:15:27Z
1,840,696
7
2009-12-03T15:35:46Z
[ "python", "function", "return-type" ]
I read somewhere that functions should always return only one type so the following code is considered as bad code: ``` def x(foo): if 'bar' in foo: return (foo, 'bar') return None ``` I guess the better solution would be ``` def x(foo): if 'bar' in foo: return (foo, 'bar') return () ``` Wouldn't it be chea...
Best practice in what a function should return varies greatly from language to language, and even between different Python projects. For Python in general, I agree with the premise that returning None is bad if your function generally returns an iterable, because iterating without testing becomes impossible. Just retu...
Is there any reason to choose __new__ over __init__ when defining a metaclass?
1,840,421
28
2009-12-03T15:00:54Z
1,840,466
30
2009-12-03T15:08:54Z
[ "python", "constructor", "new-operator", "metaclass", "init" ]
I've always set up metaclasses something like this: ``` class SomeMetaClass(type): def __new__(cls, name, bases, dict): #do stuff here ``` But I just came across a metaclass that was defined like this: ``` class SomeMetaClass(type): def __init__(self, name, bases, dict): #do stuff here ``` I...
If you want to alter the attributes dict before the class is created, or change the bases tuple, you have to use `__new__`. By the time `__init__` sees the arguments, the class object already exists. Also, you have to use `__new__` if you want to return something other than a newly created class of the type in question...
How do I call a property setter from __init__
1,840,628
10
2009-12-03T15:27:04Z
1,840,712
14
2009-12-03T15:37:25Z
[ "python", "setter", "init", "new-style-class" ]
I have the following chunk of python code: ``` import hashlib class User: def _set_password(self, value): self._password = hashlib.sha1(value).hexdigest() def _get_password(self): return self._password password = property( fset = _set_password, fget = _get_password) ...
A property is a descriptor, and descriptors only work on new-style classes. Try: ``` class User(object): ... ``` instead of: ``` class User: ... ``` A good guide to descriptors can be found [here](http://users.rcn.com/python/download/Descriptor.htm).
Can urllib2 make HTTP/1.1 requests?
1,840,965
2
2009-12-03T16:11:14Z
1,841,055
11
2009-12-03T16:22:56Z
[ "python", "http", "urllib2" ]
EDIT: This question is invalid. Turns out a transparent proxy was making an onward HTTP 1.0 request even though urllib/httplib was indeed making a HTTP 1.1 request originally. ORIGINAL QUESTION: By default `urllib2.urlopen` always makes a HTTP 1.0 request. Is there any way to get it to talk HTTP 1.1 ?
Why do you think it's not already using http 1.1? Have you tried something like...: ``` >>> import urllib2 >>> urllib2._opener.handlers[1].set_http_debuglevel(100) >>> urllib2.urlopen('http://mit.edu').read()[:10] connect: (mit.edu, 80) send: 'GET / HTTP/1.1 ``` (etc, etc)? This should show it's sending a 1.1 GET req...
Generating functions inside loop with lambda expression in python
1,841,268
23
2009-12-03T16:52:14Z
1,841,330
17
2009-12-03T17:00:54Z
[ "python", "scope" ]
If I make two lists of functions: ``` def makeFun(i): return lambda: i a = [makeFun(i) for i in range(10)] b = [lambda: i for i in range(10)] ``` why are the lists `a` and `b` not equal? For example: ``` >>> a[2]() 2 >>> b[2]() 9 ```
Technically, the lambda expression is *closed* over the `i` that's visible in the global scope, which is last set to 9. It's the *same* `i` being referred to in all 10 lambdas. For example, ``` i = 13 print b[3]() ``` In the `makeFun` function, the lambda closes on the `i` that's defined when the function is invoked....
Generating functions inside loop with lambda expression in python
1,841,268
23
2009-12-03T16:52:14Z
1,841,367
7
2009-12-03T17:04:54Z
[ "python", "scope" ]
If I make two lists of functions: ``` def makeFun(i): return lambda: i a = [makeFun(i) for i in range(10)] b = [lambda: i for i in range(10)] ``` why are the lists `a` and `b` not equal? For example: ``` >>> a[2]() 2 >>> b[2]() 9 ```
One set of functions (a) operates on the argument passed and the other (b) operates on a global variable which is then set to 9. Check the disassembly: ``` >>> import dis >>> dis.dis(a[2]) 1 0 LOAD_DEREF 0 (i) 3 RETURN_VALUE >>> dis.dis(b[2]) 1 0 LOAD_GLOBAL ...
Generating functions inside loop with lambda expression in python
1,841,268
23
2009-12-03T16:52:14Z
1,841,368
18
2009-12-03T17:05:09Z
[ "python", "scope" ]
If I make two lists of functions: ``` def makeFun(i): return lambda: i a = [makeFun(i) for i in range(10)] b = [lambda: i for i in range(10)] ``` why are the lists `a` and `b` not equal? For example: ``` >>> a[2]() 2 >>> b[2]() 9 ```
As others have stated, scoping is the problem. Note that you can solve this by adding an extra argument to the lambda expression and assigning it a default value: ``` >> def makeFun(i): return lambda: i ... >>> a = [makeFun(i) for i in range(10)] >>> b = [lambda: i for i in range(10)] >>> c = [lambda i=i: i for i in ...
ValueError: invalid literal for int() with base 10: ''
1,841,565
61
2009-12-03T17:34:19Z
1,841,607
28
2009-12-03T17:40:45Z
[ "python" ]
I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then the next line is read. If that line is not empty it continues. However, I am getting this error: ``` ValueError: invalid literal for int() with base...
Pythonic way of iterating over a file and converting to int: ``` for line in open(fname): if line.strip(): # line contains eol character(s) n = int(line) # assuming single integer on each line ``` What you're trying to do is slightly more complicated, but still not straight-forward: ``` ...
ValueError: invalid literal for int() with base 10: ''
1,841,565
61
2009-12-03T17:34:19Z
8,948,303
78
2012-01-20T21:49:34Z
[ "python" ]
I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then the next line is read. If that line is not empty it continues. However, I am getting this error: ``` ValueError: invalid literal for int() with base...
Just for the record: ``` >>> int('55063.000000') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '55063.000000' ``` Got me here... ``` >>> float('55063.000000') 55063.0 ``` Has to be used!
Python, unit test - Pass command line arguments to setUp of unittest.TestCase
1,842,168
23
2009-12-03T19:05:40Z
2,081,750
41
2010-01-17T16:52:41Z
[ "python", "unit-testing" ]
I have a script that acts as a wrapper for some unit tests written using the Python `unittest` module. In addition to cleaning up some files, creating an output stream and generating some code, it loads test cases into a suite using ``` unittest.TestLoader().loadTestsFromTestCase() ``` I am already using `optparse` t...
Well, I want to do the same thing and was going to ask this question myself. I wanted to improve over the following code because it has duplication. It does let me send in arguments to test TestCase however: ``` import unittest import helpspot class TestHelpSpot(unittest.TestCase): "A few simple tests for HelpSpo...
From a coder's perspective, what kind of project should I choose python over php for where both could do the job?
1,842,208
3
2009-12-03T19:13:03Z
1,842,236
16
2009-12-03T19:16:41Z
[ "php", "python", "linux", "theory" ]
I've never used python before. I've used php for about 5 years now. I plan to learn python, but I'm not sure what for yet. If I can think of a project that might be better to do in python, I'll use that to learn it. Edit: just to add this as an important note, I do mean strictly for linux, not multi-platform. Edit 2: ...
Python is better suited for practically anything that doesn't fall within PHP's specialty domain, which is building websites. If you want a list of programming projects that you could work on, see this thread: <http://stackoverflow.com/questions/1022738/i-need-a-good-programming-project>
Reverse for '*' with arguments '()' and keyword arguments '{}' not found
1,842,389
44
2009-12-03T19:42:13Z
1,842,548
45
2009-12-03T20:08:03Z
[ "python", "django", "django-templates" ]
Caught an exception while rendering: > Reverse for 'products.views.'filter\_by\_led' with arguments '()' and > keyword arguments '{}' not found. I was able to successfully import `products.views.filter_by_led` from the shell and it worked so the path should be correct. Here is the urls.py: ``` (r'^led-tv/$', filter...
There are 3 things I can think of off the top of my head: 1. Just used [named urls](http://docs.djangoproject.com/en/dev/topics/http/urls/#naming-url-patterns), it's more robust and maintainable anyway 2. Try using `django.core.urlresolvers.reverse` at the command line for a (possibly) better error ``` >>> from...
Reverse for '*' with arguments '()' and keyword arguments '{}' not found
1,842,389
44
2009-12-03T19:42:13Z
14,982,471
27
2013-02-20T14:37:41Z
[ "python", "django", "django-templates" ]
Caught an exception while rendering: > Reverse for 'products.views.'filter\_by\_led' with arguments '()' and > keyword arguments '{}' not found. I was able to successfully import `products.views.filter_by_led` from the shell and it worked so the path should be correct. Here is the urls.py: ``` (r'^led-tv/$', filter...
Shell calls to *reverse* (as mentioned above) are very good to debug these problems, but there are two critical conditions: * you **must** supply arguments that matches whatever arguments the view needs, * these **arguments** must match regexp patterns. Yes, it's logical. Yes, it's also confusing because *reverse* wi...
Why is 'dir()' named 'dir' in python?
1,842,414
20
2009-12-03T19:47:05Z
1,842,423
25
2009-12-03T19:48:19Z
[ "python", "built-in", "dir" ]
In Python there is a built-in function called `dir`. This is used to get a list of all the attributes for an object. I understand what it does, but I am confused about why it is called `dir`. How is this name related to getting the attributes from an object?
It gives you a **dir**ectory of all attributes of an object. This is not a directory as used in file systems, but the standard usage: a listing of names or data.
Python's string.maketrans works at home but fails on Google App Engine
1,842,692
5
2009-12-03T20:29:45Z
1,842,999
14
2009-12-03T21:21:29Z
[ "python", "google-app-engine", "internationalization", "translation" ]
I have this code in Google AppEngine (Python SDK): ``` from string import maketrans intab = u"ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ".encode('latin1') outtab = u"aaaaaaaaaaaaooooooooooooeeeeeeeecciiiiiiiiuuuuuuuuynn".encode('latin1') logging.info...
`string.maketrans` and `string.translate` do not work for Unicode strings. Your call to `string.maketrans` will implictly convert the Unicode you gave it to an encoding like `utf-8`. In `utf-8` `Ã¥` takes up more space than ASCII `a`. `string.maketrans` sees `len(str(argument))` which is different for your two strings....
Can I CREATE TEMPORARY TABLE in SQLAlchemy without appending to Table._prefixes?
1,842,902
6
2009-12-03T21:02:11Z
1,845,540
7
2009-12-04T08:08:17Z
[ "python", "sqlalchemy", "temp-tables" ]
I'd like to create a temporary table in SQLAlchemy. I can build a `CREATE TABLE` statement with a `TEMPORARY` clause by calling `table._prefixes.append('TEMPORARY')` against a `Table` object, but that's less elegant than `table.select().prefix_with()` used to add a prefix to data manipulation language expressions. Is ...
No, `prefix_with()` is defined for SELECT and INSERT only. But convenient way to add prefix to CREATE TABLE statement is passing it into table definition: ``` t = Table( 't', metadata, Column('id', Integer, primary_key=True), # ... prefixes=['TEMPORARY'], ) ```
Translating python dictionary to C++
1,842,941
17
2009-12-03T21:10:19Z
1,842,953
8
2009-12-03T21:12:20Z
[ "c++", "python", "dictionary", "tuples" ]
I have python code that contains the following code. ``` d = {} d[(0,0)] = 0 d[(1,2)] = 1 d[(2,1)] = 2 d[(2,3)] = 3 d[(3,2)] = 4 for (i,j) in d: print d[(i,j)], d[(j,i)] ``` Unfortunately looping over all the keys in python isn't really fast enough for my purpose, and I would like to translate this code to C++....
The type is ``` std::map< std::pair<int,int>, int> ``` The code to add entries to map is like here: ``` typedef std::map< std::pair<int,int>, int> container; container m; m[ make_pair(1,2) ] = 3; //... for(container::iterator i = m.begin(); i != m.end(); ++i){ std::cout << i.second << ' '; // not really ...
Translating python dictionary to C++
1,842,941
17
2009-12-03T21:10:19Z
1,842,976
33
2009-12-03T21:17:00Z
[ "c++", "python", "dictionary", "tuples" ]
I have python code that contains the following code. ``` d = {} d[(0,0)] = 0 d[(1,2)] = 1 d[(2,1)] = 2 d[(2,3)] = 3 d[(3,2)] = 4 for (i,j) in d: print d[(i,j)], d[(j,i)] ``` Unfortunately looping over all the keys in python isn't really fast enough for my purpose, and I would like to translate this code to C++....
A dictionary would be a std::map in c++, and a tuple with two elements would be a std::pair. The python code provided would translate to: ``` #include <iostream> #include <map> typedef std::map<std::pair<int, int>, int> Dict; typedef Dict::const_iterator It; int main() { Dict d; d[std::make_pair(0, 0)] = 0; ...
how to transition from C# to python?
1,843,219
7
2009-12-03T21:57:03Z
1,843,371
7
2009-12-03T22:18:35Z
[ "c#", "python", "visual-studio", "transition" ]
i feel like i'm going back to the stone age. how do i relearn to develop without intellisense (pydev intellisense doesn't count).. in general, how does one successfully leave the comfort of visual studio ?
I recently learned python with a strong C# background. My advise: Just do it. Sorry, couldn't resist but I'm also serious. Install python and read: [Python.org documentation](http://docs.python.org/) (v2.6). A book might help too -- I like [the Python PhraseBook](http://rads.stackoverflow.com/amzn/click/0672329107). F...
Get webpage contents with Python?
1,843,422
18
2009-12-03T22:25:35Z
1,843,511
16
2009-12-03T22:38:21Z
[ "python", "python-3.x" ]
I'm using Python 3.1, if that helps. Anyways, I'm trying to get the contents of [this](http://hiscore.runescape.com/index_lite.ws?player=zezima) webpage. I Googled for a little bit and tried different things, but they didn't work. I'm guessing that this should be an easy task, but...I can't get it. :/. Results of url...
Because you're using Python 3.1, you need to use the new [Python 3.1 APIs](http://www.diveinto.org/python3/porting-code-to-python-3-with-2to3.html#urllib). Try: ``` urllib.request.urlopen('http://www.python.org/') ``` Alternately, it looks like you're working from Python 2 examples. Write it in Python 2, then use th...
Get webpage contents with Python?
1,843,422
18
2009-12-03T22:25:35Z
23,565,355
9
2014-05-09T13:02:49Z
[ "python", "python-3.x" ]
I'm using Python 3.1, if that helps. Anyways, I'm trying to get the contents of [this](http://hiscore.runescape.com/index_lite.ws?player=zezima) webpage. I Googled for a little bit and tried different things, but they didn't work. I'm guessing that this should be an easy task, but...I can't get it. :/. Results of url...
The best way to do this these day is to use the 'requests' library: ``` import requests response = requests.get('http://hiscore.runescape.com/index_lite.ws?player=zezima') print (response.status_code) print (response.content) ```
How to get back to the for loop after exception handling
1,843,659
8
2009-12-03T22:59:53Z
1,843,671
18
2009-12-03T23:01:39Z
[ "python", "exception-handling" ]
I am ready to run this code but before I want to fix the exception handling: ``` for l in bios: OpenThisLink = url + l try: response = urllib2.urlopen(OpenThisLink) except urllib2.HTTPError: pass bio = response.read() item = re.search('(JD)(.*?)(\d+)', bio) .... ``` As suggeste...
Use `continue` instead of `break`. The statement `pass` is a no-op (meaning that it doesn't do anything). The program just continues to the next statement, which is why you get an error. `break` exits the loops and continues running from the next statement immediately after the loop. In this case, there are no more s...
Patterns for dealing with memcache Caching in Django
1,844,432
4
2009-12-04T02:00:44Z
1,845,729
7
2009-12-04T08:59:17Z
[ "python", "django", "memcached" ]
I have a big Django project with several interrelated projects and a lot of caching in use. It currently has a file which stores cache helper functions. So for example, get\_object\_x(id) would check cache for this object and if it wasn't there, go to the DB and pull it from there and return it, caching it along the wa...
A general Python pattern for avoiding circular imports is to put one set of the imports inside the dependent functions: ``` # module_a.py import module_b def foo(): return "bar" def bar(): return module_b.baz() # module_b.py def baz(): import module_a return module_a.foo() ``` As for caching, it so...
Programmatically pass unknown number of parameters in Python
1,844,705
2
2009-12-04T03:44:44Z
1,844,713
7
2009-12-04T03:46:52Z
[ "python" ]
I'd like an easy way to plug in a function and arguments to be executed later so I can have a kind of wrapper around it. In this case, I'd like to use it to benchmark, example: ``` def timefunc(fn, *args): start = time.clock() fn(args) stop = time.clock() return stop - start ``` How do I pass arguments w...
Just call the function like this: ``` fn(*args) ```
Get all table names in a Django app
1,845,293
23
2009-12-04T06:54:57Z
1,847,330
41
2009-12-04T14:36:27Z
[ "python", "django", "table", "model", "many-to-many" ]
How to get all table names in a Django app? I use the following code but it doesn't get the tables created by ManyToManyField ``` from django.db.models import get_app, get_models app = get_app(app_name) for model in get_models(app): print model._meta.db_table ```
``` from django.db import connection tables = connection.introspection.table_names() seen_models = connection.introspection.installed_models(tables) ``` As seen in the syncdb command for manage.py.
Get all table names in a Django app
1,845,293
23
2009-12-04T06:54:57Z
7,513,713
9
2011-09-22T11:02:35Z
[ "python", "django", "table", "model", "many-to-many" ]
How to get all table names in a Django app? I use the following code but it doesn't get the tables created by ManyToManyField ``` from django.db.models import get_app, get_models app = get_app(app_name) for model in get_models(app): print model._meta.db_table ```
The simplest answer, that still allows you to pick which app you want, is to modify your code with one extra argument "include\_auto\_created". ``` from django.db.models import get_app, get_models app = get_app(app_name) for model in get_models(app, include_auto_created=True): print model._meta.db_table ``` Obvio...
General Unicode/UTF-8 support for csv files in Python 2.6
1,846,135
41
2009-12-04T10:33:29Z
1,846,171
7
2009-12-04T10:41:47Z
[ "python", "csv", "unicode", "utf-8", "python-2.x" ]
The csv module in Python doesn't work properly when there's UTF-8/Unicode involved. I have found, in the [Python documentation](http://docs.python.org/library/csv.html) and on other webpages, snippets that work for specific cases but you have to understand well what encoding you are handling and use the appropriate sni...
There is the usage of Unicode example already in that [doc](http://docs.python.org/library/csv.html#examples), why still need to find another one or re-invent the wheel? ``` import csv def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): # csv.py doesn't do Unicode; encode temporarily as UTF-8: ...
General Unicode/UTF-8 support for csv files in Python 2.6
1,846,135
41
2009-12-04T10:33:29Z
6,187,936
51
2011-05-31T12:59:51Z
[ "python", "csv", "unicode", "utf-8", "python-2.x" ]
The csv module in Python doesn't work properly when there's UTF-8/Unicode involved. I have found, in the [Python documentation](http://docs.python.org/library/csv.html) and on other webpages, snippets that work for specific cases but you have to understand well what encoding you are handling and use the appropriate sni...
The example code of how to read Unicode given at <http://docs.python.org/library/csv.html#examples> looks to be obsolete, as it doesn't work with Python 2.6 and 2.7. Here follows `UnicodeDictReader` which works with utf-8 and may be with other encodings, but I only tested it on utf-8 inputs. The idea in short is to d...
General Unicode/UTF-8 support for csv files in Python 2.6
1,846,135
41
2009-12-04T10:33:29Z
9,347,871
22
2012-02-19T08:50:55Z
[ "python", "csv", "unicode", "utf-8", "python-2.x" ]
The csv module in Python doesn't work properly when there's UTF-8/Unicode involved. I have found, in the [Python documentation](http://docs.python.org/library/csv.html) and on other webpages, snippets that work for specific cases but you have to understand well what encoding you are handling and use the appropriate sni...
The module provided [here](http://halley.cc/code/?python/ucsv.py), looks like a cool, simple, drop-in replacement for the csv module that allows you to work with utf-8 csv. ``` import ucsv as csv with open('some.csv', 'rb') as f: reader = csv.reader(f) for row in reader: print row ```
General Unicode/UTF-8 support for csv files in Python 2.6
1,846,135
41
2009-12-04T10:33:29Z
10,275,281
31
2012-04-23T05:34:07Z
[ "python", "csv", "unicode", "utf-8", "python-2.x" ]
The csv module in Python doesn't work properly when there's UTF-8/Unicode involved. I have found, in the [Python documentation](http://docs.python.org/library/csv.html) and on other webpages, snippets that work for specific cases but you have to understand well what encoding you are handling and use the appropriate sni...
A little late answer, but I have used [unicodecsv](https://github.com/jdunck/python-unicodecsv) with great success.
Python mechanize loses attributes on second open
1,846,476
2
2009-12-04T11:47:21Z
1,846,725
7
2009-12-04T12:40:25Z
[ "python", "mechanize" ]
This is a really specialized case and I feel awkward asking it; however I'm at wits end working on it. I need to follow a tracking number through a form and to a results page so I've been using mechanize in python, the link after form submission is embedded in javascript so I can't simply follow\_link. What I want to ...
You never make *first* `.read` method call on Browser instance. That's because it doesn't have such method. The `Browswer.response` has `read` method, so if you want to get the body of response you'd need to do: ``` response = br.response() response.read() ``` For the future, you could use `dir(obj)` to see the conte...
the best shortest path algorithm
1,846,836
18
2009-12-04T13:06:24Z
1,846,908
17
2009-12-04T13:22:37Z
[ "python", "algorithm", "numpy", "shortest-path" ]
what is the difference between the **"Floyd-Warshall algorithm"** and **"Dijkstra's Algorithm"**, and which is the best for finding the shortest path in a graph? I need to calculate the shortest path between all the pairs in a net and save the results to an array as follows: ![alt text](http://img697.imageshack.us/im...
[Dijkstra](http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)'s algorithm finds the shortest path between a node and every other node in the graph. You'd run it once for every node. Weights must be non-negative, so if necessary you have to normalise the values in the graph first. [Floyd-Warshall](http://en.wikipedia...
Getting python.exe path at run time
1,846,888
4
2009-12-04T13:18:32Z
1,846,896
11
2009-12-04T13:19:49Z
[ "python" ]
On Windows, how do I find the path to python.exe from within a script at runtime?
``` >>> import sys >>> sys.executable 'C:\\Program Files\\Python31\\pythonw.exe' ```
How can I correct a corrupted $PYTHONPATH?
1,847,249
6
2009-12-04T14:22:49Z
7,761,520
8
2011-10-13T23:17:35Z
[ "python", "version-control", "mercurial", "ubuntu-9.10", "pythonpath" ]
When trying to launch Mercurial(hg) after a restart in my Ubuntu 9.10 Linux Box I got following message: ``` abort: couldn't find mercurial libraries in [/usr/bin /usr/local/lib/python2.6/dist-packages/vipy-0.4-py2.6.egg /usr/local/lib/python2.6/dist-packages/nose-0.11.1-py2.6.egg /usr/local/lib/python2.6/dist-p...
Try this: update-python-modules -p (might need to sudo that...) Source: <http://hg.opensource.lshift.net/mercurial-server/rev/32dba1a70a54>
How can I prevent a Python module from importing itself?
1,848,268
11
2009-12-04T16:54:37Z
1,848,740
12
2009-12-04T18:18:09Z
[ "python", "import", "module" ]
For instance, I want to make a sql alchemy plugin for another project. And I want to name that module sqlalchemy.py. The problem with this is that it prevents me from importing `sqlalchemy`: ``` #sqlalchemy.py import sqlalchemy ``` This will make the module import itself. I've tried this, but it doesn't seem to work:...
**Edit**: as the OP has now mentioned that the issue is one of relative import being preferred to absolute, the simplest solution for the OP's specific problem is to add at the start of the module `from __future__ import absolute_import` which changes that "preference"/ordering. The following still applies to the tick...
lxml Changing Unicode Characters
1,848,371
3
2009-12-04T17:10:28Z
1,848,497
7
2009-12-04T17:34:00Z
[ "python", "xml", "lxml" ]
I am using lxml to read through an xml file and change a few details. However, when running it I find that even if I just use lxml to read the file and then write it out again, as below: ``` fil='iTunes Music Library.XML' tre=etree.parse(fil) tre.write('temp.xml') ``` I find Queensrÿche converted to `Queensr&#255;ch...
Change your last line to: ``` tre.write('temp.xml', encoding='utf-8') ``` Otherwise `lxml` writes XML in ASCII encoding, so it have to escape all non-ASCII characters.
Method Resolution Order (MRO) in new style Python classes
1,848,474
46
2009-12-04T17:30:47Z
1,848,647
100
2009-12-04T18:03:00Z
[ "python" ]
In the book "Python in a Nutshell" (2nd Edition) there is an example which uses old style classes to demonstrate how methods are resolved in classic resolution order and how is it different with the new order. I tried the same example by rewriting the example in new style but the result is no different than what...
The crucial difference between resolution order for legacy vs new-style classes comes when the same ancestor class occurs more than once in the "naive", depth-first approach -- e.g., consider a "diamond inheritance" case: ``` >>> class A: x = 'a' ... >>> class B(A): pass ... >>> class C(A): x = 'c' ... >>> class D(...
Method Resolution Order (MRO) in new style Python classes
1,848,474
46
2009-12-04T17:30:47Z
27,670,178
10
2014-12-27T18:20:22Z
[ "python" ]
In the book "Python in a Nutshell" (2nd Edition) there is an example which uses old style classes to demonstrate how methods are resolved in classic resolution order and how is it different with the new order. I tried the same example by rewriting the example in new style but the result is no different than what...
Python's method resolution order is actually more complex than just understanding the diamond pattern. To *really* understand it, take a look at [C3 linearization](http://en.wikipedia.org/wiki/C3_linearization). I've found it really helps to use print statements when extending methods to track the order. For example, w...
How to do conditional character replacement within a string
1,849,185
2
2009-12-04T19:38:06Z
1,849,313
7
2009-12-04T20:01:07Z
[ "python", "string", "replace", "conditional" ]
I have a unicode string in Python and basically need to go through, character by character and replace certain ones based on a list of rules. One such rule is that `a` is changed to `ö` if `a` is after `n`. Also, if there are two vowel characters in a row, they get replaced by one vowel character and `:`. So if I have...
``` # -*- coding: utf-8 -*- def subpairs(s, prefix, suffix): def sub(i, sentinal=object()): r = prefix.get(s[i:i+2], sentinal) if r is not sentinal: return r r = suffix.get(s[i-1:i+1], sentinal) if r is not sentinal: return r return s[i] s = '\0'+s+'\0' return ''.j...
Do dicts preserve iteration order if they are not modified?
1,849,324
19
2009-12-04T20:03:08Z
1,849,397
12
2009-12-04T20:17:10Z
[ "python", "algorithm", "dictionary", "hash" ]
If I have a dictionary in Python, and I iterate through it once, and then again later, is the iteration order guaranteed to be preserved given that I didn't insert, delete, or update any items in the dictionary? (But I might have done look-ups).
The standard Python `dict` like most implementations does not preserve ordering as the items are usually accessed using the key. However predictable iteration is sometime useful and in Python 3.1 the `collections` module contains an [OrderedDict](http://docs.python.org/dev/py3k/library/collections.html#collections.Ord...
Do dicts preserve iteration order if they are not modified?
1,849,324
19
2009-12-04T20:03:08Z
1,849,418
31
2009-12-04T20:21:35Z
[ "python", "algorithm", "dictionary", "hash" ]
If I have a dictionary in Python, and I iterate through it once, and then again later, is the iteration order guaranteed to be preserved given that I didn't insert, delete, or update any items in the dictionary? (But I might have done look-ups).
Here is what `dict.items()` [documentation](http://www.python.org/doc/2.6.4/library/stdtypes.html#dict.items) says: > dict.items() return a copy of the dictionary’s list of (key, value) pairs. > > If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to ...
How do I INSERT INTO t1 (SELECT * FROM t2) in SQLAlchemy?
1,849,375
16
2009-12-04T20:12:58Z
1,849,474
32
2009-12-04T20:30:27Z
[ "python", "sqlalchemy" ]
In SQLAlchemy, how do I populate or update a table from a `SELECT` statement?
SQLalchemy doesn't build this construct for you. You can use the query from text. ``` session.execute('INSERT INTO t1 (SELECT * FROM t2)') ``` --- # EDIT: More than one year later, but now on sqlalchemy 0.6+ [you can create it](http://www.sqlalchemy.org/docs/core/compiler.html#compiling-sub-elements-of-a-custom-exp...
How do I INSERT INTO t1 (SELECT * FROM t2) in SQLAlchemy?
1,849,375
16
2009-12-04T20:12:58Z
17,995,969
10
2013-08-01T13:51:15Z
[ "python", "sqlalchemy" ]
In SQLAlchemy, how do I populate or update a table from a `SELECT` statement?
As of 0.8.3, you can now do this directly in sqlalchemy: [Insert.from\_select](http://docs.sqlalchemy.org/en/rel_0_8/core/expression_api.html#sqlalchemy.sql.expression.Insert.from_select): ``` sel = select([table1.c.a, table1.c.b]).where(table1.c.c > 5) ins = table2.insert().from_select(['a', 'b'], sel) ```
What are the advantages and disadvantages of the require vs. import methods of loading code?
1,849,376
9
2009-12-04T20:12:59Z
1,849,446
14
2009-12-04T20:26:30Z
[ "python", "ruby", "programming-languages", "language-features", "language-design" ]
Ruby uses `require`, Python uses `import`. They're substantially different models, and while I'm more used to the `require` model, I can see a few places where I think I like `import` more. I'm curious what things people find particularly easy — or more interestingly, harder than they should be — with each of these...
The Python `import` has a major feature in that it ties two things together -- *how to find the import* and under *what namespace to include it*. This creates very explicit code: `import xml.sax` This specifies where to find the code we want to use, by the rules of the Python search path. At the same time, all obje...
How can you detect if two regular expressions overlap in the strings they can match?
1,849,447
19
2009-12-04T20:26:42Z
1,849,487
27
2009-12-04T20:34:03Z
[ "c++", "python", "regex", "algorithm", "overlap" ]
I have a container of regular expressions. I'd like to analyze them to determine if it's possible to generate a string that matches more than 1 of them. Short of writing my own regex engine with this use case in mind, is there an easy way in C++ or Python to solve this problem?
There's no easy way. As long as your regular expressions use only standard features (Perl lets you embed arbitrary code in matching, I think), you can produce from each one a [nondeterministic finite-state automaton (NFA)](http://en.wikipedia.org/wiki/Nondeterministic%5Ffinite%5Fstate%5Fmachine) that compactly encodes...
Is pickle file of python cross-platform?
1,849,523
10
2009-12-04T20:39:58Z
1,849,632
9
2009-12-04T21:02:51Z
[ "python", "file-io", "pickle" ]
I have created a small python script of mine. I saved the pickle file on Linux and then used it on windows and then again used it back on Linux but now that file is not working on Linux but it is working perfectly on windows. Is is so that python is coss-platform but the pickle file is not. Is there any solution to thi...
The `pickle` module [supports several different data formats](http://docs.python.org/library/pickle.html#data-stream-format). If you are specifying a particular pickle format instead of using the default (0), you may be running into cross-platform binary file problems. You can use plain ASCII pickle files by specifying...
Is pickle file of python cross-platform?
1,849,523
10
2009-12-04T20:39:58Z
1,850,806
18
2009-12-05T01:45:36Z
[ "python", "file-io", "pickle" ]
I have created a small python script of mine. I saved the pickle file on Linux and then used it on windows and then again used it back on Linux but now that file is not working on Linux but it is working perfectly on windows. Is is so that python is coss-platform but the pickle file is not. Is there any solution to thi...
Python's pickle is perfectly cross-platform. This is likely due to EOL (End-Of-Line) differences between Windows and Linux. Make sure to open your pickle files in binary mode both when writing them and when reading them, using open()'s "wb" and "rb" modes respectively. Note: Passing pickles between different versions...
Can SQLAlchemy's session.merge() update its result with newer data from the database?
1,849,567
6
2009-12-04T20:47:19Z
1,851,498
21
2009-12-05T07:40:18Z
[ "python", "sqlalchemy" ]
The SQLAlchemy documentation says "[session.merge()](http://docs.sqlalchemy.org/en/latest/orm/session.html?highlight=merge#unitofwork-merging) reconciles the current state of an instance and its associated children with existing data in the database". Does the existing object's state ever get updated by newer data fro...
SQLAlchemy is designed to have single object with each identity in session. But sometimes you have to recreate an object with known identity, e.g. when you get it from network or when you implement offline lock to avoid long transactions. And when you create an object with known identity that might exist in database, t...
Creating a generator expression from a list in python
1,850,223
3
2009-12-04T23:00:35Z
1,850,252
9
2009-12-04T23:06:48Z
[ "python", "list", "generator", "functional-programming" ]
What is the best way to do the following in Python: ``` for item in [ x.attr for x in some_list ]: do_something_with(item) ``` This may be a nub question, but isn't the list comprehension generating a new list that we don't need and just taking up memory? Wouldn't it be better if we could make an iterator-like li...
Yes (to both of your questions). By using parentheses instead of brackets you can make what's called a "generator expression" for that sequence, which does exactly what you've proposed. It lets you iterate over the sequence without allocating a list to hold all the elements simultaneously. ``` for item in (x.attr for...
Adding an argument to a decorator
1,850,463
5
2009-12-05T00:03:29Z
1,850,485
7
2009-12-05T00:10:41Z
[ "python", "django", "decorator" ]
I have this decorator, used to decorate a django view when I do not want the view to be executed if the `share` argument is `True` (handled by middleware) ``` class no_share(object): def __init__(self, view): self.view = view def __call__(self, request, *args, **kwargs): """Don't let them in i...
I hope [this](http://www.artima.com/weblogs/viewpost.jsp?thread=240845) article by Bruce Eckel helps. **Upd:** According to the article your code will look like this: ``` class no_share(object): def __init__(self, arg1): self.arg1 = arg1 def __call__(self, f): """Don't let them in if it's sha...
Python fraction of seconds
1,850,607
7
2009-12-05T00:40:48Z
1,851,645
11
2009-12-05T09:02:43Z
[ "python", "datetime" ]
What is the best way to handle portions of a second in Python? The datetime library is excellent, but as far as I can tell it cannot handle any unit less than a second.
In the datetime module, the datetime, time, and timedelta classes all have the smallest resolution of microseconds: ``` >>> from datetime import datetime, timedelta >>> now = datetime.now() >>> now datetime.datetime(2009, 12, 4, 23, 3, 27, 343000) >>> now.microsecond 343000 ``` if you want to display a datetime with ...
Django Delete all but last five of queryset
1,851,197
18
2009-12-05T05:17:29Z
1,852,789
11
2009-12-05T17:20:49Z
[ "python", "django" ]
I have a super simple django model here: ``` class Notification(models.Model): message = models.TextField() user = models.ForeignKey(User) timestamp = models.DateTimeField(default=datetime.datetime.now) ``` Using ajax, I check for new messages every minute. I only show the five most recent notifications t...
Use an inner query to get the set of items you want to keep and then filter on them. ``` objects_to_keep = Notification.objects.filter(user=user).order_by('-created_at')[:5] Notification.objects.exclude(pk__in=objects_to_keep).delete() ``` Double check this before you use it. I have found that simpler inner queries d...
Django Delete all but last five of queryset
1,851,197
18
2009-12-05T05:17:29Z
1,853,168
8
2009-12-05T19:25:23Z
[ "python", "django" ]
I have a super simple django model here: ``` class Notification(models.Model): message = models.TextField() user = models.ForeignKey(User) timestamp = models.DateTimeField(default=datetime.datetime.now) ``` Using ajax, I check for new messages every minute. I only show the five most recent notifications t...
this is how i ended up doing this. ``` notes = Notification.objects.filter(user=self.user) for note in notes[4:]: note.delete() ``` because i'm doing this in the save method, the only way the loop would ever have to run more than once would be if the user got multiple notifications at once. i'm not wo...
Django Delete all but last five of queryset
1,851,197
18
2009-12-05T05:17:29Z
20,996,456
13
2014-01-08T13:03:30Z
[ "python", "django" ]
I have a super simple django model here: ``` class Notification(models.Model): message = models.TextField() user = models.ForeignKey(User) timestamp = models.DateTimeField(default=datetime.datetime.now) ``` Using ajax, I check for new messages every minute. I only show the five most recent notifications t...
This is a bit old, but I believe you can do the following: ``` notes = Notification.objects.filter(user=self.user)[:4] Notification.objects.exclude(pk__in=list(notes)).delete() # list() forces a database hit. ``` It costs two hits, but avoids using the for loop with transactions middleware. The reason is that Djang...
resampling, interpolating matrix
1,851,384
9
2009-12-05T06:46:55Z
7,493,607
7
2011-09-21T01:28:08Z
[ "python", "matrix", "interpolation", "signal-processing", "generator" ]
I'm trying to interpolate some data for the purpose of plotting. For instance, given N data points, I'd like to be able to generate a "smooth" plot, made up of 10\*N or so interpolated data points. My approach is to generate an N-by-10\*N matrix and compute the inner product the original vector and the matrix I genera...
This is upsampling. See [Help with resampling/upsampling](http://stackoverflow.com/questions/5156690/help-with-resampling-upsampling) for some example solutions. A fast way to do this (for offline data, like your plotting application) is to use FFTs. This is what SciPy's native [`resample()` function](http://docs.scip...
Python values with units
1,852,720
3
2009-12-05T16:54:13Z
1,852,777
8
2009-12-05T17:14:01Z
[ "python" ]
I need to keep track of units on float and int values in Python, but I don't want to use an external package like magnitude or others, because I don't need to perform operations on the values. Instead, all I want is to be able to define floats and ints that have a unit attribute (and I don't want to add a new dependenc...
You might be looking for something like this: ``` class UnitFloat(float): def __new__(self, value, unit=None): return float.__new__(self, value) def __init__(self, value, unit=None): self.unit = unit x = UnitFloat(35.5, "cm") y = UnitFloat(42.5) print x print x.unit print y print y.unit p...
Writing a Faster Python Spider
1,853,673
6
2009-12-05T22:28:40Z
1,853,687
9
2009-12-05T22:34:33Z
[ "python", "web-crawler" ]
I'm writing a spider in Python to crawl a site. Trouble is, I need to examine about 2.5 million pages, so I could really use some help making it optimized for speed. What I need to do is examine the pages for a certain number, and if it is found to record the link to the page. The spider is very simple, it just needs ...
You could use [MapReduce](http://en.wikipedia.org/wiki/MapReduce) like Google does, either via [Hadoop](http://hadoop.apache.org/) (specifically with Python: [1](http://www.michael-noll.com/wiki/Writing%5FAn%5FHadoop%5FMapReduce%5FProgram%5FIn%5FPython) and [2](http://blog.last.fm/2008/05/29/python-hadoop-flying-circus...
Python web application
1,854,058
5
2009-12-06T00:39:21Z
1,854,079
10
2009-12-06T00:47:56Z
[ "python" ]
I want to create a very simple python web app. I don't need Django or any other web framwwork like that. Isn't there a simpler way to create a web app in python? Thanks
If you don't need Django, try web.py <http://webpy.org/> ``` import web urls = ( '/(.*)', 'hello' ) app = web.application(urls, globals()) class hello: def GET(self, name): if not name: name = 'world' return 'Hello, ' + name + '!' if __name__ == "__main__": app.run(...
Raise unhandled exceptions in a thread in the main thread?
1,854,216
10
2009-12-06T03:05:50Z
1,854,263
9
2009-12-06T03:39:43Z
[ "python", "exception-handling", "multithreading", "systemexit" ]
There are some similar questions, but none supply the answer I require. If I create threads via `threading.Thread`, which then throw exceptions which are unhandled, those threads are terminated. I wish to retain the default print out of the exception details with the stack trace, but bring down the whole process as we...
I wrote about [Re-throwing exceptions in Python](http://nedbatchelder.com/blog/200711/rethrowing%5Fexceptions%5Fin%5Fpython.html), including something very much like this as an example. On your worker thread you do this: ``` try: self.result = self.do_something_dangerous() except Exception, e: import sys ...
Django edit form based on add form?
1,854,237
30
2009-12-06T03:18:48Z
1,854,453
73
2009-12-06T05:27:24Z
[ "python", "django", "forms", "logic" ]
I've made a nice form, and a big complicated 'add' function for handling it. It starts like this... ``` def add(req): if req.method == 'POST': form = ArticleForm(req.POST) if form.is_valid(): article = form.save(commit=False) article.author = req.user # more proc...
If you are extending your form from a ModelForm, use the `instance` keyword argument. Here we pass either an existing `instance` or a new one, depending on whether we're editing or adding an existing article. In both cases the `author` field is set on the instance, so `commit=False` is not required. Note also that I'm ...
Google App Engine Application Extremely slow
1,854,821
15
2009-12-06T08:58:43Z
1,854,875
14
2009-12-06T09:29:52Z
[ "python", "django", "google-app-engine" ]
I created a Hello World website in Google App Engine. It is using Django 1.1 without any patch. Even though it is just a very simple web page, it takes long time and often it times out. Any suggestions to solve this? Note: It is responding fast after the first call.
This is a horrible suggestion but I'll make it anyway: Build a little client application or just use `wget` with `cron` to periodically access your app, maybe once every 5 minutes or so. That should keep Google from putting it into a dormant state. I say this is a horrible suggestion because it's a waste of resources...
Google App Engine Application Extremely slow
1,854,821
15
2009-12-06T08:58:43Z
1,864,345
7
2009-12-08T03:17:55Z
[ "python", "django", "google-app-engine" ]
I created a Hello World website in Google App Engine. It is using Django 1.1 without any patch. Even though it is just a very simple web page, it takes long time and often it times out. Any suggestions to solve this? Note: It is responding fast after the first call.
To summarize [this thread](http://groups.google.com/group/google-appengine/browse%5Fthread/thread/22692895421825cb) so far: * Cold starts take a long time * Google discourages pinging apps to keep them warm, but people do not know the alternative * There is [an issue filed](http://code.google.com/p/googleappengine/iss...
Google App Engine Application Extremely slow
1,854,821
15
2009-12-06T08:58:43Z
5,017,635
19
2011-02-16T14:29:37Z
[ "python", "django", "google-app-engine" ]
I created a Hello World website in Google App Engine. It is using Django 1.1 without any patch. Even though it is just a very simple web page, it takes long time and often it times out. Any suggestions to solve this? Note: It is responding fast after the first call.
Now Google has added a payment option "Always On" which is 0.30$ a day. Using this feature, your application will not have to cold start any more. > Always On > > While warmup requests help your > application scale smoothly, they do > not help if your application has very > low amounts of traffic. For > high-priority...
How to create a zip archive of a directory
1,855,095
137
2009-12-06T11:12:53Z
1,855,118
206
2009-12-06T11:23:55Z
[ "python", "zipfile" ]
How can I create a zip archive of a directory structure in Python?
As others have pointed out, you should use [zipfile](http://docs.python.org/library/zipfile.html). The documentation tells you what functions are available, but doesn't really explain how you can use them to zip an entire directory. I think it's easiest to explain with some example code: ``` #!/usr/bin/env python impo...
How to create a zip archive of a directory
1,855,095
137
2009-12-06T11:12:53Z
1,855,122
45
2009-12-06T11:28:24Z
[ "python", "zipfile" ]
How can I create a zip archive of a directory structure in Python?
To add the contents of `mydirectory` to a new zip file, including all files and subdirectories: ``` import os import zipfile zf = zipfile.ZipFile("myzipfile.zip", "w") for dirname, subdirs, files in os.walk("mydirectory"): zf.write(dirname) for filename in files: zf.write(os.path.join(dirname, filenam...
How to create a zip archive of a directory
1,855,095
137
2009-12-06T11:12:53Z
16,254,846
8
2013-04-27T17:14:02Z
[ "python", "zipfile" ]
How can I create a zip archive of a directory structure in Python?
For adding compression to the resulting zip file, check out [this link](http://neopatel.blogspot.ca/2010/07/creating-zip-file-in-python-and.html). You need to change: ``` zip = zipfile.ZipFile('Python.zip', 'w') ``` to ``` zip = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED) ```
How to create a zip archive of a directory
1,855,095
137
2009-12-06T11:12:53Z
17,080,988
21
2013-06-13T06:57:03Z
[ "python", "zipfile" ]
How can I create a zip archive of a directory structure in Python?
This function will recursively zip up a directory tree, *compressing* the files, and recording the correct relative filenames in the archive. The archive entries are the same as those generated by `zip -r output.zip source_dir`. ``` def make_zipfile(output_filename, source_dir): relroot = os.path.abspath(os.path.j...
How to create a zip archive of a directory
1,855,095
137
2009-12-06T11:12:53Z
25,650,295
138
2014-09-03T17:26:41Z
[ "python", "zipfile" ]
How can I create a zip archive of a directory structure in Python?
The easiest way is to use [shutil.make\_archive](https://docs.python.org/2/library/shutil.html#shutil.make_archive). It supports both zip and tar formats. ``` import shutil shutil.make_archive(output_filename, 'zip', dir_name) ``` If you need to do something more complicated than zipping the whole directory (such as ...
How to create a zip archive of a directory
1,855,095
137
2009-12-06T11:12:53Z
36,341,469
7
2016-03-31T18:57:20Z
[ "python", "zipfile" ]
How can I create a zip archive of a directory structure in Python?
> # How can I create a zip archive of a directory structure in Python? ## In a Python script In Python 2.7+, `shutil` has a `make_archive` function. ``` from shutil import make_archive make_archive( 'zipfile_name', 'zip', # the archive format - or tar, bztar, gztar root_dir=None, # root for archi...
What is the best way to call Java code from Python?
1,855,320
11
2009-12-06T12:54:15Z
1,855,323
14
2009-12-06T12:55:44Z
[ "java", "python" ]
I have a Java class library (3rd party, proprietary) and I want my python script to call its functions. I already have java code that uses this library. What is the best way to achieve this?
Can you run your current Python scripts under [Jython](http://www.jython.org) ? If so, that's probably the best way, since the Java library can be exposed directly into Jython as scriptable objects. Failing that, there are a number of solutions listed [here](http://wiki.cacr.caltech.edu/danse/index.php/Communication%5...
What is the best way to call Java code from Python?
1,855,320
11
2009-12-06T12:54:15Z
1,855,374
8
2009-12-06T13:19:04Z
[ "java", "python" ]
I have a Java class library (3rd party, proprietary) and I want my python script to call its functions. I already have java code that uses this library. What is the best way to achieve this?
The other answer is [JPype](http://jpype.sourceforge.net/), which allows CPython to talk to Java. It's useful if you can't switch to Jython.
Converting a Tuples List into a nested List using Python
1,855,471
3
2009-12-06T14:04:32Z
1,855,502
11
2009-12-06T14:16:01Z
[ "python", "list", "nested", "tuples" ]
I want to convert a tuples list into a nested list using Python. How do I do that? I have a sorted list of tuples (sorted by the second value): ``` [(1, 5), (5, 4), (13, 3), (4, 3), (3, 2), (14, 1), (12, 1), (10, 1), (9, 1), (8, 1), (7, 1), (6, 1), (2, 1)] ``` Now I want it to have like this (second value ignore...
``` from operator import itemgetter from itertools import groupby lst = [(1, 5), (5, 4), (13, 3), (4, 3), (3, 2), (14, 1), (12, 1), (10, 1), (9, 1), (8, 1), (7, 1), (6, 1), (2, 1)] result = [[x for x, y in group] for key, group in groupby(lst, key=itemgetter(1))] ``` `groupby(lst, key=itemgetter(1...