title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python HTML sanitizer / scrubber / filter | 699,468 | 60 | 2009-03-30T23:25:29Z | 5,246,109 | 10 | 2011-03-09T12:56:43Z | [
"python",
"html",
"filter"
] | I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist. | I modified [Bryan](http://stackoverflow.com/users/73049/bryan)'s [solution with BeautifulSoup](http://stackoverflow.com/questions/699468/python-html-sanitizer-scrubber-filter/699483#699483) to address the [problem raised by Chris Drost](http://stackoverflow.com/questions/699468/python-html-sanitizer-scrubber-filter/812... |
Python HTML sanitizer / scrubber / filter | 699,468 | 60 | 2009-03-30T23:25:29Z | 19,605,146 | 19 | 2013-10-26T09:41:36Z | [
"python",
"html",
"filter"
] | I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist. | [Bleach](https://github.com/jsocol/bleach) does better with more useful options. It's built on html5lib and ready for production.
Check this [documents](http://bleach.readthedocs.org/en/latest/clean.html). |
python decorators and methods | 699,526 | 7 | 2009-03-30T23:59:12Z | 699,549 | 7 | 2009-03-31T00:15:02Z | [
"python",
"metaprogramming",
"decorator"
] | New here. Also I'm (very) new to python and trying to understand the following behavior. Can someone explain to me why the two methods in this example have different output?
```
def map_children(method):
def wrapper(self,*args,**kwargs):
res = method(self,*args,**kwargs)
for child in self._children... | In the decorator, you are looping over the node's children and calling the *original*, non-recursive `method` on them
```
method(child, *args, **kwargs)
```
so you'll only go one level deep. Try replacing that line with
```
map_children(method)(child, *args, **kwargs)
```
and you'll get the same output as the manua... |
Python int to binary? | 699,866 | 183 | 2009-03-31T03:04:37Z | 699,891 | 235 | 2009-03-31T03:17:18Z | [
"python"
] | Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?
There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library. | Python's string format method can take a format spec.
```
>>> "{0:b}".format(10)
'1010'
```
[Format spec docs for Python 2](https://docs.python.org/2/library/string.html#formatspec)
[Format spec docs for Python 3](https://docs.python.org/3/library/string.html#formatspec) |
Python int to binary? | 699,866 | 183 | 2009-03-31T03:04:37Z | 699,892 | 203 | 2009-03-31T03:17:30Z | [
"python"
] | Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?
There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library. | If you're looking for [`bin()`](http://docs.python.org/library/functions.html#bin) as an equivalent to `hex()`, it was added in python 2.6.
Example:
```
>>> bin(10)
'0b1010'
``` |
Python int to binary? | 699,866 | 183 | 2009-03-31T03:04:37Z | 699,901 | 32 | 2009-03-31T03:25:52Z | [
"python"
] | Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?
There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library. | No language or library will give its user base *everything* that they desire. If you're working in an envronment that doesn't provide exactly what you need, you should be collecting snippets of code as you develop to ensure you never have to write the same thing twice. Such as, for example:
```
def int2bin(i):
if ... |
Python int to binary? | 699,866 | 183 | 2009-03-31T03:04:37Z | 20,643,178 | 17 | 2013-12-17T19:39:08Z | [
"python"
] | Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?
There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library. | As a reference:
```
def toBinary(n):
return ''.join(str(1 & int(n) >> i) for i in range(64)[::-1])
```
This function can convert a positive integer as large as `18446744073709551615`, represented as string `'1111111111111111111111111111111111111111111111111111111111111111'`.
It can be modified to serve a much la... |
Python int to binary? | 699,866 | 183 | 2009-03-31T03:04:37Z | 21,732,313 | 17 | 2014-02-12T15:33:28Z | [
"python"
] | Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?
There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library. | If you want a textual representation without the 0b-prefix, you could use this:
```
get_bin = lambda x: format(x, 'b')
print(get_bin(3))
>>> '11'
print(get_bin(-3))
>>> '-11'
```
When you want a n-bit representation:
```
get_bin = lambda x, n: format(x, 'b').zfill(n)
>>> get_bin(12, 32)
'00000000000000000000000000... |
Python int to binary? | 699,866 | 183 | 2009-03-31T03:04:37Z | 30,836,520 | 10 | 2015-06-15T02:12:19Z | [
"python"
] | Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?
There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library. | one-liner with **lambda**:
```
>>> binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)
```
test:
```
>>> binary(5)
'101'
```
**EDIT**:
but then :(
```
t1 = time()
for i in range(1000000):
binary(i)
t2 = time()
print(t2 - t1)
# 6.57236599922
```
in compare to
```
t1 = time()
for i in range(1000000):
... |
Format a number as a string | 700,016 | 3 | 2009-03-31T04:42:58Z | 700,032 | 8 | 2009-03-31T04:49:27Z | [
"python",
"string",
"integer",
"format"
] | How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this?
```
a = str(52500)
b = str(5)
lengt... | [Format operator](http://docs.python.org/library/stdtypes.html#string-formatting):
```
>>> "%10d" % 5
' 5'
>>>
```
Using `*` spec, the field length can be an argument:
```
>>> "%*d" % (10,5)
' 5'
>>>
``` |
How to add a Python import path using a .pth file | 700,375 | 10 | 2009-03-31T07:15:05Z | 700,394 | 30 | 2009-03-31T07:23:40Z | [
"python",
"python-import"
] | If I put a \*.pth file in site-packages it's giving an `ImportError`.
I'm not getting how to import by creating a \*.pth file.
*(Refers to [importing in python](http://stackoverflow.com/questions/697281/importing-in-python))* | If you put a `.pth` file in the `site-packages` directory containing a path, python searches this path for imports. So I have a `sth.pth` file there that simply contains:
```
K:\Source\Python\lib
```
In that directory there are some normal Python modules:
```
logger.py
fstools.py
...
```
This allows to directly imp... |
How to add a Python import path using a .pth file | 700,375 | 10 | 2009-03-31T07:15:05Z | 700,512 | 22 | 2009-03-31T08:11:16Z | [
"python",
"python-import"
] | If I put a \*.pth file in site-packages it's giving an `ImportError`.
I'm not getting how to import by creating a \*.pth file.
*(Refers to [importing in python](http://stackoverflow.com/questions/697281/importing-in-python))* | ```
/tmp/$ mkdir test; cd test
/tmp/test/$ mkdir foo; mkdir bar
/tmp/test/$ echo -e "foo\nbar" > foobar.pth
/tmp/test/$ cd ..
/tmp/$ python
Python 2.6 (r26:66714, Feb 3 2009, 20:52:03)
[GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> impo... |
EOFError in Python script | 700,873 | 4 | 2009-03-31T13:12:33Z | 700,914 | 14 | 2009-03-31T13:21:31Z | [
"python",
"pickle",
"raw-input",
"eoferror"
] | I have the following code fragment:
```
def database(self):
databasename=""
host=""
user=""
password=""
try:
self.fp=file("detailing.dat","rb")
except IOError:
self.fp=file("detailing.dat","wb")
pickle.dump([databasename,host,user,password],self.fp,-1)
self.fp.cl... | Unless you've got a typo, the issue may be in this line where you assign the file handle to `selffp` not `self.fp`:
```
selffp=file("detailing.dat","rb")
```
If that is a typo, and your code actually opens the file to `self.fp`, then you may wish to verify that the file actually has contents (ie: that the previous pi... |
Py3k memory conservation by returning iterators rather than lists | 701,088 | 2 | 2009-03-31T13:55:17Z | 701,889 | 7 | 2009-03-31T16:27:59Z | [
"python",
"memory",
"list",
"iterator",
"python-3.x"
] | Many methods that used to return lists in Python 2.x now seem to return iterators in Py3k
Are iterators also generator expressions? Lazy evaluation?
Thus, with this the memory footprint of python is going to reduce drastically. Isn't it?
What about for the programs converted from 2to3 using the builtin script?
Does... | Many of them are not exactly iterators, but special view objects. For instance range() now returns something similar to the old xrange object - it can still be indexed, but lazily constructs the integers as needed.
Similarly dict.keys() gives a dict\_keys object implementing a view on the dict, rather than creating a ... |
Best way to choose a random file from a directory | 701,402 | 10 | 2009-03-31T14:58:41Z | 701,430 | 31 | 2009-03-31T15:02:21Z | [
"python",
"file",
"random"
] | What is the best way to choose a random file from a directory in Python?
*Edit:* Here is what I am doing:
```
import os
import random
import dircache
dir = 'some/directory'
filename = random.choice(dircache.listdir(dir))
path = os.path.join(dir, filename)
```
Is this particularly bad, or is there a particularly bet... | ```
import os, random
random.choice(os.listdir("C:\\")) #change dir name to whatever
```
---
Regarding your edited question: first, I assume you know the risks of using a `dircache`, as well as the fact that it is [deprecated since 2.6, and removed in 3.0](http://docs.python.org/library/dircache.html).
Second of all... |
Nested try statements in python? | 701,466 | 28 | 2009-03-31T15:07:16Z | 701,542 | 21 | 2009-03-31T15:19:15Z | [
"python",
"try-catch"
] | Is there a nicer way of doing the following:
```
try:
a.method1()
except AttributeError:
try:
a.method2()
except AttributeError:
try:
a.method3()
except AttributeError:
raise
```
It looks pretty nasty and I'd rather not do:
```
if hasattr(a, 'method1'):
... | Perhaps you could try something like this:
```
def call_attrs(obj, attrs_list, *args):
for attr in attrs_list:
if hasattr(obj, attr):
bound_method = getattr(obj, attr)
return bound_method(*args)
raise AttributeError
```
You would call it like this:
```
call_attrs(a, ['method1... |
Nested try statements in python? | 701,466 | 28 | 2009-03-31T15:07:16Z | 701,682 | 20 | 2009-03-31T15:50:14Z | [
"python",
"try-catch"
] | Is there a nicer way of doing the following:
```
try:
a.method1()
except AttributeError:
try:
a.method2()
except AttributeError:
try:
a.method3()
except AttributeError:
raise
```
It looks pretty nasty and I'd rather not do:
```
if hasattr(a, 'method1'):
... | A slight change to the second looks pretty nice and simple. I really doubt you'll notice any performance difference between the two, and this is a bit nicer than a nested try/excepts
```
def something(a):
for methodname in ['method1', 'method2', 'method3']:
try:
m = getattr(a, methodname)
... |
Convert HTML entities to Unicode and vice versa | 701,704 | 36 | 2009-03-31T15:54:25Z | 701,722 | 20 | 2009-03-31T15:57:56Z | [
"python",
"html",
"html-entities"
] | > **Possible duplicates:**
>
> * [Convert XML/HTML Entities into Unicode String in Python](http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python)
> * [HTML Entity Codes to Text](http://stackoverflow.com/questions/663058/html-entity-codes-to-text)
How do you convert HTML entit... | You need to have [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/).
```
from BeautifulSoup import BeautifulStoneSoup
import cgi
def HTMLEntitiesToUnicode(text):
"""Converts HTML entities to unicode. For example '&' becomes '&'."""
text = unicode(BeautifulStoneSoup(text, convertEntities=Beaut... |
Convert HTML entities to Unicode and vice versa | 701,704 | 36 | 2009-03-31T15:54:25Z | 2,657,467 | 67 | 2010-04-17T06:13:38Z | [
"python",
"html",
"html-entities"
] | > **Possible duplicates:**
>
> * [Convert XML/HTML Entities into Unicode String in Python](http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python)
> * [HTML Entity Codes to Text](http://stackoverflow.com/questions/663058/html-entity-codes-to-text)
How do you convert HTML entit... | As to the "vice versa" (which I needed myself, leading me to find this question, which didn't help, and subsequently [another site which had the answer](http://www.megasolutions.net/python/Unicode-to-HTML-entities-78703.aspx)):
```
u'some string'.encode('ascii', 'xmlcharrefreplace')
```
will return a plain string wit... |
How do I execute a string containing Python code in Python? | 701,802 | 156 | 2009-03-31T16:12:20Z | 701,810 | 37 | 2009-03-31T16:14:38Z | [
"python",
"string",
"exec"
] | How do I execute a string containing Python code in Python? | In the example a string is executed as code using the exec function.
```
import sys
import StringIO
# create file-like string to capture output
codeOut = StringIO.StringIO()
codeErr = StringIO.StringIO()
code = """
def f(x):
x = x + 1
return x
print 'This is my output.'
"""
# capture output and errors
sys.... |
How do I execute a string containing Python code in Python? | 701,802 | 156 | 2009-03-31T16:12:20Z | 701,813 | 169 | 2009-03-31T16:15:24Z | [
"python",
"string",
"exec"
] | How do I execute a string containing Python code in Python? | For statements, use [`exec(string)`](https://docs.python.org/library/functions.html#exec) (Python 2/3) or [`exec string`](https://docs.python.org/2/reference/simple_stmts.html#grammar-token-exec_stmt) (Python 2):
```
>>> mycode = 'print "hello world"'
>>> exec(mycode)
Hello world
```
When you need the value of an exp... |
How do I execute a string containing Python code in Python? | 701,802 | 156 | 2009-03-31T16:12:20Z | 4,278,878 | 11 | 2010-11-25T16:03:11Z | [
"python",
"string",
"exec"
] | How do I execute a string containing Python code in Python? | `eval()` is just for expressions, while `eval('x+1')` works, `eval('x=1')` won't work for example. In that case, it's better to use `exec`, or even better: try to find a better solution :) |
How do I execute a string containing Python code in Python? | 701,802 | 156 | 2009-03-31T16:12:20Z | 11,551,525 | 7 | 2012-07-18T22:51:49Z | [
"python",
"string",
"exec"
] | How do I execute a string containing Python code in Python? | You accomplish executing code using exec, as with the following IDLE session:
```
>>> kw = {}
>>> exec( "ret = 4" ) in kw
>>> kw['ret']
4
``` |
How do I execute a string containing Python code in Python? | 701,802 | 156 | 2009-03-31T16:12:20Z | 14,926,430 | 8 | 2013-02-17T21:44:32Z | [
"python",
"string",
"exec"
] | How do I execute a string containing Python code in Python? | `eval` and `exec` are the correct solution, and they can be used in a safe manner!
As discussed in [Python's reference manual](http://docs.python.org/2/reference/simple_stmts.html#exec) and clearly explained in [this](http://lybniz2.sourceforge.net/safeeval.html) tutorial, the `eval` and `exec` functions take two extr... |
How do I execute a string containing Python code in Python? | 701,802 | 156 | 2009-03-31T16:12:20Z | 17,378,416 | 17 | 2013-06-29T08:49:04Z | [
"python",
"string",
"exec"
] | How do I execute a string containing Python code in Python? | Remember that from version 3 `exec` is a function!
so always use `exec(mystring)` instead of `exec mystring`. |
Django vs other Python web frameworks? | 702,179 | 58 | 2009-03-31T17:39:02Z | 702,215 | 7 | 2009-03-31T17:46:40Z | [
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] | I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with [Snakelets](http://snakelets.sf.net) and heartily enjoyed being able to control almost everything at a lower leve... | Have you taken a look at CherryPy. It is minimalistic, yet efficient and simple. It is low level enough for not it to get in they way, but high enough to hide complexity. If I remember well, TurboGears was built on it.
With CherryPy, you have the choice of much everything. (Template framework, ORM if wanted, back-end,... |
Django vs other Python web frameworks? | 702,179 | 58 | 2009-03-31T17:39:02Z | 702,360 | 21 | 2009-03-31T18:11:31Z | [
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] | I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with [Snakelets](http://snakelets.sf.net) and heartily enjoyed being able to control almost everything at a lower leve... | I'd say you're being a bit too pessimistic about "not learning anything" using Django or a similar full-stack framework, and underestimating the value of documentation and a large community. Even with Django there's still a considerable learning curve; and if it doesn't do everything you want, it's not like the framewo... |
Django vs other Python web frameworks? | 702,179 | 58 | 2009-03-31T17:39:02Z | 703,232 | 15 | 2009-03-31T21:54:24Z | [
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] | I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with [Snakelets](http://snakelets.sf.net) and heartily enjoyed being able to control almost everything at a lower leve... | I suggest taking another look at TG2. I think people have failed to notice some of the strides that have been made since the last version. Aside from the growing WSGI stack of utilities available there are quite a few TG2-specific items to consider. Here are a couple of highlights:
[TurboGears Administration System](h... |
Django vs other Python web frameworks? | 702,179 | 58 | 2009-03-31T17:39:02Z | 703,271 | 11 | 2009-03-31T22:07:15Z | [
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] | I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with [Snakelets](http://snakelets.sf.net) and heartily enjoyed being able to control almost everything at a lower leve... | Your question seems to be "is it worth learning WSGI and doing everything yourself," or using a "full stack framework that does everything for you."
I'd say that's a false dichotomy and there's an obvious third way. TurboGears 2 tries to provide a smooth path from a "do everything for you" style framework up to an und... |
Django vs other Python web frameworks? | 702,179 | 58 | 2009-03-31T17:39:02Z | 703,326 | 52 | 2009-03-31T22:25:31Z | [
"python",
"django",
"wsgi",
"web-frameworks",
"turbogears"
] | I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with [Snakelets](http://snakelets.sf.net) and heartily enjoyed being able to control almost everything at a lower leve... | > the religious debates between the Django and WSGI camps
It would seem as though you're a tad bit confused about what WSGI is and what Django is. Saying that Django and WSGI are competing is a bit like saying that C and SQL are competing: you're comparing apples and oranges.
Django is a framework, WSGI is a protocol... |
How to make Django slugify work properly with Unicode strings? | 702,337 | 28 | 2009-03-31T18:07:54Z | 702,445 | 10 | 2009-03-31T18:30:52Z | [
"python",
"django",
"unicode",
"django-templates",
"slug"
] | What can I do to prevent `slugify` filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)
[cnprog.com](http://cnprog.com) has Chinese characters in question URLs, so I looked in their code. They are not using `slugify` in templates, instead they're calling this method in `Question` model... | I'm afraid django's definition of slug means ascii, though the django docs don't explicitly state this. This is the source of the defaultfilters for the slugify... you can see that the values are being converted to ascii, with the 'ignore' option in case of errors:
```
import unicodedata
value = unicodedata.normalize(... |
How to make Django slugify work properly with Unicode strings? | 702,337 | 28 | 2009-03-31T18:07:54Z | 4,019,144 | 15 | 2010-10-25T21:45:40Z | [
"python",
"django",
"unicode",
"django-templates",
"slug"
] | What can I do to prevent `slugify` filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)
[cnprog.com](http://cnprog.com) has Chinese characters in question URLs, so I looked in their code. They are not using `slugify` in templates, instead they're calling this method in `Question` model... | Also, the Django version of slugify doesn't use the re.UNICODE flag, so it wouldn't even attempt to understand the meaning of `\w\s` as it pertains to non-ascii characters.
This custom version is working well for me:
```
def u_slugify(txt):
"""A custom version of slugify that retains non-ascii characters. The... |
How to make Django slugify work properly with Unicode strings? | 702,337 | 28 | 2009-03-31T18:07:54Z | 4,036,665 | 76 | 2010-10-27T18:58:15Z | [
"python",
"django",
"unicode",
"django-templates",
"slug"
] | What can I do to prevent `slugify` filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)
[cnprog.com](http://cnprog.com) has Chinese characters in question URLs, so I looked in their code. They are not using `slugify` in templates, instead they're calling this method in `Question` model... | There is a python package called [unidecode](http://pypi.python.org/pypi/Unidecode) that I've adopted for the askbot Q&A forum, it works well for the latin-based alphabets and even looks reasonable for greek:
```
>>> import unidecode
>>> from unidecode import unidecode
>>> unidecode(u'διακÏιÏικÏÏ')
'diakrit... |
How to make Django slugify work properly with Unicode strings? | 702,337 | 28 | 2009-03-31T18:07:54Z | 6,191,847 | 7 | 2011-05-31T18:26:39Z | [
"python",
"django",
"unicode",
"django-templates",
"slug"
] | What can I do to prevent `slugify` filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)
[cnprog.com](http://cnprog.com) has Chinese characters in question URLs, so I looked in their code. They are not using `slugify` in templates, instead they're calling this method in `Question` model... | You might want to look at:
<https://github.com/un33k/django-uuslug>
It will take care of both "U"s for you. **U** in unique and **U** in Unicode.
It will do the job for you hassle free. |
How to make Django slugify work properly with Unicode strings? | 702,337 | 28 | 2009-03-31T18:07:54Z | 7,041,953 | 19 | 2011-08-12T14:55:48Z | [
"python",
"django",
"unicode",
"django-templates",
"slug"
] | What can I do to prevent `slugify` filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)
[cnprog.com](http://cnprog.com) has Chinese characters in question URLs, so I looked in their code. They are not using `slugify` in templates, instead they're calling this method in `Question` model... | The Mozilla website team has been working on an implementation :
<https://github.com/mozilla/unicode-slugify>
sample code at
<http://davedash.com/2011/03/24/how-we-slug-at-mozilla/> |
How to get number of affected rows in sqlalchemy? | 702,342 | 17 | 2009-03-31T18:08:34Z | 702,398 | 19 | 2009-03-31T18:21:52Z | [
"python",
"sqlalchemy"
] | I have one question concerning Python and the sqlalchemy module. What is the equivalent for `cursor.rowcount` in the sqlalchemy Python? | Although it isn't really stated in the docs, a `ResultProxy` object does have a `rowcount` property as well. |
Python 3.0.1 Executable Creator | 702,395 | 6 | 2009-03-31T18:21:20Z | 1,263,241 | 11 | 2009-08-11T22:07:12Z | [
"python",
"executable",
"py2exe",
"pyinstaller"
] | Does anyone know if there's a windows Python executable creator program available now that supports Python 3.0.1? It seems that py2exe and pyInstaller, along with all the rest I've found, still aren't anywhere close to supporting 3.0 or 3.0.1.
Any help is greatly appreciated.
Edit: I guess I could downgrade the progr... | How about [cx\_Freeze](http://cx-freeze.sourceforge.net/). Seems to support python 3.0 and 3.1? |
How to limit I/O consumption of Python processes (possibly using ionice)? | 702,407 | 12 | 2009-03-31T18:23:07Z | 6,245,160 | 13 | 2011-06-05T19:04:18Z | [
"python",
"linux",
"performance",
"unix"
] | I would like a particular set of Python subprocesses to be as low-impact as possible. I'm already using [nice](http://www.manpagez.com/man/1/nice/) to help limit CPU consumption. But ideally I/O would be limited as well. (If skeptical, please humor me and assume there is value in doing this; it doesn't matter how long ... | [psutil](http://code.google.com/p/psutil/) exposes this functionality (python 2.4 -> 3.2):
```
import psutil, os
p = psutil.Process(os.getpid())
p.ionice(psutil.IOPRIO_CLASS_IDLE)
```
Also, starting from Python 3.3 this will be available in python stdlib as well:
<http://bugs.python.org/issue10784> |
Django admin - inline inlines (or, three model editing at once) | 702,637 | 48 | 2009-03-31T19:20:51Z | 1,332,476 | 19 | 2009-08-26T05:18:15Z | [
"python",
"django",
"django-models",
"django-admin",
"inlines"
] | I've got a set of models that look like this:
```
class Page(models.Model):
title = models.CharField(max_length=255)
class LinkSection(models.Model):
page = models.ForeignKey(Page)
title = models.CharField(max_length=255)
class Link(models.Model):
linksection = models.ForeignKey(LinkSection)
text... | You need to create a custom [form](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form) and [template](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#template) for the `LinkSectionInline`.
Something like this should work for the form:
```
LinkFormset = forms.modelformset_factory(Link)
class LinkSect... |
How do I generate multi-word terms recursively? | 702,760 | 5 | 2009-03-31T19:54:20Z | 702,807 | 11 | 2009-03-31T20:07:02Z | [
"python",
"recursion"
] | Say I have a string of words: `'a b c d e f'`. I want to generate a list of multi-word terms from this string.
Word order matters. The term `'f e d'` shouldn't be generated from the above example.
**Edit:** Also, words should not be skipped. `'a c'`, or `'b d f'` shouldn't be generated.
**What I have right now:**
`... | This isn't recursive, but I think it does what you want.
```
doc = 'a b c d e f'
words = doc.split(None)
max = 3
for index in xrange(len(words)):
for n in xrange(max):
if index + n < len(words):
print ' '.join(words[index:index+n+1])
```
And here's a recursive soluti... |
Executing Java programs through Python | 702,861 | 8 | 2009-03-31T20:20:32Z | 702,888 | 8 | 2009-03-31T20:25:59Z | [
"java",
"python"
] | How do I do this? | You can execute anything you want from Python with the [`os.system()`](http://docs.python.org/library/os.html#os.system) function.
> **os.system(command)**
> Execute the command
> (a string) in a subshell. This is
> implemented by calling the Standard C
> function system, and has the same
> limitations. Changes to o... |
URL encode a non-value pair in Python | 702,986 | 14 | 2009-03-31T20:48:16Z | 703,002 | 36 | 2009-03-31T20:52:33Z | [
"python",
"json",
"urlencode"
] | I'm trying to use Google's AJAX (JSON) Web Search API in Python. I'm stuck because Python's urllib.urlencode() only takes value pairs, not strings by themselves, to encode. In Google's API, the query string is the search term and it doesn't associate with a variable.
```
query = "string that needs to be encoded"
param... | I think you're looking for [`urllib.quote`](http://docs.python.org/library/urllib.html#urllib.quote) instead. |
Using email.HeaderParser with imaplib.fetch in python? | 703,185 | 7 | 2009-03-31T21:40:57Z | 703,479 | 16 | 2009-03-31T23:27:07Z | [
"python",
"email"
] | Does anyone have a good example of using the HeaderParser class in Python for a message that you pull down with imaplib.fetch?
I have been able to find a lot of related things, but nothing that does just this.
Do I need to full down the fetch has an RFC822? I was hoping to simply pull down the subjects.
Thanks! | Good news: you're right... you don't need to pull down the RFC822. The `message_parts` parameter to `fetch()` lets you be quite fine-grained.
Here's a simple example of how to fetch just the header:
```
import imaplib
from email.parser import HeaderParser
conn = imaplib.IMAP4('my.host.com')
conn.login('[email protected]... |
Most efficient way of loading formatted binary files in Python | 703,262 | 5 | 2009-03-31T22:03:36Z | 703,267 | 8 | 2009-03-31T22:05:12Z | [
"python",
"input",
"binaryfiles"
] | I have binary files no larger than 20Mb in size that have a header section and then a data section containing sequences of uchars. I have Numpy, SciPy, etc. and each library has different ways of loading in the data. Any suggestions for the most efficient methods I should use? | Use the [struct](http://docs.python.org/library/struct.html) module, or possibly a custom module written in C if performance is critical. |
Python: an iteration over a non-empty list with no if-clause comes up empty. Why? | 703,520 | 4 | 2009-03-31T23:53:51Z | 703,534 | 13 | 2009-03-31T23:59:40Z | [
"python",
"iterator",
"generator",
"leaky-abstraction"
] | How can an iterator over a non-empty sequence, with no filtering and no aggregation (`sum()`, etc.), yield nothing?
Consider a simple example:
```
sequence = ['a', 'b', 'c']
list((el, ord(el)) for el in sequence)
```
This yields `[('a', 97), ('b', 98), ('c', 99)]` as expected.
Now, just swap the `ord(el)` out for a... | `odd_integers_up_to_length(el).next()` will raise StopIteration, which isn't caught there, but is caught for the generator expression within it, stopping it without ever yielding anything.
look at the first iteration, when the value is 'a':
```
>>> odd_integers_up_to_length('a').next()
Traceback (most recent call las... |
Anything like SciPy in Ruby? | 703,717 | 14 | 2009-04-01T01:33:31Z | 703,731 | 17 | 2009-04-01T01:39:34Z | [
"python",
"ruby",
"math",
"scipy"
] | Looking further into the differences between Python and Ruby, is there a Ruby equivalent to SciPy, or what other scientific math gems are available for Ruby? | There's nothing quite as mature or well done as SciPy, but check out [SciRuby](http://sciruby.com/) and [Numerical Ruby](http://narray.rubyforge.org/). |
How would I compute exactly 30 days into the past with Python (down to the minute)? | 703,907 | 16 | 2009-04-01T02:59:46Z | 703,912 | 37 | 2009-04-01T03:01:48Z | [
"python",
"datetime",
"date",
"time"
] | In Python, I'm attempting to retrieve the date/time that is exactly 30 days (30\*24hrs) into the past. At present, I'm simply doing:
```
>>> import datetime
>>> start_date = datetime.date.today() + datetime.timedelta(-30)
```
Which returns a datetime object, but with no time data:
```
>>> start_date.year
2009
>>> st... | You want to use a `datetime` object instead of just a `date` object:
```
start_date = datetime.datetime.now() + datetime.timedelta(-30)
```
`date` just stores a date and `time` just a time. `datetime` is a date with a time. |
Using pydev with Eclipse on OSX | 703,925 | 11 | 2009-04-01T03:11:00Z | 2,785,302 | 10 | 2010-05-06T23:53:40Z | [
"python",
"eclipse"
] | I setup PyDev with this path for the python interpreter
/System/Library/Frameworks/Python.framework/Versions/2.5/Python
since the one under /usr/bin were alias and Eclipse won't select it. I can run my python script now but cannot run the shell as an external tool. The message I get is
variable references empty select... | I installed the Python.org version as well, this is a must.
I finally got PyDev working in Eclipse by pointing the interpreter to:
```
/Library/Frameworks/Python.framework/Versions/2.6/bin/python
```
manually. If you don't do it manually (by using the Autoconfig) it seems to not find the right version. |
Can I transpose a file in Vim? | 704,130 | 12 | 2009-04-01T05:09:10Z | 704,139 | 10 | 2009-04-01T05:13:33Z | [
"python",
"vim",
"text-files",
"text-parsing"
] | I know I can use AWK but I am on a Windows box. I am making a function for others that may not have AWK. I also know I can write a C program but I would love not have to create maintain and compile something for a little Vim utility I am making.
The original file might be
```
THE DAY WAS LONG
THE WAY WAS FAST
```
a... | Vim support for a number of scripting languages built in -- see [the Python interface](http://www.vim.org/htmldoc/if_pyth.html) as an example.
Just modify `vim.current.buffer` appropriately and you're set.
To be a little more specific:
```
function! Rotate()
python <<EOF
import vim, itertools
max_len = max((len(n) f... |
Can I transpose a file in Vim? | 704,130 | 12 | 2009-04-01T05:09:10Z | 704,797 | 11 | 2009-04-01T09:42:24Z | [
"python",
"vim",
"text-files",
"text-parsing"
] | I know I can use AWK but I am on a Windows box. I am making a function for others that may not have AWK. I also know I can write a C program but I would love not have to create maintain and compile something for a little Vim utility I am making.
The original file might be
```
THE DAY WAS LONG
THE WAY WAS FAST
```
a... | Here is a command in Vim language. So you don't have to compile Vim with +python support.
```
function! s:transpose()
let maxcol = 0
let lines = getline(1, line('$'))
for line in lines
let len = len(line)
if len > maxcol
let maxcol = len
endif
endfor
let newli... |
How can I convert a character to a integer in Python, and viceversa? | 704,152 | 160 | 2009-04-01T05:19:15Z | 704,158 | 20 | 2009-04-01T05:21:39Z | [
"python",
"integer",
"char",
"type-conversion"
] | I want to get, given a character, its `ASCII` value.
For example, for the character `a`, I want to get `97`, and vice versa. | ```
>>> ord('a')
97
>>> chr(97)
'a'
``` |
How can I convert a character to a integer in Python, and viceversa? | 704,152 | 160 | 2009-04-01T05:19:15Z | 704,160 | 300 | 2009-04-01T05:22:00Z | [
"python",
"integer",
"char",
"type-conversion"
] | I want to get, given a character, its `ASCII` value.
For example, for the character `a`, I want to get `97`, and vice versa. | Use [`chr()`](http://docs.python.org/library/functions.html#chr) and [`ord()`](http://docs.python.org/library/functions.html#ord):
```
>>> chr(97)
'a'
>>> ord('a')
97
``` |
How can I convert a character to a integer in Python, and viceversa? | 704,152 | 160 | 2009-04-01T05:19:15Z | 704,183 | 7 | 2009-04-01T05:36:09Z | [
"python",
"integer",
"char",
"type-conversion"
] | I want to get, given a character, its `ASCII` value.
For example, for the character `a`, I want to get `97`, and vice versa. | The question has been answered but I think this reference is a good thing to keep note of. <http://docs.python.org/library/functions.html> |
python: finding a missing letter in the alphabet from a list - least lines of code | 704,526 | 2 | 2009-04-01T08:08:19Z | 704,576 | 10 | 2009-04-01T08:25:40Z | [
"python"
] | I'm trying to find the missing letter in the alphabet from the list with the least lines of code.
If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter.
If I know there are only one missing letter.
(This is not any type of interview questions. I actu... | Some questions:
* Are all the letters upper or lower case? (a/A)
* Is this the only alphabet you'll want to check?
* Why are you doing this so often?
Least lines of code:
```
# do this once, outside the loop
alphabet=set(string.ascii_lowercase)
# inside the loop, just 1 line:
missingletter=(alphabet-set(yourlist)).p... |
python: finding a missing letter in the alphabet from a list - least lines of code | 704,526 | 2 | 2009-04-01T08:08:19Z | 704,595 | 7 | 2009-04-01T08:32:13Z | [
"python"
] | I'm trying to find the missing letter in the alphabet from the list with the least lines of code.
If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter.
If I know there are only one missing letter.
(This is not any type of interview questions. I actu... | Using a list comprehension:
```
>>> import string
>>> sourcelist = 'abcdefghijklmnopqrstuvwx'
>>> [letter for letter in string.ascii_lowercase if letter not in sourcelist]
['y', 'z']
>>>
```
The [string](http://docs.python.org/library/string.html) module has some predefined constants that are useful.
```
>>> string.... |
python: finding a missing letter in the alphabet from a list - least lines of code | 704,526 | 2 | 2009-04-01T08:08:19Z | 704,686 | 7 | 2009-04-01T09:06:28Z | [
"python"
] | I'm trying to find the missing letter in the alphabet from the list with the least lines of code.
If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter.
If I know there are only one missing letter.
(This is not any type of interview questions. I actu... | In the too clever for it's own good category, and assuming there is exactly one missing letter in a lowercase alphabet:
```
print chr(2847 - sum(map(ord, theString)))
```
**[Edit]**
I've run some timings on the various solutions to see which is faster.
Mine turned out to be fairly slow in practice (slightly faster if... |
Does anyone know about workflow frameworks/libraries in Python? | 704,834 | 15 | 2009-04-01T09:54:00Z | 704,938 | 11 | 2009-04-01T10:31:10Z | [
"python",
"django",
"workflow"
] | I'm searching for a workflow library/framework for Python. I'm astonished that there I cannot find anything which is simple and not attached to Zope/Plone.
Does anyone know of an open-source, simple workflow library/framework. It's preferred to support Django, but not required. | Try [GoFlow](http://code.djangoproject.com/wiki/GoFlow), a workflow engine for Django. |
Python JSON decoding performance | 706,101 | 36 | 2009-04-01T15:39:31Z | 706,353 | 16 | 2009-04-01T16:30:29Z | [
"python",
"json",
"python-2.6"
] | I'm using the `json` module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and `json.loads()` is taking 20 seconds.
I thought the `json` module had some native code to speed up the decoding?
How do I check if this... | It may vary by platform, but the builtin json module is based on [simplejson](http://pypi.python.org/pypi/simplejson/), not including the C speedups. I've found simplejson to be as a fast as python-cjson anyway, so I prefer it since it obviously has the same interface as the builtin.
```
try:
import simplejson as ... |
Python JSON decoding performance | 706,101 | 36 | 2009-04-01T15:39:31Z | 5,821,091 | 21 | 2011-04-28T15:29:52Z | [
"python",
"json",
"python-2.6"
] | I'm using the `json` module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and `json.loads()` is taking 20 seconds.
I thought the `json` module had some native code to speed up the decoding?
How do I check if this... | The new [Yajl - Yet Another JSON Library](https://github.com/rtyler/py-yajl/) is very fast.
```
yajl serialize: 0.180 deserialize: 0.182 total: 0.362
simplejson serialize: 0.840 deserialize: 0.490 total: 1.331
stdlib json serialize: 2.812 deserialize: 8.725 total: 11.537
```
You can [compare the librari... |
Python JSON decoding performance | 706,101 | 36 | 2009-04-01T15:39:31Z | 14,513,180 | 11 | 2013-01-25T00:09:00Z | [
"python",
"json",
"python-2.6"
] | I'm using the `json` module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and `json.loads()` is taking 20 seconds.
I thought the `json` module had some native code to speed up the decoding?
How do I check if this... | I was parsing the same file 10x. File size was 1,856,944 bytes.
Python 2.6:
```
yajl serialize: 0.294 deserialize: 0.334 total: 0.627
cjson serialize: 0.494 deserialize: 0.276 total: 0.769
simplejson serialize: 0.554 deserialize: 0.268 total: 0.823
stdlib json serialize: 3.917 deserialize: 17.508... |
Python JSON decoding performance | 706,101 | 36 | 2009-04-01T15:39:31Z | 15,440,843 | 11 | 2013-03-15T19:41:37Z | [
"python",
"json",
"python-2.6"
] | I'm using the `json` module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and `json.loads()` is taking 20 seconds.
I thought the `json` module had some native code to speed up the decoding?
How do I check if this... | take a look UltraJSON <https://github.com/esnme/ultrajson>
here my test (code from: <https://gist.github.com/lightcatcher/1136415>)
platform: OS X 10.8.3 MBP 2.2 GHz Intel Core i7
JSON:
simplejson==3.1.0
python-cjson==1.0.5
jsonlib==1.6.1
ujson==1.30
yajl==0.3.5
```
JSON Benchmark
2.7.2 (default, Oct 11 2012, ... |
Complex Beautiful Soup query | 706,443 | 3 | 2009-04-01T16:51:24Z | 706,531 | 9 | 2009-04-01T17:15:12Z | [
"python",
"beautifulsoup"
] | Here is a snippet of an HTML file I'm exploring with Beautiful Soup.
```
<td width="50%">
<strong class="sans"><a href="http:/website">Site</a></strong> <br />
```
I would like to get the `<a href>` for any line which has the `<strong class="sans">` and which is inside a `<td width="50%">`.
Is it possible to que... | BeautifulSoup's search mechanisms accept a callable, which the docs appear to recommend for your case: "If you need to impose complex or interlocking restrictions on a tag's attributes, pass in a callable object for name,...". (ok... they're talking about attributes specifically, but the advice reflects an underlying s... |
Can you define aliases for imported modules in Python? | 706,595 | 59 | 2009-04-01T17:33:02Z | 706,601 | 88 | 2009-04-01T17:34:00Z | [
"python",
"module",
"alias",
"python-import"
] | In Python, is it possible to define an alias for an imported module?
For instance:
```
import a_ridiculously_long_module_name
```
...so that is has an alias of 'short\_name'. | ```
import a_ridiculously_long_module_name as short_name
```
also works for
```
import module.submodule.subsubmodule as short_name
``` |
Can you define aliases for imported modules in Python? | 706,595 | 59 | 2009-04-01T17:33:02Z | 706,602 | 22 | 2009-04-01T17:34:03Z | [
"python",
"module",
"alias",
"python-import"
] | In Python, is it possible to define an alias for an imported module?
For instance:
```
import a_ridiculously_long_module_name
```
...so that is has an alias of 'short\_name'. | [Check here](http://docs.python.org/reference/simple%5Fstmts.html#import)
```
import module as name
```
or
```
from relative_module import identifier as name
``` |
Can you define aliases for imported modules in Python? | 706,595 | 59 | 2009-04-01T17:33:02Z | 707,571 | 19 | 2009-04-01T22:22:14Z | [
"python",
"module",
"alias",
"python-import"
] | In Python, is it possible to define an alias for an imported module?
For instance:
```
import a_ridiculously_long_module_name
```
...so that is has an alias of 'short\_name'. | If you've done:
```
import long_module_name
```
you can also give it an alias by:
```
lmn = long_module_name
```
There's no reason to do it this way in code, but I sometimes find it useful in the interactive interpreter. |
How do I pass a method as a parameter in python | 706,721 | 31 | 2009-04-01T18:06:53Z | 706,735 | 52 | 2009-04-01T18:09:03Z | [
"python"
] | Is it possible to pass a method as a parameter to a method?
```
self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
``` | Yes it is, just use the name of the method, as you have written. Methods/functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.
FYI, there is no `c... |
How do I pass a method as a parameter in python | 706,721 | 31 | 2009-04-01T18:06:53Z | 706,743 | 10 | 2009-04-01T18:11:42Z | [
"python"
] | Is it possible to pass a method as a parameter to a method?
```
self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
``` | Yes it is possible. Just call it:
```
class Foo(object):
def method1(self):
pass
def method2(self, method):
return method()
foo = Foo()
foo.method2(foo.method1)
``` |
How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python? | 706,755 | 15 | 2009-04-01T18:14:27Z | 706,770 | 27 | 2009-04-01T18:18:08Z | [
"python",
"mysql"
] | I have a simple table in mysql with the following fields:
* id -- Primary key, int, autoincrement
* name -- varchar(50)
* description -- varchar(256)
Using MySQLdb, a python module, I want to insert a name and description into the table, and get back the id.
In pseudocode:
```
db = MySQLdb.connection(...)
queryStri... | I think it might be
```
newID = db.insert_id()
```
---
**Edit by Original Poster**
Turns out, in the version of MySQLdb that I am using (1.2.2)
You would do the following:
```
conn = MySQLdb(host...)
c = conn.cursor()
c.execute("INSERT INTO...")
newID = c.lastrowid
```
I am leaving this as the correct answer, si... |
What is the best way to pass a method (with parameters) to another method in python | 706,813 | 2 | 2009-04-01T18:31:10Z | 706,864 | 11 | 2009-04-01T18:43:55Z | [
"python"
] | What's the best way to pass a method and a method parameter to another method?
Is there a better way to do the following?
```
def method1(name)
return 'Hello ' + name
def method2(methodToCall, methodToCallParams, question):
greetings = methodToCall(methodToCallParams)
return greetings + ', ' + question
... | If you want to package the invocation up in one hit, you can use the functools module:
```
from functools import partial
def some_function(param_one, param_two):
print "Param One: %s" % param_one
print "Param Two: %s" % param_two
def calling_function(target):
target()
calling_function(partial(some_funct... |
How to call an external program in python and retrieve the output and return code? | 706,989 | 24 | 2009-04-01T19:25:10Z | 707,001 | 42 | 2009-04-01T19:28:30Z | [
"python",
"return-value",
"external-process"
] | How can I call an external program with a python script and retrieve the output and return code? | Look at the [**subprocess**](http://docs.python.org/library/subprocess.html) module: a simple example follows...
```
from subprocess import Popen, PIPE
process = Popen(["ls", "-la", "."], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
``` |
How to call an external program in python and retrieve the output and return code? | 706,989 | 24 | 2009-04-01T19:25:10Z | 15,190,186 | 12 | 2013-03-03T20:00:32Z | [
"python",
"return-value",
"external-process"
] | How can I call an external program with a python script and retrieve the output and return code? | Following Ambroz Bizjak's previous comment, here is a solution that worked for me:
```
import shlex
from subprocess import Popen, PIPE
cmd = "..."
process = Popen(shlex.split(cmd), stdout=PIPE)
process.communicate()
exit_code = process.wait()
``` |
Is there a Perl equivalent to Python's `if __name__ == '__main__'`? | 707,022 | 28 | 2009-04-01T19:35:15Z | 707,034 | 39 | 2009-04-01T19:39:55Z | [
"python",
"perl",
"executable"
] | Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct:
```
if __name__ == '__main__':
# This file is being executed.
raise NotImplementedError
```
I can hack something together using `FindBin` and `__FILE__`, but I'm hoping ... | ```
unless (caller) {
print "This is the script being executed\n";
}
```
See [caller](http://perldoc.perl.org/functions/caller.html). It returns `undef` in the main script. Note that that doesn't work inside a subroutine, only in top-level code. |
Is there a Perl equivalent to Python's `if __name__ == '__main__'`? | 707,022 | 28 | 2009-04-01T19:35:15Z | 707,045 | 9 | 2009-04-01T19:43:18Z | [
"python",
"perl",
"executable"
] | Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct:
```
if __name__ == '__main__':
# This file is being executed.
raise NotImplementedError
```
I can hack something together using `FindBin` and `__FILE__`, but I'm hoping ... | See the "Subclasses for Applications (Chapter 18)" portion of [brian d foy](http://stackoverflow.com/users/8817/brian-d-foy)'s article [Five Ways to Improve Your Perl Programming](http://www.onlamp.com/pub/a/onlamp/2007/04/12/five-ways-to-improve-your-perl-programming.html). |
Python source header comment | 707,127 | 8 | 2009-04-01T20:05:21Z | 707,146 | 14 | 2009-04-01T20:10:09Z | [
"python",
"unix",
"shebang"
] | What is the line
```
#!/usr/bin/env python
```
in the first line of a python script used for? | This is called a [shebang](http://en.wikipedia.org/wiki/Shebang%5F%28Unix%29) line:
> In computing, a shebang (also called a hashbang, hashpling, or pound bang) refers to the characters "#!" when they are the first two characters in a text file. Unix-like operating systems take the presence of these two characters as ... |
Python source header comment | 707,127 | 8 | 2009-04-01T20:05:21Z | 707,166 | 24 | 2009-04-01T20:14:20Z | [
"python",
"unix",
"shebang"
] | What is the line
```
#!/usr/bin/env python
```
in the first line of a python script used for? | In UNIX and Linux this tells which binary to use as an interpreter (see also [Wiki page](http://en.wikipedia.org/wiki/Shebang%5F%28Unix%29)).
For example shell script is interpreted by `/bin/sh`.
```
#!/bin/sh
```
Now with python it's a bit tricky, because you can't assume where the binary is installed, nor which you... |
Create a standalone windows exe which does not require pythonXX.dll | 707,242 | 16 | 2009-04-01T20:38:16Z | 707,274 | 17 | 2009-04-01T20:48:40Z | [
"python",
"windows",
"py2exe"
] | is there a way to create a standalone .exe from a python script.
Executables generated with py2exe can run only with pythonXX.dll.
I'd like to obtain a fully standalone .exe which does not require to install the python runtime library.
It looks like a linking problem but using static library instead the dynamic one and... | You can do this in the latest version of py2exe...
Just add something like the code below in your `setup.py` file (key part is 'bundle\_files': 1).
To include your TkInter package in the install, use the 'includes' key.
```
distutils.core.setup(
windows=[
{'script': 'yourmodule.py',
... |
In Python how can I access "static" class variables within class methods | 707,380 | 61 | 2009-04-01T21:23:39Z | 707,389 | 66 | 2009-04-01T21:25:28Z | [
"python"
] | If I have the following python code:
```
class Foo(object):
bar = 1
def bah(self):
print bar
f = Foo()
f.bah()
```
It complains
```
NameError: global name 'bar' is not defined
```
How can I access class/static variable 'bar' within method 'bah'? | Instead of `bar` use `self.bar` or `Foo.bar`. Assigning to `Foo.bar` will create a static variable, and assigning to `self.bar` will create an instance variable. |
In Python how can I access "static" class variables within class methods | 707,380 | 61 | 2009-04-01T21:23:39Z | 708,381 | 8 | 2009-04-02T05:13:03Z | [
"python"
] | If I have the following python code:
```
class Foo(object):
bar = 1
def bah(self):
print bar
f = Foo()
f.bah()
```
It complains
```
NameError: global name 'bar' is not defined
```
How can I access class/static variable 'bar' within method 'bah'? | As with all good examples, you've simplified what you're actually trying to do. This is good, but it is worth noting that python has a *lot* of flexibility when it comes to class versus instance variables. The same can be said of methods. For a good list of possibilities, I recommend reading [Michael Fötsch' new-style... |
In Python how can I access "static" class variables within class methods | 707,380 | 61 | 2009-04-01T21:23:39Z | 709,024 | 46 | 2009-04-02T09:42:57Z | [
"python"
] | If I have the following python code:
```
class Foo(object):
bar = 1
def bah(self):
print bar
f = Foo()
f.bah()
```
It complains
```
NameError: global name 'bar' is not defined
```
How can I access class/static variable 'bar' within method 'bah'? | Define class method:
```
class Foo(object):
bar = 1
@classmethod
def bah(cls):
print cls.bar
```
Now if `bah()` has to be instance method (i.e. have access to self), you can still directly access the class variable.
```
class Foo(object):
bar = 1
def bah(self):
print self.... |
questions re: current state of GUI programming with Python | 707,491 | 20 | 2009-04-01T21:53:15Z | 707,543 | 12 | 2009-04-01T22:09:32Z | [
"python",
"user-interface"
] | I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I lik... | seems your complains are about wxPython, not about Python itself. try pyQt (or is it qtPython?)
but, both wxPython and pyQt are just Python bindings to a C / C++ (respectively) library, it's just as (conceptually) low level as the originals.
but, Qt is far superior to wx |
How to compare type of an object in Python? | 707,674 | 85 | 2009-04-01T23:03:05Z | 707,685 | 106 | 2009-04-01T23:07:02Z | [
"python",
"types",
"compare"
] | Basically I want to do this:
```
obj = 'str'
type ( obj ) == string
```
I tried:
```
type ( obj ) == type ( string )
```
and it didn't work.
Also, what about the other types? For example, I couldn't replicate `NoneType`. | ```
isinstance()
```
In your case, `isinstance("this is a string", str)` will return `True`.
You may also want to read this: <http://www.canonical.org/~kragen/isinstance/> |
How to compare type of an object in Python? | 707,674 | 85 | 2009-04-01T23:03:05Z | 707,716 | 20 | 2009-04-01T23:19:36Z | [
"python",
"types",
"compare"
] | Basically I want to do this:
```
obj = 'str'
type ( obj ) == string
```
I tried:
```
type ( obj ) == type ( string )
```
and it didn't work.
Also, what about the other types? For example, I couldn't replicate `NoneType`. | For other types, check out the [types](http://docs.python.org/library/types.html) module:
```
>>> import types
>>> x = "mystring"
>>> isinstance(x, types.StringType)
True
>>> x = 5
>>> isinstance(x, types.IntType)
True
>>> x = None
>>> isinstance(x, types.NoneType)
True
```
P.S. Typechecking is a bad idea. |
How to compare type of an object in Python? | 707,674 | 85 | 2009-04-01T23:03:05Z | 707,732 | 30 | 2009-04-01T23:26:47Z | [
"python",
"types",
"compare"
] | Basically I want to do this:
```
obj = 'str'
type ( obj ) == string
```
I tried:
```
type ( obj ) == type ( string )
```
and it didn't work.
Also, what about the other types? For example, I couldn't replicate `NoneType`. | `isinstance` works:
```
if isinstance(obj, MyClass): do_foo(obj)
```
**but**, keep in mind: if it looks like a duck, and if it sounds like a duck, it is a duck.
EDIT: For the None type, you can simply do:
```
if obj is None: obj = MyClass()
``` |
How to compare type of an object in Python? | 707,674 | 85 | 2009-04-01T23:03:05Z | 707,812 | 8 | 2009-04-02T00:01:28Z | [
"python",
"types",
"compare"
] | Basically I want to do this:
```
obj = 'str'
type ( obj ) == string
```
I tried:
```
type ( obj ) == type ( string )
```
and it didn't work.
Also, what about the other types? For example, I couldn't replicate `NoneType`. | You can always use the `type(x) == type(y)` trick, where `y` is something with known type.
```
# check if x is a regular string
type(x) == type('')
# check if x is an integer
type(x) == type(1)
# check if x is a NoneType
type(x) == type(None)
```
Often there are better ways of doing that, particularly with any recent... |
How to compare type of an object in Python? | 707,674 | 85 | 2009-04-01T23:03:05Z | 707,878 | 26 | 2009-04-02T00:34:18Z | [
"python",
"types",
"compare"
] | Basically I want to do this:
```
obj = 'str'
type ( obj ) == string
```
I tried:
```
type ( obj ) == type ( string )
```
and it didn't work.
Also, what about the other types? For example, I couldn't replicate `NoneType`. | First, avoid all type comparisons. They're very, very rarely necessary. Sometimes, they help to check parameter types in a function -- even that's rare. Wrong type data will raise an exception, and that's all you'll ever need.
All of the basic conversion functions will map as equal to the type function.
```
type(9) i... |
Which Python Bayesian text classification modules are similar to dbacl? | 707,879 | 11 | 2009-04-02T00:34:26Z | 707,901 | 9 | 2009-04-02T00:49:04Z | [
"python",
"text",
"classification",
"bayesian"
] | A quick Google search reveals that there are a good number of Bayesian classifiers implemented as Python modules. If I want wrapped, high-level functionality similar to [dbacl](http://dbacl.sourceforge.net/), which of those modules is right for me?
Training
```
% dbacl -l one sample1.txt
% dbacl -l two sample2.txt
``... | I think you'll find the [nltk](http://www.nltk.org) helpful. Specifically, the [classify module](http://nltk.googlecode.com/svn/trunk/doc/api/nltk.classify-module.html). |
Python comments: # vs strings | 708,649 | 19 | 2009-04-02T07:24:59Z | 708,674 | 53 | 2009-04-02T07:36:08Z | [
"python"
] | I have a question regarding the "standard" way to put comments inside Python source code:
```
def func():
"Func doc"
... <code>
'TODO: fix this'
#badFunc()
... <more code>
def func():
"Func doc"
... <code>
#TODO: fix this
#badFunc()
... <more code>
```
I prefer to write genera... | Don't misuse strings (no-op statements) as comments. Docstrings, e.g. the first string in a module, class or function, are special and definitely recommended.
Note that **docstrings are documentation**, and documentation and comments are two different things!
* Documentation is important to understand *what* the code... |
Why do languages like Java use hierarchical package names, while Python does not? | 709,036 | 13 | 2009-04-02T09:45:13Z | 709,100 | 10 | 2009-04-02T10:02:10Z | [
"java",
"python",
"packages"
] | I haven't done enterprise work in Java, but I often see the [reverse-domain-name package naming convention](http://stackoverflow.com/questions/420945/java-package-name-convention-failure). For example, for a Stack Overflow Java package you'd put your code underneath package `com.stackoverflow`.
I just ran across a Pyt... | It's a great way of preventing name collisions, and takes full advantage of the existing domain name system, so it requires no additional bureaucracy or registration. It is simple and brilliant.
By reversing the domain name it also gives it a hierarchical structure, which is handy. So you can have sub-packages on the ... |
Why do languages like Java use hierarchical package names, while Python does not? | 709,036 | 13 | 2009-04-02T09:45:13Z | 709,150 | 12 | 2009-04-02T10:18:03Z | [
"java",
"python",
"packages"
] | I haven't done enterprise work in Java, but I often see the [reverse-domain-name package naming convention](http://stackoverflow.com/questions/420945/java-package-name-convention-failure). For example, for a Stack Overflow Java package you'd put your code underneath package `com.stackoverflow`.
I just ran across a Pyt... | "What are the reasons you'd prefer one over the other?"
Python's style is simpler. Java's style allows same-name products from different organizations.
"Do those reasons apply across the languages?"
Yes. You can easily have top level Python packages named "com", "org", "mil", "net", "edu" and "gov" and put your pack... |
Why do languages like Java use hierarchical package names, while Python does not? | 709,036 | 13 | 2009-04-02T09:45:13Z | 709,188 | 18 | 2009-04-02T10:32:12Z | [
"java",
"python",
"packages"
] | I haven't done enterprise work in Java, but I often see the [reverse-domain-name package naming convention](http://stackoverflow.com/questions/420945/java-package-name-convention-failure). For example, for a Stack Overflow Java package you'd put your code underneath package `com.stackoverflow`.
I just ran across a Pyt... | Python doesn't do this because you end up with a problem -- who owns the "com" package that almost everything else is a subpackage of? Python's method of establishing package heirarchy (through the filesystem heirarchy) does not play well with this convention at all. Java can get away with it because package heirarchy ... |
Why do languages like Java use hierarchical package names, while Python does not? | 709,036 | 13 | 2009-04-02T09:45:13Z | 711,380 | 12 | 2009-04-02T20:05:02Z | [
"java",
"python",
"packages"
] | I haven't done enterprise work in Java, but I often see the [reverse-domain-name package naming convention](http://stackoverflow.com/questions/420945/java-package-name-convention-failure). For example, for a Stack Overflow Java package you'd put your code underneath package `com.stackoverflow`.
I just ran across a Pyt... | If Guido himself announced that the reverse domain convention ought to be followed, it wouldn't be adopted, unless there were significant changes to the implementation of `import` in python.
Consider: python searches an import path at run-time with a fail-fast algorithm; java searches a path with an exhaustive algorit... |
Why do languages like Java use hierarchical package names, while Python does not? | 709,036 | 13 | 2009-04-02T09:45:13Z | 711,452 | 10 | 2009-04-02T20:24:06Z | [
"java",
"python",
"packages"
] | I haven't done enterprise work in Java, but I often see the [reverse-domain-name package naming convention](http://stackoverflow.com/questions/420945/java-package-name-convention-failure). For example, for a Stack Overflow Java package you'd put your code underneath package `com.stackoverflow`.
I just ran across a Pyt... | Somewhere on Joel on Software, Joel has a comparison between two methods of growing a company: the Ben & Jerry's method, which starts small and grows organically, and the Amazon method of raising a whole lot of money and staking very wide claims from the start.
When Sun introduced Java, it was with fanfare and hype. J... |
How to tell the difference between an iterator and an iterable? | 709,084 | 10 | 2009-04-02T09:56:55Z | 709,132 | 14 | 2009-04-02T10:11:29Z | [
"python",
"iterator"
] | In Python the interface of an iterable is a subset of the [iterator interface](http://docs.python.org/library/stdtypes.html#iterator-types). This has the advantage that in many cases they can be treated in the same way. However, there is an important semantic difference between the two, since for an iterable `__iter__`... | ```
'iterator' if obj is iter(obj) else 'iterable'
``` |
What is the best way to toggle python prints? | 709,385 | 8 | 2009-04-02T11:49:09Z | 709,389 | 12 | 2009-04-02T11:50:52Z | [
"python",
"printing"
] | I'm running Python 2.4 in a game engine and I want to be able to turn off all prints if needed. For example I'd like to have the prints on for a debug build, and then turned off for a release build.
It's also imperative that it's as transparent as possible.
My solution to this in the C code of the engine is having the... | yes, you can assign `sys.stdout` to whatever you want. Create a little class with a `write` method that does nothing:
```
class DevNull(object):
def write(self, arg):
pass
import sys
sys.stdout = DevNull()
print "this goes to nirvana!"
```
With the same technique you can also have your prints logged ... |
What is the best way to toggle python prints? | 709,385 | 8 | 2009-04-02T11:49:09Z | 709,417 | 8 | 2009-04-02T12:00:43Z | [
"python",
"printing"
] | I'm running Python 2.4 in a game engine and I want to be able to turn off all prints if needed. For example I'd like to have the prints on for a debug build, and then turned off for a release build.
It's also imperative that it's as transparent as possible.
My solution to this in the C code of the engine is having the... | The [logging module](http://docs.python.org/library/logging.html) is the "best" way.. although I quite often just use something simple like..
```
class MyLogger:
def _displayMessage(self, message, level = None):
# This can be modified easily
if level is not None:
print "[%s] %s" % (leve... |
What is the best way to toggle python prints? | 709,385 | 8 | 2009-04-02T11:49:09Z | 709,897 | 10 | 2009-04-02T14:17:17Z | [
"python",
"printing"
] | I'm running Python 2.4 in a game engine and I want to be able to turn off all prints if needed. For example I'd like to have the prints on for a debug build, and then turned off for a release build.
It's also imperative that it's as transparent as possible.
My solution to this in the C code of the engine is having the... | I know an answer has already been marked as correct, but Python has a debug flag that provides a cleaner solution. You use it like this:
```
if __debug__:
print "whoa"
```
If you invoke Python with -O or -OO (as you normally would for a release build), `__debug__` is set to `False`. What's even better is that `__... |
What's a more elegant rephrasing of this cropping algorithm? (in Python) | 709,388 | 4 | 2009-04-02T11:50:49Z | 709,442 | 9 | 2009-04-02T12:06:23Z | [
"image",
"python-imaging-library",
"python",
"crop"
] | I want to crop a thumbnail image in my Django application, so that I get a quadratic image that shows the center of the image. This is not very hard, I agree.
I have already written some code that does exactly this, but somehow it lacks a certain ... elegance. I don't want to play code golf, but there must be a way to... | I think this should do.
```
size = min(image.Size)
originX = image.Size[0] / 2 - size / 2
originY = image.Size[1] / 2 - size / 2
cropBox = (originX, originY, originX + size, originY + size)
``` |
Import an existing python project to XCode | 709,397 | 6 | 2009-04-02T11:54:59Z | 710,629 | 7 | 2009-04-02T16:57:19Z | [
"python",
"xcode",
"osx"
] | I've got a python project I've been making in terminal with vim etc.. I've read that XCode supports Python development at that it supports SVN (which I am using) but I can't find documentation on how to start a new XCode project from an existing code repository.
Other developers are working on the project not using XC... | I don't think it's worth using Xcode for a pure python project. Although the Xcode editor does syntax-highlight Python code, Xcode does not give you any other benefit for writing a pure-python app. On OS X, I would recommend [TextMate](http://macromates.com/) as a text editor or Eclipse with [PyDev](http://pydev.source... |
python code convention using pylint | 709,490 | 9 | 2009-04-02T12:21:31Z | 709,515 | 9 | 2009-04-02T12:29:00Z | [
"python",
"conventions",
"pylint"
] | I'm trying out pylint to check my source code for conventions. Somehow some variable names are matched with the regex for constants (`const-rgx`) instead of the variable name regex (`variable-rgx`). How to match the variable name with `variable-rgx`? Or should I extend `const-rgx` with my `variable-rgx` stuff?
e.g.
... | I just disable that warning because I don't follow those naming conventions.
To do that, add this line to the top of you module:
```
# pylint: disable-msg=C0103
```
If you want to disable that globally, then add it to the pylint command:
```
python lint.py --disable-msg=C0103 ...
``` |
python code convention using pylint | 709,490 | 9 | 2009-04-02T12:21:31Z | 709,709 | 24 | 2009-04-02T13:27:59Z | [
"python",
"conventions",
"pylint"
] | I'm trying out pylint to check my source code for conventions. Somehow some variable names are matched with the regex for constants (`const-rgx`) instead of the variable name regex (`variable-rgx`). How to match the variable name with `variable-rgx`? Or should I extend `const-rgx` with my `variable-rgx` stuff?
e.g.
... | > Somehow some variable names are matched with the regex for constants (const-rgx) instead of the variable name regex (variable-rgx).
Are those variables declared on module level? Maybe that's why they are treated as constants (at least that's how they should be declared, according to PEP-8). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.