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 |
|---|---|---|---|---|---|---|---|---|---|
Does Python re module support word boundaries (\b)? | 3,995,034 | 37 | 2010-10-22T08:21:37Z | 3,995,242 | 35 | 2010-10-22T08:49:32Z | [
"python",
"regex"
] | While trying to learn a little more about regular expressions, a tutorial suggested that you can use the \b to match a word boundary. However, the following snippet in the Python interpreter does not work as expected:
```
>>> x = 'one two three'
>>> y = re.search("\btwo\b", x)
```
y should have been a match object if... | This will work: `re.search(r"\btwo\b", x)`
When you write `"\b"` in Python, it is a single character: `"\x08"`. Either escape the backslash like this:
```
"\\b"
```
or write a raw string like this:
```
r"\b"
``` |
Defining constants in python class, is self really needed? | 3,995,546 | 22 | 2010-10-22T09:33:54Z | 3,995,811 | 32 | 2010-10-22T10:09:18Z | [
"python",
"constants",
"visibility"
] | I want to define a set of constants in a class like:
```
class Foo(object):
(NONEXISTING,VAGUE,CONFIRMED) = (0,1,2)
def __init__(self):
self.status = VAGUE
```
However, I get
```
NameError: global name 'VAGUE' is not defined
```
Is there a way of defining these constants to be visiable inside the class... | When you assign to names in the class body, you're creating attributes of the class. You can't refer to them without referring to the class either directly or indirectly. You can use `Foo.VAGUE` as the other answers say, or you can use `self.VAGUE`. You do not have to *assign* to attributes of `self`.
Usually, using `... |
Generate random integers between 0 and 9 | 3,996,904 | 430 | 2010-10-22T12:48:29Z | 3,996,919 | 50 | 2010-10-22T12:49:55Z | [
"python",
"random"
] | How can I generate random **integer** numbers **between 0 and 9** (inclusive) in Python?
i.e. 0 1 2 3 4 5 6 7 8 9 | Try this:
```
from random import randrange, uniform
# randrange gives you an integral value
irand = randrange(0, 10)
# uniform gives you a floating-point value
frand = uniform(0, 10)
``` |
Generate random integers between 0 and 9 | 3,996,904 | 430 | 2010-10-22T12:48:29Z | 3,996,930 | 697 | 2010-10-22T12:51:31Z | [
"python",
"random"
] | How can I generate random **integer** numbers **between 0 and 9** (inclusive) in Python?
i.e. 0 1 2 3 4 5 6 7 8 9 | Try:
```
from random import randint
print(randint(0,9))
```
More info: <https://docs.python.org/3.1/library/random.html#random.randint> |
Generate random integers between 0 and 9 | 3,996,904 | 430 | 2010-10-22T12:48:29Z | 16,376,904 | 155 | 2013-05-04T17:13:28Z | [
"python",
"random"
] | How can I generate random **integer** numbers **between 0 and 9** (inclusive) in Python?
i.e. 0 1 2 3 4 5 6 7 8 9 | ```
import random
print(random.randint(0,9))
```
---
```
random.randint(a, b)
```
Return a random integer N such that a <= N <= b.
Docs: <https://docs.python.org/3.1/library/random.html#random.randint> |
Generate random integers between 0 and 9 | 3,996,904 | 430 | 2010-10-22T12:48:29Z | 20,224,166 | 22 | 2013-11-26T17:39:09Z | [
"python",
"random"
] | How can I generate random **integer** numbers **between 0 and 9** (inclusive) in Python?
i.e. 0 1 2 3 4 5 6 7 8 9 | ```
from random import randint
x=[randint(0,9) for p in range(0,9)]
```
Generates 10 pseudo random integers in range 0 to 9 inclusive. |
Generate random integers between 0 and 9 | 3,996,904 | 430 | 2010-10-22T12:48:29Z | 28,785,907 | 12 | 2015-02-28T19:28:55Z | [
"python",
"random"
] | How can I generate random **integer** numbers **between 0 and 9** (inclusive) in Python?
i.e. 0 1 2 3 4 5 6 7 8 9 | **You must import the `random` module**
The program will look something like this
```
import random
random.randrange(10)
``` |
Python urllib urlencode problem with æøå | 3,996,974 | 5 | 2010-10-22T12:55:58Z | 3,997,027 | 9 | 2010-10-22T13:02:40Z | [
"python",
"urlencode",
"urllib"
] | How can I urlencode a string with special chars æøå?
ex.
```
urllib.urlencode('http://www.test.com/q=testæøå')
```
I get this error :(..
> not a valid non-string sequence or
> mapping object | You should pass dictionary to urlencode, not a string. See the correct example below:
```
from urllib import urlencode
print 'http://www.test.com/?' + urlencode({'q': 'testæøå'})
``` |
Python urllib urlencode problem with æøå | 3,996,974 | 5 | 2010-10-22T12:55:58Z | 3,997,031 | 26 | 2010-10-22T13:03:09Z | [
"python",
"urlencode",
"urllib"
] | How can I urlencode a string with special chars æøå?
ex.
```
urllib.urlencode('http://www.test.com/q=testæøå')
```
I get this error :(..
> not a valid non-string sequence or
> mapping object | `urlencode` is intended to take a dictionary, for example:
```
>>> q= u'\xe6\xf8\xe5' # u'æøå'
>>> params= {'q': q.encode('utf-8')}
>>> 'http://www.test.com/?'+urllib.urlencode(params)
'http://www.test.com/?q=%C3%A6%C3%B8%C3%A5'
```
If you just want to URL-encode a single string, the function you're looking for is... |
Python generator, non-swallowing exception in 'coroutine' | 3,997,496 | 12 | 2010-10-22T13:55:56Z | 3,997,538 | 14 | 2010-10-22T14:02:08Z | [
"python",
"exception",
"generator"
] | I recently came across some surprising behaviour in Python generators:
```
class YieldOne:
def __iter__(self):
try:
yield 1
except:
print '*Excepted Successfully*'
# raise
for i in YieldOne():
raise Exception('test exception')
```
Which gives the output:
```
*Excepted Successfully*
Tra... | Your code does not do what you think it does. You cannot raise Exceptions in a coroutine like this. What you do instead is catching the [`GeneratorExit`](http://docs.python.org/library/exceptions.html#exceptions.GeneratorExit) exception. See what happens when you use a different Exception:
```
class YieldOne:
def __... |
Python: Replace with regex | 3,997,525 | 45 | 2010-10-22T14:00:29Z | 3,997,562 | 79 | 2010-10-22T14:04:57Z | [
"python",
"regex"
] | I need to replace part of a string. I was looking through the Python documentation and found re.sub.
```
import re
s = '<textarea id="Foo"></textarea>'
output = re.sub(r'<textarea.*>(.*)</textarea>', 'Bar', s)
print output
>>>'Bar'
```
I was expecting this to print `'<textarea id="Foo">Bar</textarea>'` and not 'bar'... | Instead of capturing the part you want to *replace* you can capture the parts you want to *keep* and then refer to them using a reference `\1` to include them in the substituted string.
Try this instead:
```
output = re.sub(r'(<textarea.*>).*(</textarea>)', r'\1Bar\2', s)
```
Also, assuming this is HTML you should c... |
what would be a quick way to read a property file in python? | 3,997,777 | 8 | 2010-10-22T14:26:06Z | 3,997,881 | 7 | 2010-10-22T14:39:06Z | [
"python",
"configuration-files"
] | I have a file with the format
```
VarName=Value
.
.
```
I want to read it into a hash such that `H("VarName")` will return the value.
What would be a quick way? (read a set of strings, split all of them where the equality sign is, and then put it into a hash?
I am working with python. | Maybe [ConfigParser](http://docs.python.org/library/configparser.html) can help you. |
what would be a quick way to read a property file in python? | 3,997,777 | 8 | 2010-10-22T14:26:06Z | 3,998,395 | 18 | 2010-10-22T15:31:38Z | [
"python",
"configuration-files"
] | I have a file with the format
```
VarName=Value
.
.
```
I want to read it into a hash such that `H("VarName")` will return the value.
What would be a quick way? (read a set of strings, split all of them where the equality sign is, and then put it into a hash?
I am working with python. | The oneliner answer:
```
H = dict(line.strip().split('=') for line in open('filename.txt'))
```
(optionally use `.split()` with `maxsplit=1` if the values could also contain the "=" character) |
How do I limit a file size when writing to files in python | 3,999,007 | 10 | 2010-10-22T16:41:13Z | 3,999,085 | 9 | 2010-10-22T16:50:43Z | [
"python",
"file-io"
] | I am using the output streams from the io module and writing to files. I want to be able to detect when I have written 1G of data to a file and then start writing to a second file. I can't seem to figure out how to determine how much data I have written to the file.
Is there something easy built in to io? Or might I h... | See the Python documentation for [File Objects](http://docs.python.org/library/stdtypes.html#file-objects), specifically [tell](http://docs.python.org/library/stdtypes.html#file.tell)().
Example:
```
>>> f=open('test.txt','w')
>>> f.write(10*'a')
>>> f.tell()
10L
>>> f.write(100*'a')
>>> f.tell()
110L
``` |
How do I limit a file size when writing to files in python | 3,999,007 | 10 | 2010-10-22T16:41:13Z | 3,999,638 | 14 | 2010-10-22T18:05:04Z | [
"python",
"file-io"
] | I am using the output streams from the io module and writing to files. I want to be able to detect when I have written 1G of data to a file and then start writing to a second file. I can't seem to figure out how to determine how much data I have written to the file.
Is there something easy built in to io? Or might I h... | if you are using this file for a logging purpose i suggest using the [RotatingFileHandler](http://docs.python.org/library/logging.handlers.html#rotatingfilehandler) in logging module like this:
```
import logging
import logging.handlers
file_name = 'test.log'
test_logger = logging.getLogger('Test')
handler = logging... |
Linux: Pipe into Python (ncurses) script, stdin and termios | 3,999,114 | 4 | 2010-10-22T16:54:21Z | 4,000,997 | 7 | 2010-10-22T21:10:28Z | [
"python",
"linux",
"pipe",
"ncurses",
"termios"
] | Apparently this is almost a duplicate of "[Bad pipe filedescriptor when reading from stdin in python - Stack Overflow](http://stackoverflow.com/questions/1057638/bad-pipe-filedescriptor-when-reading-from-stdin-in-python)"; however, I believe this case is slightly more complicated (*and it is not Windows specific, as th... | > The problem is that whenever I try the actual piping, that seems to mess up stdin, and the curses window never shows.
> [...snip...]
> As far as I can see, the issue is: - whenever we pipe strings into the Python script, the Python script loses the reference to the terminal as stdin, and notices that the replaced std... |
Which Python IDE can run my script line-by-line? | 3,999,829 | 20 | 2010-10-22T18:31:39Z | 3,999,918 | 7 | 2010-10-22T18:43:40Z | [
"python",
"ide"
] | I wouldn't call myself programmer, but I've started learning Python recently and really enjoy it.
I mainly use it for small tasks so far - scripting, text processing, KML generation and ArcGIS.
From my experience with R (working with excellent Notepad++ and [NppToR](http://sourceforge.net/projects/npptor/) combo) I u... | The only one I've had success with is [Eclipse](http://eclipse.org) with [Pydev](http://pydev.org) |
Which Python IDE can run my script line-by-line? | 3,999,829 | 20 | 2010-10-22T18:31:39Z | 4,001,138 | 9 | 2010-10-22T21:36:09Z | [
"python",
"ide"
] | I wouldn't call myself programmer, but I've started learning Python recently and really enjoy it.
I mainly use it for small tasks so far - scripting, text processing, KML generation and ArcGIS.
From my experience with R (working with excellent Notepad++ and [NppToR](http://sourceforge.net/projects/npptor/) combo) I u... | If you like R's layout. I highly recommend trying out [Spyder](http://packages.python.org/spyder/). If you are using windows, try out Python(x,y). It is a package with a few different editors and a lot of common extra modules like scipy and numpy. |
Python list help | 4,000,345 | 2 | 2010-10-22T19:37:59Z | 4,000,367 | 8 | 2010-10-22T19:40:49Z | [
"python",
"list"
] | simple Python question:
Example list: `A = [1,2,3,4,5]`
I need to generate another list B which is a shallow copy of list A such that B is a new list containing the same elements in the same order (so that I can substitute one of B's elements w/o affecting A). How can I do this?
---
clarification: I want to do some... | That would be a deep copy, not a shallow one.
Lists copy shallow by default. That's why there's a `deepcopy` command in the [copy module](http://docs.python.org/library/copy.html).
`B = copy.deepcopy(A)`
Optionally, `B = A[:]` will do. But keep deepcopy in mind for future. More complex data types can benefit from it... |
Sum one row of a NumPy array | 4,001,067 | 6 | 2010-10-22T21:23:15Z | 4,001,097 | 18 | 2010-10-22T21:28:18Z | [
"python",
"arrays",
"performance",
"numpy"
] | I'd like to sum one particular row of a large NumPy array. I know the function `array.max()` will give the maximum across the whole array, and `array.max(1)` will give me the maximum across each of the rows as an array. However, I'd like to get the maximum in a certain row (for example, row 7, or row 29). I have a larg... | You can easily access a row of a two-dimensional array using the indexing operator. The row itself is an array, a view of a part of the original array, and exposes all array methods, including `sum()` and `max()`. Therefore you can easily get the maximum per row like this:
```
x = arr[7].max() # Maximum in row 7
y =... |
can't 'import time' in python, get 'AttributeError: struct_time' How to solve? | 4,001,211 | 4 | 2010-10-22T21:49:04Z | 4,001,238 | 8 | 2010-10-22T21:52:18Z | [
"python",
"time",
"import"
] | Running python on Snow Leopard, and I can't import the 'time' module. Works in ipython. Don't have any .pythonrc files being loaded. Scripts that 'import time' using the same interpreter run fine. Have no idea how to troubleshoot this. Anyone have an idea?
```
[wiggles@bananas ~]$ python2.6
Python 2.6.6 (r266:84292, S... | Look for a file called time.py. It looks like Python is importing that, instead of the one from the standard library:
```
File "time.py", line 4, in <module>
```
The solution is to rename the file something other than "time.py".
By the way, you can find the path to the offending file by opening a Python REPL and t... |
Change how Python Cmd Module handles autocompletion | 4,001,708 | 7 | 2010-10-22T23:43:40Z | 4,003,719 | 8 | 2010-10-23T11:21:40Z | [
"python",
"command-line",
"autocomplete"
] | I have a Cmd console set up to auto-complete card names for a Magic: the Gathering collection management system.
It uses the text parameter to query the database for cards, and uses the results to auto-complete/suggest cards.
However, these cards names have multiple words, and Cmd runs auto-completion from the *last*... | It shouldn't need to be overly complicated. Something like the following:
```
import cmd
completions = [
'Mage Slayer (Alara Reborn)',
'Magefire Wings (Alara Reborn)',
'Sages of the Anima (Alara Reborn)',
'Sanctum Plowbeast (Alara Reborn)',
'Sangrite Backlash (Alara Reborn)',
'Sanity Gnawers (... |
How come when I use the tComment VIM plugin in a .ini file it adds/removes semi-colons instead of hashes as comment? | 4,002,018 | 2 | 2010-10-23T01:33:49Z | 4,002,291 | 8 | 2010-10-23T03:14:36Z | [
"python",
"vim",
"comments",
"pylons",
"ini"
] | I am using gVIM and the tComment plug-in during editing the **development.ini** file in a Pylons/Python project. The default **development.ini** file has lines commented out using the hash **#** symbol which is the standard method of commenting out lines in Python. However, when I try to uncomment lines by using a tCom... | In the `tcomment.vim` file in your autoload directory you should find a list like this:
```
call tcomment#DefineType('aap', '# %s' )
call tcomment#DefineType('ada', '-- %s' )
call tcomment#DefineType('apache', '# %s' )
```
In there you'll find thi... |
Python: Find the min, max value in a list of tuples | 4,002,796 | 24 | 2010-10-23T06:22:17Z | 4,002,806 | 53 | 2010-10-23T06:25:11Z | [
"python",
"list",
"graphics"
] | ```
alist = [(1,3),(2,5),(2,4),(7,5)]
```
I need to get the min max value for each position in tuple.
Fox example:
The exepected output of alist is
```
min_x = 1
max_x = 7
min_y = 3
max_y = 5
```
Is there any easy way to do? | ```
map(max, zip(*alist))
```
This first unzips your list, then finds the max for each tuple position
```
>>> alist = [(1,3),(2,5),(2,4),(7,5)]
>>> zip(*alist)
[(1, 2, 2, 7), (3, 5, 4, 5)]
>>> map(max, zip(*alist))
[7, 5]
>>> map(min, zip(*alist))
[1, 3]
```
This will also work for tuples of any length in a list. |
Python: Find the min, max value in a list of tuples | 4,002,796 | 24 | 2010-10-23T06:22:17Z | 4,002,842 | 7 | 2010-10-23T06:37:14Z | [
"python",
"list",
"graphics"
] | ```
alist = [(1,3),(2,5),(2,4),(7,5)]
```
I need to get the min max value for each position in tuple.
Fox example:
The exepected output of alist is
```
min_x = 1
max_x = 7
min_y = 3
max_y = 5
```
Is there any easy way to do? | ```
>>> from operator import itemgetter
>>> alist = [(1,3),(2,5),(2,4),(7,5)]
>>> min(alist)[0], max(alist)[0]
(1, 7)
>>> min(alist, key=itemgetter(1))[1], max(alist, key=itemgetter(1))[1]
(3, 5)
``` |
Auto-load a module on python startup | 4,002,924 | 7 | 2010-10-23T07:14:57Z | 4,002,933 | 11 | 2010-10-23T07:18:34Z | [
"python",
"module",
"autoload",
"ipython"
] | I want IPython or the Python interpreter to auto-load a module when I start them.
Is it possible?
For example when I start IPython:
```
$ ipython
...
>>> from __future__ import division
>>> from mymodule import *
In [1]:
```
Something like [SymPy's live shell](http://docs.sympy.org/latest/tutorial/index.html#tut... | ```
Have a .pythonstartup in your home directory and load modules there
and point PYTHONSTARTUP env to that file.
```
Python commands in that file are executed before the first prompt is displayed in interactive mode.
* <http://docs.python.org/using/cmdline.html>
I use it for enabling command line completion in pyt... |
Translate `thread.start_new_thread(...)` to the new threading API | 4,003,783 | 5 | 2010-10-23T11:40:19Z | 4,004,028 | 7 | 2010-10-23T12:50:01Z | [
"python",
"multithreading"
] | When I use the old Python `thread` API everything works fine:
```
thread.start_new_thread(main_func, args, kwargs)
```
But if I try to use the new [threading](http://docs.python.org/library/threading.html#thread-objects) API the process, which runs the thread hangs when it should exit itself with `sys.exit(3)`:
```
... | This behavior is due to the fact that `thread.start_new_thread` creates thread in `daemon` mode while `threading.Thread` creates thread in `non-daemon` mode.
To start `threading.Thread` in daemon mode, you need to use `.setDaemon` method:
```
my_thread = threading.Thread(target=main_func, args=args, kwargs=kwargs)
m... |
How to build a conceptual search engine? | 4,003,840 | 6 | 2010-10-23T11:58:22Z | 4,004,314 | 9 | 2010-10-23T13:56:42Z | [
"python",
"search",
"lucene",
"nlp",
"lsa"
] | I would like to build an internal search engine (I have a very large collection of thousands of XML files) that is able to map queries to concepts. For example, if I search for "big cats", I would want highly ranked results to return documents with "large cats" as well. But I may also be interested in having it return ... | > I'm not sure how to integrate that into a search engine. Could I use Lucene to do this? How?
Step 1. Stop.
Step 2. Get **something** to work.
Step 3. By then, you'll understand more about Python and Lucene and other tools and ways you might integrate them.
Don't start by trying to solve integration problems. Soft... |
How to remove the last element in each tuple in a list | 4,004,447 | 3 | 2010-10-23T14:25:41Z | 4,004,453 | 8 | 2010-10-23T14:26:47Z | [
"python",
"list",
"tuples"
] | I've got a list like:
```
alist = [[a,b,(1,2)], [a,b,(1,2)], [a,b,(1,2)]]
```
I want to remove the last element from all the elements in a list. So the result will be:
```
alist = [[a,b], [a,b], [a,b]]
```
Is there a fast way to do this? | You could use list comprehension to create a new list that removes the last element.
```
>>> alist = [[1,2,(3,4)],[5,6,(7,8)],[9,10,(11,12)]]
>>> [x[:-1] for x in alist] # <-------------
[[1, 2], [5, 6], [9, 10]]
```
However, if you want efficiency you could modify the list in-place:
```
>>> alist = [[1,2,(3,4... |
Converting string series to float list in python | 4,004,550 | 25 | 2010-10-23T14:50:40Z | 4,004,554 | 50 | 2010-10-23T14:52:07Z | [
"python"
] | I am quite new to programing so I hope this question is simple enough.
I need to know how to convert a string input of numbers separated by spaces on a single line:
```
5.2 5.6 5.3
```
and convert this to a float list
```
lsit = [5.2,5.6,5.3]
```
How can this be done? | Try a list comprehension:
```
s = '5.2 5.6 5.3'
floats = [float(x) for x in s.split()]
```
In Python 2.x it can also be done with map:
```
floats = map(float, s.split())
```
Note that in Python 3.x the second version returns a map object rather than a list. If you need a list you can convert it to a list with a cal... |
Using SoupStrainer to parse selectively | 4,004,979 | 3 | 2010-10-23T16:34:31Z | 4,007,118 | 8 | 2010-10-24T03:58:15Z | [
"python",
"beautifulsoup",
"scrape"
] | Im trying to parse a list of video game titles from a shopping site. however as the item list is all stored inside a tag .
[This](http://www.crummy.com/software/BeautifulSoup/documentation.html#Improving%20Performance%20by%20Parsing%20Only%20Part%20of%20the%20Document) section of the documentation supposedly explains ... | Oh boy am i silly, i was searching for tags with atribute id = products, but it should have been product\_list
heres the finaly code if anyone comes searching.
```
from BeautifulSoup import BeautifulSoup, SoupStrainer
import urllib
import re
start = time.clock()
url = "http://someplace.com"
html = urllib.urlopen(ur... |
How to implement a good __hash__ function in python | 4,005,318 | 51 | 2010-10-23T17:54:24Z | 4,005,412 | 34 | 2010-10-23T18:19:42Z | [
"python",
"hash"
] | When implementing a class with multiple properties (like in the toy example below), what is the best way to handle hashing?
I guess that the `__eq__` and `__hash__` should be consistent, but how to implement a proper hash function that is capable of handling all the properties?
```
class AClass:
def __init__(self):... | `__hash__` should return the same value for objects that are equal. It also shouldn't change over the lifetime of the object; generally you only implement it for immutable objects.
A trivial implementation would be to just `return 0`. This is always correct, but performs badly.
Your solution, returning the hash of a ... |
How to implement a good __hash__ function in python | 4,005,318 | 51 | 2010-10-23T17:54:24Z | 12,511,715 | 9 | 2012-09-20T11:31:08Z | [
"python",
"hash"
] | When implementing a class with multiple properties (like in the toy example below), what is the best way to handle hashing?
I guess that the `__eq__` and `__hash__` should be consistent, but how to implement a proper hash function that is capable of handling all the properties?
```
class AClass:
def __init__(self):... | It's dangerous to write
```
def __eq__(self, other):
return other and self.a == other.a and self.b == other.b
```
because if your rhs (i.e., `other`) object evaluates to boolean False, it will never compare as equal to anything!
In addition, you might want to double check if `other` belongs to the class or subclas... |
changing order of unit tests in Python | 4,005,695 | 19 | 2010-10-23T19:32:09Z | 4,005,707 | 11 | 2010-10-23T19:36:10Z | [
"python",
"unit-testing"
] | How can I make it so unit tests in Python (using `unittest`) are run in the order in which they are specified in the file? | Clever Naming.
```
class Test01_Run_Me_First( unittest.TestCase ):
def test010_do_this( self ):
assertTrue( True )
def test020_do_that( self ):
etc.
```
Is one way to force a specific order. |
changing order of unit tests in Python | 4,005,695 | 19 | 2010-10-23T19:32:09Z | 4,006,044 | 22 | 2010-10-23T21:02:03Z | [
"python",
"unit-testing"
] | How can I make it so unit tests in Python (using `unittest`) are run in the order in which they are specified in the file? | You can change the default sorting behavior by setting a custom comparison function. In unittest.py you can find the class variable `unittest.TestLoader.sortTestMethodsUsing` which is set to the builtin function `cmp` by default.
For example you can revert the execution order of your tests with doing this:
```
import... |
AttributeError: 'str' object has no attribute 'append' | 4,005,796 | 10 | 2010-10-23T19:59:04Z | 4,005,800 | 10 | 2010-10-23T20:00:49Z | [
"python"
] | ```
>>> myList[1]
'from form'
>>> myList[1].append(s)
Traceback (most recent call last):
File "<pyshell#144>", line 1, in <module>
myList[1].append(s)
AttributeError: 'str' object has no attribute 'append'
>>>
```
Why `myList[1]` is considered a `'str'` object? `mList[1]` returns the first item in the list `'fr... | myList[1] is an element of myList and it's type is string.
myList[1] is str, you can not append to it.
myList is a list, you should have been appending to it.
```
>>> myList = [1, 'from form', [1,2]]
>>> myList[1]
'from form'
>>> myList[2]
[1, 2]
>>> myList[2].append('t')
>>> myList
[1, 'from form', [1, 2, 't']]
>>> ... |
etree Clone Node | 4,005,975 | 20 | 2010-10-23T20:43:35Z | 4,006,135 | 23 | 2010-10-23T21:24:34Z | [
"python",
"xml.etree"
] | How to clone `Element` objects in Python `xml.etree`? I'm trying to procedurally move and copy (then modify their attributes) nodes. | You can just use [copy.deepcopy()](http://docs.python.org/library/copy.html) to make a copy of the element. (this will also work with lxml by the way). |
How to choose 10 different integers from range (0, 99) | 4,006,054 | 2 | 2010-10-23T21:05:04Z | 4,006,070 | 10 | 2010-10-23T21:07:43Z | [
"python"
] | I want to choose 10 random integers from 0 to 99. I know I can use:
```
random.randint(a, b)
```
But how to tell the randint() that I only want different integers.
Do I have to just check after each random generation to see if the integer has already been generated and call the method again? That does not seem like ... | ```
from random import sample
sample(range(0, 100), 10)
``` |
How to choose 10 different integers from range (0, 99) | 4,006,054 | 2 | 2010-10-23T21:05:04Z | 4,006,089 | 8 | 2010-10-23T21:12:12Z | [
"python"
] | I want to choose 10 random integers from 0 to 99. I know I can use:
```
random.randint(a, b)
```
But how to tell the randint() that I only want different integers.
Do I have to just check after each random generation to see if the integer has already been generated and call the method again? That does not seem like ... | Here's general strategy that is language independent. Generate an array of 100 entries from 0 to 99. Choose a random number from 0 to 99 and swap the entry at that position with the element at position 0. Then successively choose a random number from i to 99, where i = 1 to 9 and swap the element at that position with ... |
Ignore last \n when using readlines with python | 4,006,441 | 5 | 2010-10-23T22:44:49Z | 4,006,456 | 7 | 2010-10-23T22:49:10Z | [
"python",
"readlines"
] | I have a file I read from that looks like:
```
1 value1
2 value2
3 value3
```
The file may or may not have a trailing \n in the last line.
The code I'm using works great, but if there is an trailing \n it fails.
Whats the best way to catch this?
My code for reference:
```
r=open(sys.argv[1], 'r');
for line... | You can ignore lines that contain only whitespace:
```
for line in r.readlines():
line = line.rstrip() # Remove trailing whitespace.
if line: # Only process non-empty lines.
ref = line.split();
print ref[0], ref[1]
``` |
Monitor ZIP File Extraction Python | 4,006,970 | 5 | 2010-10-24T02:50:34Z | 4,007,052 | 7 | 2010-10-24T03:33:57Z | [
"python",
"zip",
"monitor",
"progress",
"extraction"
] | I need to unzip a .ZIP archive. I already know how to unzip it, but it is a huge file and takes some time to extract. How would I print the percentage complete for the extraction? I would like something like this:
```
Extracting File
1% Complete
2% Complete
etc, etc
``` | here an example that you can start with, it's not optimized:
```
import zipfile
zf = zipfile.ZipFile('test.zip')
uncompress_size = sum((file.file_size for file in zf.infolist()))
extracted_size = 0
for file in zf.infolist():
extracted_size += file.file_size
print "%s %%" % (extracted_size * 100/uncompress_... |
So what exactly does âfrom __future__ import barry_as_FLUFLâ do? | 4,007,289 | 46 | 2010-10-24T06:15:22Z | 4,007,310 | 46 | 2010-10-24T06:42:33Z | [
"python",
"operators"
] | I understand it's an inside joke that's meant to stay (just like â`from __future__ import braces`â), but what exactly does it do? | It's related to [PEP 0401: BDFL Retirement](http://www.python.org/dev/peps/pep-0401/)
Barry refers to Barry Warsaw, a well-known Python developer. The `from __future__ import barry_as_FLUFL` basically replaces the `!=` operator with `<>`. |
How to pad with n characters in Python | 4,008,546 | 11 | 2010-10-24T14:01:30Z | 4,008,562 | 28 | 2010-10-24T14:05:08Z | [
"python",
"string"
] | I should deï¬ne a function `pad_with_n_chars(s, n, c)` that takes a
string 's', an integer 'n', and a character 'c' and returns
a string consisting of 's' padded with 'c' to create a
string with a centered 's' of length 'n'. For example,
`pad_with_n_chars(âdogâ, 5, âxâ)` should return the
string "`xdogx`". | With Python2.6 or better, there's no need to define your own function; the string [format](http://docs.python.org/library/string.html#format-string-syntax) method can do all this for you:
```
In [18]: '{s:{c}^{n}}'.format(s='dog',n=5,c='x')
Out[18]: 'xdogx'
``` |
QListWidget and Multple Selection | 4,008,649 | 9 | 2010-10-24T14:25:32Z | 4,009,709 | 12 | 2010-10-24T18:28:52Z | [
"python",
"user-interface",
"pyqt",
"qlistwidget"
] | I have a regular `QListWidget` with couple of signals and slots hookedup. Everything works as I expect. I can update, retrieve, clear etc.
But the UI wont support multiple selections.
How do I 'enable' multiple selections for `QListWidget`? My limited experience with PyQt tells me I need to create a custom `QListWidg... | Unfortunately I can't help with the Python specific syntax but you don't need to create any subclasses.
After your `QListWidget` is created, call `setSelectionMode()` with one of the multiple selection types passed in, probably `QAbstractItemView::ExtendedSelection` is the one you want. There are a few variations on t... |
QListWidget and Multple Selection | 4,008,649 | 9 | 2010-10-24T14:25:32Z | 24,022,216 | 8 | 2014-06-03T18:19:16Z | [
"python",
"user-interface",
"pyqt",
"qlistwidget"
] | I have a regular `QListWidget` with couple of signals and slots hookedup. Everything works as I expect. I can update, retrieve, clear etc.
But the UI wont support multiple selections.
How do I 'enable' multiple selections for `QListWidget`? My limited experience with PyQt tells me I need to create a custom `QListWidg... | For PyQT4 it's
```
QListWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
``` |
pytz and Etc/GMT-5 | 4,008,960 | 3 | 2010-10-24T15:51:22Z | 4,009,126 | 7 | 2010-10-24T16:27:30Z | [
"python",
"timezone",
"utc",
"pytz"
] | I'm having trouble understanding the conversion between the "Etc/GMT-5" timezone and UTC in pytz.
```
>>> dt = datetime(2009, 9, 9, 10, 0) # September 9 2009, 10:00
>>> gmt_5 = pytz.timezone("Etc/GMT-5")
>>> gmt_5.localize(dt)
datetime.datetime(2009, 9, 9, 10, 0, tzinfo=<StaticTzInfo 'Etc/GMT-5'>)
```
Everything is f... | This is apparently a POSIX thing. From [Wikipedia](http://en.wikipedia.org/wiki/Tz_database):
> In order to conform with the POSIX style, those zones beginning with "Etc/GMT" have their sign reversed from what most people expect. In this style, zones west of GMT have a positive sign and those east have a negative sign... |
Fast max-flow min-cut library for Python | 4,008,997 | 12 | 2010-10-24T16:03:20Z | 7,226,905 | 12 | 2011-08-29T06:37:31Z | [
"python",
"graph",
"graph-theory"
] | Is there a reliable and well-documented Python library with a *fast* implementation of an algorithm that finds maximum flows and minimum cuts in directed graphs?
[pygraph.algorithms.minmax.maximum\_flow](http://www.linux.ime.usp.br/~matiello/python-graph/docs/pygraph.algorithms.minmax-module.html#maximum_flow) from [p... | I have used [graph-tool](http://projects.skewed.de/graph-tool/) for similar tasks.
Graph-tool is an efficient python module for manipulation and statistical analysis of graphs (a.k.a. networks). They even have superb documentation about [max-flow algorithms](http://projects.skewed.de/graph-tool/doc/flow.html).
Curren... |
Python trailing comma after print executes next instruction | 4,009,672 | 6 | 2010-10-24T18:20:41Z | 4,009,681 | 19 | 2010-10-24T18:22:37Z | [
"python",
"text"
] | If a trailing comma is added to the end of a print statement, the next statement is executed first. Why is this? For example, this executes `10000 ** 10000` before it prints `"Hi "`:
```
print "Hi",
print 10000 ** 10000
```
And this takes a while before printing "Hi Hello":
```
def sayHello():
for i in [0] * 100... | 1. In Python 2.x, a trailing `,` in a `print` statement prevents a new line to be emitted.
* In Python 3.x, use `print("Hi", end="")` to achieve the same effect.
2. The standard output is line-buffered. So the `"Hi"` won't be printed before a new line is emitted. |
Python - default arguments in function | 4,009,863 | 2 | 2010-10-24T19:02:34Z | 4,009,872 | 8 | 2010-10-24T19:04:07Z | [
"python",
"urllib2"
] | Looking at the python doc <http://docs.python.org/library/urllib2.html>
urllib2.urlopen(url[, data][, timeout])
So, I pass in a url, then optional data and timeout variables (from how I read it).
So if I want to pass a timeout, but not the data... whats the default variable for data? Do you just do,
```
urlopen('ht... | You use the parameter names:
```
urlopen('http://www.exmaple.com/', timeout=5)
``` |
generating variable names on fly in python | 4,010,840 | 22 | 2010-10-24T22:38:35Z | 4,010,856 | 18 | 2010-10-24T22:43:59Z | [
"python"
] | Is there a way I can generate variable names in python in a loop and assign values to them? For example, if I have
```
prices = [5, 12, 45]
```
I want
```
price1 = 5
price2 = 12
price3 = 45
```
Can I do this in a loop or something instead of manually assigning `price1 = prices[0]`, `price2 = prices[1]` etc.
Thank ... | Though I don't see much point, here it is:
```
for i in xrange(0, len(prices)):
exec("price%d = %s" % (i + 1, repr(prices[i])));
``` |
generating variable names on fly in python | 4,010,840 | 22 | 2010-10-24T22:38:35Z | 4,010,869 | 17 | 2010-10-24T22:47:15Z | [
"python"
] | Is there a way I can generate variable names in python in a loop and assign values to them? For example, if I have
```
prices = [5, 12, 45]
```
I want
```
price1 = 5
price2 = 12
price3 = 45
```
Can I do this in a loop or something instead of manually assigning `price1 = prices[0]`, `price2 = prices[1]` etc.
Thank ... | If you really want to create them on the fly you can assign to the dict that is returned by either globals() or locals() depending on what namespace you want to create them in:
```
globals()['somevar'] = 'someval'
print somevar # prints 'someval'
```
But I wouldn't recommend doing that. In general, avoid global vari... |
generating variable names on fly in python | 4,010,840 | 22 | 2010-10-24T22:38:35Z | 4,010,963 | 7 | 2010-10-24T23:14:05Z | [
"python"
] | Is there a way I can generate variable names in python in a loop and assign values to them? For example, if I have
```
prices = [5, 12, 45]
```
I want
```
price1 = 5
price2 = 12
price3 = 45
```
Can I do this in a loop or something instead of manually assigning `price1 = prices[0]`, `price2 = prices[1]` etc.
Thank ... | On an object, you can achieve this with `setattr`
```
>>> class A(object): pass
>>> a=A()
>>> setattr(a, "hello1", 5)
>>> a.hello1
5
``` |
Python 2.7 cannot import PyQt4 | 4,010,842 | 8 | 2010-10-24T22:39:25Z | 4,892,505 | 8 | 2011-02-03T22:30:50Z | [
"python",
"linux",
"ubuntu",
"python-2.7"
] | I've upgraded to Python 2.7 from Python 2.6 on Ubuntu Maverick Meerkat (10.10) and I'm unable to import PyQt4.
```
austin@gerald:~$ python2.7
Python 2.7.0+ (r27:82500, Sep 15 2010, 18:04:55)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import PyQt4
Traceback (most r... | As PyQt is not using setup.py it cannot be installed using pip or easy\_install
Here you have a tutorial showing how to build and install PyQt for python2.7:
<http://problemssol.blogspot.com/2010/12/compile-and-install-pyqt4-for-python27.html> |
Medical information extraction using Python | 4,011,526 | 10 | 2010-10-25T02:31:02Z | 4,011,602 | 8 | 2010-10-25T02:47:36Z | [
"python",
"parsing",
"machine-learning",
"nlp",
"information-extraction"
] | I am a nurse and I know python but I am not an expert, just used it to process DNA sequences
We got hospital records written in human languages and I am supposed to insert these data into a database or csv file but they are more than 5000 lines and this can be so hard. All the data are written in a consistent format ... | Here are some possible way you can solve this -
1. **Using Regular Expressions** - Define them according to the patterns in your text. Match the expressions, extract pattern and you repeat for all records. This approach needs good understanding of the format in which the data is & of course regular expressions :)
2. *... |
Medical information extraction using Python | 4,011,526 | 10 | 2010-10-25T02:31:02Z | 4,011,756 | 7 | 2010-10-25T03:36:51Z | [
"python",
"parsing",
"machine-learning",
"nlp",
"information-extraction"
] | I am a nurse and I know python but I am not an expert, just used it to process DNA sequences
We got hospital records written in human languages and I am supposed to insert these data into a database or csv file but they are more than 5000 lines and this can be so hard. All the data are written in a consistent format ... | This uses [dateutil](http://labix.org/python-dateutil) to parse the date (e.g. '11/11/2010 - 09:00am'), and [parsedatetime](http://code.google.com/p/parsedatetime/) to parse the relative time (e.g. '4 hours later'):
```
import dateutil.parser as dparser
import parsedatetime.parsedatetime as pdt
import parsedatetime.pa... |
Python: The _imagingft C module is not installed | 4,011,705 | 64 | 2010-10-25T03:21:10Z | 4,011,715 | 50 | 2010-10-25T03:24:32Z | [
"python",
"image",
"python-imaging-library"
] | I've tried lots of solution that posted on the net, they don't work.
```
>>> import _imaging
>>> _imaging.__file__
'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd'
>>>
```
So the system can find the \_imaging but still can't use truetype font
```
from PIL import Image, ImageDraw, ImageFilter, ImageFont
im = I... | Your installed PIL was compiled without libfreetype.
You can get precompiled installer of PIL (compiled with libfreetype) here (and many other precompiled Python C Modules):
<http://www.lfd.uci.edu/~gohlke/pythonlibs/> |
Python: The _imagingft C module is not installed | 4,011,705 | 64 | 2010-10-25T03:21:10Z | 5,770,215 | 64 | 2011-04-24T11:20:57Z | [
"python",
"image",
"python-imaging-library"
] | I've tried lots of solution that posted on the net, they don't work.
```
>>> import _imaging
>>> _imaging.__file__
'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd'
>>>
```
So the system can find the \_imaging but still can't use truetype font
```
from PIL import Image, ImageDraw, ImageFilter, ImageFont
im = I... | On Ubuntu, you need to have libfreetype-dev installed before compiling PIL.
i.e.
```
$ sudo aptitude install libfreetype6-dev
$ sudo -s # See PS!
\# pip uninstall pil
\# pip install pil # or use 'easy_install pil'
```
PS! Running pip uninstall/install with sudo is not really recommended as it makes your Ubuntu insta... |
Python: The _imagingft C module is not installed | 4,011,705 | 64 | 2010-10-25T03:21:10Z | 11,756,083 | 12 | 2012-08-01T09:11:46Z | [
"python",
"image",
"python-imaging-library"
] | I've tried lots of solution that posted on the net, they don't work.
```
>>> import _imaging
>>> _imaging.__file__
'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd'
>>>
```
So the system can find the \_imaging but still can't use truetype font
```
from PIL import Image, ImageDraw, ImageFilter, ImageFont
im = I... | In OS X, I did this to solve the problem:
```
pip uninstall PIL
ln -s /usr/X11/include/freetype2 /usr/local/include/
ln -s /usr/X11/include/ft2build.h /usr/local/include/
ln -s /usr/X11/lib/libfreetype.6.dylib /usr/local/lib/
ln -s /usr/X11/lib/libfreetype.6.dylib /usr/local/lib/libfreetype.dylib
pip install PIL
``` |
Python: The _imagingft C module is not installed | 4,011,705 | 64 | 2010-10-25T03:21:10Z | 12,057,474 | 12 | 2012-08-21T14:47:08Z | [
"python",
"image",
"python-imaging-library"
] | I've tried lots of solution that posted on the net, they don't work.
```
>>> import _imaging
>>> _imaging.__file__
'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd'
>>>
```
So the system can find the \_imaging but still can't use truetype font
```
from PIL import Image, ImageDraw, ImageFilter, ImageFont
im = I... | Basically, you need to install freetype before installing PIL.
If you're using [Homebrew](http://mxcl.github.com/homebrew/) on OS X it's just a matter of:
```
brew remove pil
brew install freetype
brew install pil
``` |
Python: The _imagingft C module is not installed | 4,011,705 | 64 | 2010-10-25T03:21:10Z | 14,538,874 | 12 | 2013-01-26T16:22:58Z | [
"python",
"image",
"python-imaging-library"
] | I've tried lots of solution that posted on the net, they don't work.
```
>>> import _imaging
>>> _imaging.__file__
'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd'
>>>
```
So the system can find the \_imaging but still can't use truetype font
```
from PIL import Image, ImageDraw, ImageFilter, ImageFont
im = I... | Worked for Ubuntu 12.10:
```
sudo pip uninstall PIL
sudo apt-get install libfreetype6-dev
sudo apt-get install python-imaging
``` |
Python: The _imagingft C module is not installed | 4,011,705 | 64 | 2010-10-25T03:21:10Z | 16,510,480 | 14 | 2013-05-12T18:04:11Z | [
"python",
"image",
"python-imaging-library"
] | I've tried lots of solution that posted on the net, they don't work.
```
>>> import _imaging
>>> _imaging.__file__
'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd'
>>>
```
So the system can find the \_imaging but still can't use truetype font
```
from PIL import Image, ImageDraw, ImageFilter, ImageFont
im = I... | solution for CentOS 6 (and probably other rpm based):
```
yum install freetype-devel libjpeg-devel libpng-devel
pip uninstall pil Pillow
pip install pil Pillow
``` |
Python: The _imagingft C module is not installed | 4,011,705 | 64 | 2010-10-25T03:21:10Z | 32,548,013 | 19 | 2015-09-13T08:57:58Z | [
"python",
"image",
"python-imaging-library"
] | I've tried lots of solution that posted on the net, they don't work.
```
>>> import _imaging
>>> _imaging.__file__
'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd'
>>>
```
So the system can find the \_imaging but still can't use truetype font
```
from PIL import Image, ImageDraw, ImageFilter, ImageFont
im = I... | The following worked for me on Ubuntu 14.04.1 64 bit:
```
sudo apt-get install libfreetype6-dev
```
Then, in the virtualenv:
```
pip uninstall pillow
pip install --no-cache-dir pillow
``` |
Is it bad that I don't follow PEP 8 and cut my lines at 79 characters? | 4,012,482 | 7 | 2010-10-25T07:08:24Z | 4,012,589 | 8 | 2010-10-25T07:27:14Z | [
"python",
"coding-style",
"pep8"
] | I think every Python code has seen [PEP 8](http://www.python.org/dev/peps/pep-0008/). The part that sticks out to me is:
```
Limit all lines to a maximum of 79 characters.
```
I'm sitting here on a widescreen monitor and coding right across the screen. I'm not coding in a terminal and don't plan on coding in a termin... | Are you the only one who's going to read the code?
No matter what language you're programming in, it's recommended practice to keep code line length down.
There are typically 2 types of causes for long lines:
1. Deeply nested code: this type of code is hard to follow, especially if you have more than 2 levels of nest... |
Python: Which encoding is used for processing sys.argv? | 4,012,571 | 17 | 2010-10-25T07:23:47Z | 4,085,760 | 7 | 2010-11-03T09:44:46Z | [
"python",
"encoding",
"argv",
"sys"
] | In what encoding are the elements of `sys.argv`, in Python? are they encoded with the `sys.getdefaultencoding()` encoding?
> sys.getdefaultencoding(): Return the name of the current default string encoding used by the Unicode implementation.
**PS**: As pointed out in some of the answers, `sys.stdin.encoding` would in... | I'm guessing that you are asking this because you ran into [issue 2128](http://bugs.python.org/issue2128). Note that this has been fixed in Python 3.0. |
How many bytes does a string have | 4,013,230 | 30 | 2010-10-25T09:20:36Z | 4,013,246 | 38 | 2010-10-25T09:23:02Z | [
"python"
] | Is there some function which will tell me how many bytes does a string occupy in memory?
I need to set a size of a socket buffer in order to transfer the whole string at once. | ```
import sys
sys.getsizeof(s)
# getsizeof(object, default) -> int
# Return the size of object in bytes.
```
But actually you need to know its represented length, so something like `len(s)` should be enough. |
How many bytes does a string have | 4,013,230 | 30 | 2010-10-25T09:20:36Z | 4,013,418 | 27 | 2010-10-25T09:48:28Z | [
"python"
] | Is there some function which will tell me how many bytes does a string occupy in memory?
I need to set a size of a socket buffer in order to transfer the whole string at once. | If it's a Python 2.x `str`, get its `len`. If it's a Python 3.x `str` (or a Python 2.x `unicode`), first encode to `bytes` (or a `str`, respectively) using your preferred encoding (`'utf-8'` is a good choice) and then get the `len` of the encoded bytes/str object. |
urlencode a multidimensional dictionary in python | 4,013,838 | 5 | 2010-10-25T10:51:08Z | 4,014,164 | 7 | 2010-10-25T11:38:11Z | [
"python",
"urlencode"
] | How can I get a URL-encoded version of a multidimensional dictionary in Python? Unfortunately, `urllib.urlencode()` only works in a single dimension. I would need a version capable of recursively encoding the dictionary.
For example, if I have the following dictionary:
```
{'a': 'b', 'c': {'d': 'e'}}
```
I want to o... | OK people. I implemented it myself:
```
import urllib
def recursive_urlencode(d):
"""URL-encode a multidimensional dictionary.
>>> data = {'a': 'b&c', 'd': {'e': {'f&g': 'h*i'}}, 'j': 'k'}
>>> recursive_urlencode(data)
u'a=b%26c&j=k&d[e][f%26g]=h%2Ai'
"""
def recursion(d, base=[]):
pa... |
exception handling for optparse of python | 4,014,211 | 2 | 2010-10-25T11:46:20Z | 4,014,314 | 10 | 2010-10-25T12:01:58Z | [
"python",
"command-line",
"exception-handling"
] | HI, guys.
I am using cmd and optparse to develop a CLI.py for a collection of already-functional classes (CDContainer, CD, etc.). The following are some parts of the code. I have a problem here. when there are exceptions(wrong input type or missing values), the optparse will exit the whole program instead of the speci... | The `optparse` documentation says this:
> If optparseâs default error-handling behaviour does not suit your needs, youâll need to subclass OptionParser and override its exit() and/or error() methods.
Ideally you'd define a new type of exception, subclass `optparse`, raise the exception in the `exit()` or `error()... |
A python class that acts like dict | 4,014,621 | 45 | 2010-10-25T12:42:18Z | 4,014,660 | 21 | 2010-10-25T12:47:31Z | [
"python",
"dictionary"
] | I want to write a custom class that behaves like `dict` - so, I am inheriting from `dict`.
My question, though, is: Do I need to create a private `dict` member in my `__init__()` method?. I don't see the point of this, since I already have the `dict` behavior if I simply inherit from `dict`.
Can anyone point out why ... | Check the documentation on [emulating container types](https://docs.python.org/3/reference/datamodel.html?emulating-container-types#emulating-container-types). In your case, the first parameter to `add` should be `self`. |
A python class that acts like dict | 4,014,621 | 45 | 2010-10-25T12:42:18Z | 4,015,104 | 40 | 2010-10-25T13:39:00Z | [
"python",
"dictionary"
] | I want to write a custom class that behaves like `dict` - so, I am inheriting from `dict`.
My question, though, is: Do I need to create a private `dict` member in my `__init__()` method?. I don't see the point of this, since I already have the `dict` behavior if I simply inherit from `dict`.
Can anyone point out why ... | Like this
```
class CustomDictOne(dict):
def __init__(self,*arg,**kw):
super(CustomDictOne, self).__init__(*arg, **kw)
```
Now you can use the built-in functions, like `dict.get()` as `self.get()`.
You do not need to wrap a hidden `self._dict`. Your class already **is** a dict. |
A python class that acts like dict | 4,014,621 | 45 | 2010-10-25T12:42:18Z | 23,976,949 | 37 | 2014-06-01T05:10:32Z | [
"python",
"dictionary"
] | I want to write a custom class that behaves like `dict` - so, I am inheriting from `dict`.
My question, though, is: Do I need to create a private `dict` member in my `__init__()` method?. I don't see the point of this, since I already have the `dict` behavior if I simply inherit from `dict`.
Can anyone point out why ... | ```
class Mapping(dict):
def __setitem__(self, key, item):
self.__dict__[key] = item
def __getitem__(self, key):
return self.__dict__[key]
def __repr__(self):
return repr(self.__dict__)
def __len__(self):
return len(self.__dict__)
def __delitem__(self, key):
... |
Send commands between two computers over the internet | 4,014,670 | 3 | 2010-10-25T12:48:46Z | 4,014,689 | 11 | 2010-10-25T12:51:16Z | [
"java",
"php",
"javascript",
"python"
] | I wish to control my computer (and usb devices attached to the computer) at home with any computer that is connected to the internet. The computer at home must have a program installed that receives commands from any other computer that is connected to the internet. I thought it would be best if I do this with a web in... | [VNC](http://www.tightvnc.com/)
[SSH](http://www.openssh.com/)
[Remote Desktop (Windows)](http://www.microsoft.com/windowsxp/using/mobility/getstarted/remoteintro.mspx) |
Python class inherits object | 4,015,417 | 372 | 2010-10-25T14:15:26Z | 4,015,465 | 17 | 2010-10-25T14:20:34Z | [
"python",
"class",
"object",
"inheritance"
] | Is there any reason for a class declaration to inherit from `object`?
I just found some code that does this and I can't find a good reason why.
```
class MyClass(object):
# class code follows...
``` | Yes, it's [historical](http://www.python.org/doc/newstyle/). Without its old-style classes.
If you use `type()` on an old-style object, you just get "instance". On a new-style object you get its class |
Python class inherits object | 4,015,417 | 372 | 2010-10-25T14:15:26Z | 4,015,466 | 291 | 2010-10-25T14:20:56Z | [
"python",
"class",
"object",
"inheritance"
] | Is there any reason for a class declaration to inherit from `object`?
I just found some code that does this and I can't find a good reason why.
```
class MyClass(object):
# class code follows...
``` | Yes, this is a 'new style' object. It was a feature introduced in python2.2.
New style objects have a different object model to classic objects, and some things won't work properly with old style objects, for instance, super(), @property and descriptors. See this article for a good description of what a new style clas... |
Python class inherits object | 4,015,417 | 372 | 2010-10-25T14:15:26Z | 9,448,136 | 320 | 2012-02-25T21:15:32Z | [
"python",
"class",
"object",
"inheritance"
] | Is there any reason for a class declaration to inherit from `object`?
I just found some code that does this and I can't find a good reason why.
```
class MyClass(object):
# class code follows...
``` | **Python 3.x:**
`class MyClass(object):` = new-style class
`class MyClass:` = new-style class (implicitly inherits from object)
**Python 2.x:**
`class MyClass(object):` = new-style class
`class MyClass:` = *OLD-STYLE CLASS*
## Explanation:
When defining base classes in Python 3.x, youâre allowed to drop th... |
Python class inherits object | 4,015,417 | 372 | 2010-10-25T14:15:26Z | 26,733,360 | 16 | 2014-11-04T10:54:50Z | [
"python",
"class",
"object",
"inheritance"
] | Is there any reason for a class declaration to inherit from `object`?
I just found some code that does this and I can't find a good reason why.
```
class MyClass(object):
# class code follows...
``` | History from [Learn Python the Hard Way](http://learnpythonthehardway.org/book/ex42.html):
> Python's original rendition of a class was broken in many serious
> ways. By the time this fault was recognized it was already too late,
> and they had to support it. In order to fix the problem, they needed
> some "new class"... |
Can I include sub-config files in my mercurial .hgrc? | 4,015,901 | 13 | 2010-10-25T15:05:13Z | 4,016,310 | 17 | 2010-10-25T15:48:01Z | [
"python",
"mercurial",
"hgrc",
"dotfiles"
] | I want to keep my main `.hgrc` in revision control, because I have a fair amount of customization it in, but I want to have different author names depending on which machine I'm using (work, home, &c.).
The way I'd do this in a bash script is to source a host-local bash script that is ignored by Mercurial, but I'm not... | You can do this using the not-often-used but been-there-awhile include syntax.
Put your machine specific stuff in your `~/.hgrc` and then include a constant-across-all-systems boilerplate config file. Example:
```
[ui]
username=You <you@somewhere>
%include .hgrc-boilerplate
```
Track the .hgrc-boilerplate file in r... |
How to use Python's "easy_install" on Windows ... it's not so easy | 4,016,151 | 55 | 2010-10-25T15:31:20Z | 4,016,552 | 8 | 2010-10-25T16:10:37Z | [
"python",
"windows",
"easy-install"
] | After installing Python 2.7 on Windows XP, then manually setting the `%PATH%` to `python.exe` (why won't the python installer do this?), then installing `setuptools 0.6c11` (why doesn't the python installer do this?), then manually setting the `%PATH%` to `easy_install.exe` (why doesn't the installer do this?), I final... | One problem is that easy\_install is set up to download and install .egg files or source distributions (contained within .tgz, .tar, .tar.gz, .tar.bz2, or .zip files). It doesn't know how to deal with the PyWin32 extensions because they are put [within a separate installer executable](http://sourceforge.net/projects/py... |
How to use Python's "easy_install" on Windows ... it's not so easy | 4,016,151 | 55 | 2010-10-25T15:31:20Z | 13,737,171 | 21 | 2012-12-06T04:52:49Z | [
"python",
"windows",
"easy-install"
] | After installing Python 2.7 on Windows XP, then manually setting the `%PATH%` to `python.exe` (why won't the python installer do this?), then installing `setuptools 0.6c11` (why doesn't the python installer do this?), then manually setting the `%PATH%` to `easy_install.exe` (why doesn't the installer do this?), I final... | If you are using windows 7 64-bit version, then the solution is found here: <http://pypi.python.org/pypi/setuptools>
namely, you need to download a python script, run it, and then easy\_install will work normally from commandline.
P.S. I agree with the original poster saying that this should work out of the box. |
How to use Python's "easy_install" on Windows ... it's not so easy | 4,016,151 | 55 | 2010-10-25T15:31:20Z | 17,997,823 | 8 | 2013-08-01T15:09:04Z | [
"python",
"windows",
"easy-install"
] | After installing Python 2.7 on Windows XP, then manually setting the `%PATH%` to `python.exe` (why won't the python installer do this?), then installing `setuptools 0.6c11` (why doesn't the python installer do this?), then manually setting the `%PATH%` to `easy_install.exe` (why doesn't the installer do this?), I final... | I also agree with the OP that all these things should come with Python already set. I guess we will have to deal with it until that day comes. Here is a solution that actually worked for me :
[installing easy\_install faster and easier](http://simpledeveloper.com/how-to-install-easy_install/)
I hope it helps you or a... |
How can I add a command to the Python interactive shell? | 4,017,204 | 2 | 2010-10-25T17:27:36Z | 4,017,300 | 7 | 2010-10-25T17:41:27Z | [
"python",
"interactive",
"readline",
"cpython"
] | I'm trying to save myself just a few keystrokes for a command I type fairly regularly in Python.
In my [python startup script](http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP), I define a function called load which is similar to import, but adds some functionality. It takes a single string:
```
def loa... | You could try [ipython](http://ipython.scipy.org/moin/) - which gives a python shell which does allow many things including [automatic parentheses](http://ipython.scipy.org/doc/manual/html/interactive/reference.html#automatic-parentheses) which gives you the function call as you requested. |
How can I make an alias to a non-function member attribute in a Python class? | 4,017,572 | 11 | 2010-10-25T18:19:44Z | 4,017,638 | 12 | 2010-10-25T18:30:32Z | [
"python",
"class",
"alias"
] | I'm in the midst of writing a Python Library API and I often run into the scenario where my users want multiple different names for the same functions and variables.
If I have a Python class with the function `foo()` and I want to make an alias to it called `bar()`, that's super easy:
```
class Dummy(object):
def... | You can provide a `__setattr__` and `__getattr__` that reference an aliases map:
```
class Dummy(object):
aliases = {
'xValue': 'x',
'another': 'x',
}
def __init__(self):
self.x = 17
def __setattr__(self, name, value):
name = self.aliases.get(name, name)
ob... |
convert string to datetime object | 4,018,730 | 9 | 2010-10-25T20:49:57Z | 4,018,751 | 25 | 2010-10-25T20:52:04Z | [
"python",
"datetime"
] | I'd like to convert this string into a datetime object:
```
Wed Oct 20 16:35:44 +0000 2010
```
Is there a simple way to do this? Or do I have to write a RE to parse the elements, convert Oct to 10 and so forth?
EDIT:
strptime is great. However, with
```
datetime.strptime(date_str, "%a %b %d %H:%M:%S %z %Y")
```
I ... | No RE needed. Try this:
```
from dateutil import parser
yourDate = parser.parse(yourString)
```
for "Wed Oct 20 16:35:44 +0000 2010" returns `datetime.datetime(2010, 10, 20, 16, 35, 44, tzinfo=tzutc())` |
Python: Is it bad style to give an argument the same name as the function? | 4,018,783 | 3 | 2010-10-25T20:55:38Z | 4,018,792 | 11 | 2010-10-25T20:57:25Z | [
"python",
"coding-style"
] | Consider the following code:
```
def localize(value, localize=None):
# do something with the localize argument
```
The `localize` variable contains information whether the global localization setting should be respected or not. It is called by the same name through three layers of code. What's the lesser evil,
*... | I'd say that's bad style. Instead of changing the function name you could change the parameter name. Perhaps you could use a name like `locale` or `localization`? A noun is probably a better choice than a verb anyway. |
Text box with line wrapping in matplotlib? | 4,018,860 | 57 | 2010-10-25T21:06:23Z | 4,056,853 | 91 | 2010-10-30T01:24:09Z | [
"python",
"textbox",
"matplotlib"
] | Is it possible to display text in a box through Matplotlib, *with automatic line breaks*? By using `pyplot.text()`, I was only able to print multi-line text that flows beyond the boundaries of the window, which is annoying. The size of the lines is not known in advance⦠Any idea would be much appreciated! | The contents of this answer were merged into mpl master in <https://github.com/matplotlib/matplotlib/pull/4342> and will be in the next feature release.
---
Wow... This is a thorny problem... (And it exposes a lot of limitations in matplotlib's text rendering...)
This should (i.m.o.) be something that matplotlib has... |
splitting a dictionary in python into keys and values | 4,019,639 | 6 | 2010-10-25T23:17:00Z | 4,019,648 | 25 | 2010-10-25T23:18:57Z | [
"python",
"list",
"dictionary"
] | How can I take a dictionary and split it into two lists, one of keys, one of values. For example take:
```
{'name': 'Han Solo', 'firstname': 'Han', 'lastname': 'Solo', 'age': 37, 'score': 100, 'yrclass': 10}
```
and split it into:
```
['name', 'firstname', 'lastname', 'age', 'score', 'yrclass']
# and
['Han Solo', 'H... | Not that hard, try `help(dict)` in a console for more info :)
```
keys = dictionary.keys()
values = dictionary.values()
```
For both keys and values:
```
items = dictionary.items()
```
Which can be used to split them as well:
```
keys, values = zip(*dictionary.items())
```
Note that the order of all of these is c... |
Decimal to JSON | 4,019,856 | 5 | 2010-10-26T00:27:31Z | 4,019,897 | 10 | 2010-10-26T00:39:36Z | [
"python",
"django"
] | I'm pulling a sum from a DB which is a decimal value.
I'm trying to use that value in a JSON result
```
json.dumps( { 'sum': amount } ) #where amount is my Decimal
```
Django can't serialize the `Decimal`.
I can convert it to a string, but I'd like a numeric type within the JSON.
If I try and convert it to a `float` ... | What you can do is extend the JSONDecoder class to provide a custom serializer for the Decimal type, similar to the example in this document: <http://docs.python.org/py3k/library/json.html>
```
>>> import json
>>> class DecimalEncoder(json.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, De... |
How to implement __iter__(self) for a container object (Python) | 4,019,971 | 52 | 2010-10-26T00:59:23Z | 4,019,987 | 52 | 2010-10-26T01:04:01Z | [
"python"
] | I have written a custom container object.
According to [this page](http://docs.python.org/release/2.5.2/ref/sequence-types.html), I need to implement this method on my object:
```
__iter__(self)
```
However, upon following up the link to [Iterator Types](http://docs.python.org/release/2.5.2/lib/typeiter.html) in the... | I normally would use a generator function. Each time you use a yield statement, it will add an item to the sequence.
The following will create an iterator that returns five, and then every item in some\_list.
```
def __iter__(self):
yield 5
for x in some_list:
yield x
``` |
How to implement __iter__(self) for a container object (Python) | 4,019,971 | 52 | 2010-10-26T00:59:23Z | 4,020,009 | 7 | 2010-10-26T01:13:17Z | [
"python"
] | I have written a custom container object.
According to [this page](http://docs.python.org/release/2.5.2/ref/sequence-types.html), I need to implement this method on my object:
```
__iter__(self)
```
However, upon following up the link to [Iterator Types](http://docs.python.org/release/2.5.2/lib/typeiter.html) in the... | usually `__iter__()` just return self if you have already define the next() method (generator object):
here is a Dummy example of a generator :
```
class Test(object):
def __init__(self, data):
self.data = data
def next(self):
if not self.data:
raise StopIteration
return se... |
How to implement __iter__(self) for a container object (Python) | 4,019,971 | 52 | 2010-10-26T00:59:23Z | 4,020,113 | 18 | 2010-10-26T01:45:32Z | [
"python"
] | I have written a custom container object.
According to [this page](http://docs.python.org/release/2.5.2/ref/sequence-types.html), I need to implement this method on my object:
```
__iter__(self)
```
However, upon following up the link to [Iterator Types](http://docs.python.org/release/2.5.2/lib/typeiter.html) in the... | Another option is to inherit from the appropriate abstract base class from the `collections module as documented [here](http://docs.python.org/library/collections.html#abcs-abstract-base-classes).
In case the container is its own iterator, you can inherit from
`collections.Iterator`. You only need to implement the `ne... |
Why aren't python nested functions called closures? | 4,020,419 | 156 | 2010-10-26T03:11:14Z | 4,020,443 | 244 | 2010-10-26T03:20:12Z | [
"python",
"closures",
"nested-function"
] | I have seen and used nested functions in Python, and they match the definition of a closure. So why are they called `nested functions` instead of `closures`?
Are nested functions not closures because they are not used by the external world?
**UPDATE:** I was reading about closures and it got me thinking about this co... | A closure occurs when a function has access to a local variable from an enclosing scope that has finished its execution.
```
def make_printer(msg):
def printer():
print msg
return printer
printer = make_printer('Foo!')
printer()
```
When `make_printer` is called, a new frame is put on the stack with ... |
Why aren't python nested functions called closures? | 4,020,419 | 156 | 2010-10-26T03:11:14Z | 20,898,085 | 55 | 2014-01-03T06:41:20Z | [
"python",
"closures",
"nested-function"
] | I have seen and used nested functions in Python, and they match the definition of a closure. So why are they called `nested functions` instead of `closures`?
Are nested functions not closures because they are not used by the external world?
**UPDATE:** I was reading about closures and it got me thinking about this co... | **The question has already been answered by** [aaronasterling](http://stackoverflow.com/users/376728/aaronasterling)
However, someone might be interested in how the variables are stored under the hood.
**Before coming to the snippet:**
Closures are functions that inherit variables from their enclosing environment. W... |
Why aren't python nested functions called closures? | 4,020,419 | 156 | 2010-10-26T03:11:14Z | 23,558,809 | 42 | 2014-05-09T07:22:27Z | [
"python",
"closures",
"nested-function"
] | I have seen and used nested functions in Python, and they match the definition of a closure. So why are they called `nested functions` instead of `closures`?
Are nested functions not closures because they are not used by the external world?
**UPDATE:** I was reading about closures and it got me thinking about this co... | Python has a *weak* support for closure. To see what I mean take the following example of a counter using closure with JavaScript:
```
function initCounter(){
var x = 0;
function counter () {
x += 1;
console.log(x);
};
return counter;
}
count = initCounter();
count(); //Prints 1
coun... |
Process escape sequences in a string in Python | 4,020,539 | 48 | 2010-10-26T03:43:56Z | 4,020,824 | 65 | 2010-10-26T05:01:32Z | [
"python",
"string",
"escaping"
] | Sometimes when I get input from a file or the user, I get a string with escape sequences in it. I would like to process the escape sequences [in the same way that Python processes escape sequences in string literals](http://docs.python.org/reference/lexical_analysis.html#string-literals).
For example, let's say `myStr... | The correct thing to do is use the 'string-escape' code to decode the string.
```
>>> myString = "spam\\neggs"
>>> decoded_string = bytes(myString, "utf-8").decode("unicode_escape") # python3
>>> decoded_string = myString.decode('string_escape') # python2
>>> print(decoded_string)
spam
eggs
```
Don't use the AST or ... |
Process escape sequences in a string in Python | 4,020,539 | 48 | 2010-10-26T03:43:56Z | 24,519,338 | 44 | 2014-07-01T21:12:28Z | [
"python",
"string",
"escaping"
] | Sometimes when I get input from a file or the user, I get a string with escape sequences in it. I would like to process the escape sequences [in the same way that Python processes escape sequences in string literals](http://docs.python.org/reference/lexical_analysis.html#string-literals).
For example, let's say `myStr... | ## `unicode_escape` doesn't work in general
It turns out that the `string_escape` or `unicode_escape` solution does not work in general -- particularly, it doesn't work in the presence of actual Unicode.
If you can be sure that *every* non-ASCII character will be escaped (and remember, anything beyond the first 128 c... |
Finding the index of a string in a tuple | 4,021,154 | 11 | 2010-10-26T06:19:29Z | 4,021,165 | 21 | 2010-10-26T06:21:13Z | [
"python",
"tuples"
] | ```
Tup = ('string1','string2','string3')
```
My program returned **string2** how do I get it's index within **Tup**? | ```
>>> tup.index('string2')
1
```
Note that the `index()` method has only just been added for tuples in versions 2.6 and better. |
Can an object's methods act on itself? | 4,022,419 | 4 | 2010-10-26T09:41:36Z | 4,022,748 | 8 | 2010-10-26T10:23:38Z | [
"javascript",
"python",
"ruby",
"oop",
"design-patterns"
] | I'm not sure where to put some methods.
Let's say I want to send an email.
Which of the following options should I choose:
```
email = new Email("title", "adress", "body");
email.send();
```
or
```
email = new Email("title", "adress", "body");
Postman.send(email);
```
Because how can an email send itself? And isn... | I disagree with Arseny. An email *can* send itself, and that's exactly where the code should live. That's what methods are: actions that can be performed on the object.
However, note that your approaches are not mutually incompatible. An email's `send` action could easily just contain the code to add itself to the Pos... |
python pty.fork - how does it work | 4,022,600 | 5 | 2010-10-26T10:04:05Z | 6,953,572 | 10 | 2011-08-05T08:39:51Z | [
"python",
"pty"
] | <http://docs.python.org/library/pty.html> says -
> pty.fork()¶
> Fork. Connect the childâs controlling terminal to a pseudo-terminal. Return value is (pid, fd). Note that the child gets pid 0, and the fd is invalid. The parentâs return value is the pid of the child, and fd is a file descriptor connected to the ch... | I think I finally got a minimal example for `pty.fork` in Python - and since I found it extremely difficult to find a similar example, I'm posting it here as an illustration of @joni's answer. It is essentially based on:
* [pty - Python os.forkpty why can't I make it work - Stack Overflow](http://stackoverflow.com/que... |
Insert some string into given string at given index in Python | 4,022,827 | 20 | 2010-10-26T10:35:17Z | 4,023,434 | 62 | 2010-10-26T12:02:22Z | [
"python",
"string"
] | I am newbie in Python facing a problem: How to insert some fields in already existing string?
For example, suppose I have read one line from any file which contains:
```
line = "Name Age Group Class Profession"
```
Now I have to insert 3rd Field(Group) 3 times more in the same line before Class field. It means the o... | An important point that often bites new Python programmers but the other posters haven't made explicit is that strings in Python are immutable -- you can't **ever** modify them in place.
You need to retrain yourself when working with strings in Python so that instead of thinking, "How can I modify this string?" instea... |
Insert some string into given string at given index in Python | 4,022,827 | 20 | 2010-10-26T10:35:17Z | 24,450,558 | 27 | 2014-06-27T11:19:19Z | [
"python",
"string"
] | I am newbie in Python facing a problem: How to insert some fields in already existing string?
For example, suppose I have read one line from any file which contains:
```
line = "Name Age Group Class Profession"
```
Now I have to insert 3rd Field(Group) 3 times more in the same line before Class field. It means the o... | For the sake of future 'newbies' tackling this problem, I think a quick answer would be fitting to this thread.
Like [bgporter](http://stackoverflow.com/users/203568/bgporter) said: Python strings are immutable, and so, in order to modify a string you have to make use of the pieces you already have.
In the following ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.