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 |
|---|---|---|---|---|---|---|---|---|---|
Using python map and other functional tools | 672,172 | 119 | 2009-03-23T03:46:29Z | 672,198 | 52 | 2009-03-23T04:00:28Z | [
"python",
"dictionary",
"functional-programming"
] | This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:
```
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo, bar):
print foo, bar
map(maptest, foos, bars)
```
produces:
```
1.0 1
2.0 2
3.0 3
4.0 None
5.0 None
```
**Q. Is there a way to use ma... | The easiest way would be not to pass `bars` through the different functions, but to access it directly from `maptest`:
```
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo):
print foo, bars
map(maptest, foos)
```
With your original `maptest` function you could also use a lambda function in `map`:
``... |
Using python map and other functional tools | 672,172 | 119 | 2009-03-23T03:46:29Z | 672,216 | 11 | 2009-03-23T04:17:28Z | [
"python",
"dictionary",
"functional-programming"
] | This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:
```
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo, bar):
print foo, bar
map(maptest, foos, bars)
```
produces:
```
1.0 1
2.0 2
3.0 3
4.0 None
5.0 None
```
**Q. Is there a way to use ma... | ```
import itertools
foos=[1.0, 2.0, 3.0, 4.0, 5.0]
bars=[1, 2, 3]
print zip(foos, itertools.cycle([bars]))
``` |
Using python map and other functional tools | 672,172 | 119 | 2009-03-23T03:46:29Z | 672,222 | 12 | 2009-03-23T04:21:19Z | [
"python",
"dictionary",
"functional-programming"
] | This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:
```
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo, bar):
print foo, bar
map(maptest, foos, bars)
```
produces:
```
1.0 1
2.0 2
3.0 3
4.0 None
5.0 None
```
**Q. Is there a way to use ma... | ```
>>> from itertools import repeat
>>> for foo, bars in zip(foos, repeat(bars)):
... print foo, bars
...
1.0 [1, 2, 3]
2.0 [1, 2, 3]
3.0 [1, 2, 3]
4.0 [1, 2, 3]
5.0 [1, 2, 3]
``` |
Using python map and other functional tools | 672,172 | 119 | 2009-03-23T03:46:29Z | 672,296 | 188 | 2009-03-23T05:11:47Z | [
"python",
"dictionary",
"functional-programming"
] | This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:
```
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo, bar):
print foo, bar
map(maptest, foos, bars)
```
produces:
```
1.0 1
2.0 2
3.0 3
4.0 None
5.0 None
```
**Q. Is there a way to use ma... | Are you familiar with other functional languages? i.e. are you trying to learn how python does functional programming, or are you trying to learn about functional programming and using python as the vehicle?
Also, do you understand list comprehensions?
```
map(f, sequence)
```
is directly equivalent (\*) to:
```
[f... |
Using python map and other functional tools | 672,172 | 119 | 2009-03-23T03:46:29Z | 672,469 | 18 | 2009-03-23T07:28:29Z | [
"python",
"dictionary",
"functional-programming"
] | This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:
```
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo, bar):
print foo, bar
map(maptest, foos, bars)
```
produces:
```
1.0 1
2.0 2
3.0 3
4.0 None
5.0 None
```
**Q. Is there a way to use ma... | Functional programming is about creating side-effect-free code.
map is a functional list transformation abstraction. You use it to take a sequence of something and turn it into a sequence of something else.
You are trying to use it as an iterator. Don't do that. :)
Here is an example of how you might use map to buil... |
Django Custom Queryset filters | 672,182 | 6 | 2009-03-23T03:53:41Z | 673,180 | 12 | 2009-03-23T12:21:14Z | [
"python",
"django",
"django-queryset",
"generator-expression"
] | Is there, in Django, a standard way to write complex, custom filters for QuerySets?
Just as I can write
```
MyClass.objects.all().filter(field=val)
```
I'd like to do something like this :
```
MyClass.objects.all().filter(customFilter)
```
I could use a generator expression
```
(x for x in MyClass.objects.all() i... | The recommendation to start using manager methods is a good one, but to answer your question more directly: yes, use [Q objects](http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects). For example:
```
from django.db.models import Q
complexQuery = Q(name__startswith='Xa') | ~Q(birthda... |
How do you send AT GSM commands using python? | 672,366 | 9 | 2009-03-23T06:11:02Z | 672,448 | 16 | 2009-03-23T07:08:33Z | [
"python",
"modem"
] | How do i send AT GSM commands using python?
Am able to do this quite easily using Delphi and some comport component (TComport), but how do i talk to my modem using python?
Gath | I do it like this with pyserial:
```
import serial
serialPort = serial.Serial(port=1,baudrate=115200,timeout=0,rtscts=0,xonxoff=0)
def sendatcmd(cmd):
serialPort.write('at'+cmd+'\r')
print 'Loading profile...',
sendatcmd('+npsda=0,2')
```
Then I listen for an answer... |
Python Programming - Rules/Advice for developing enterprise-level software in Python? | 672,781 | 7 | 2009-03-23T09:59:44Z | 672,975 | 16 | 2009-03-23T11:11:11Z | [
"java",
"python",
"design-patterns",
"programming-languages",
"dynamic-typing"
] | I'm a somewhat advanced C++/Java Developer who recently became interested in Python and I enjoy its dynamic typing and efficient coding style very much. I currently use it on my small programming needs like solving programming riddles and scripting, but I'm curious if anyone out there has successfully used Python in an... | I'm using Python for developing a complex insurance underwriting application.
Our application software essentially repackages our actuarial model in a form that companies can subscribe to it. This business is based on our actuaries and their deep thinking. We're not packaging a clever algorithm that's relatively fixed... |
File dialogs of Tkinter in Python 3? | 673,174 | 13 | 2009-03-23T12:20:01Z | 673,309 | 36 | 2009-03-23T13:11:44Z | [
"python",
"python-2.7",
"python-3.x",
"tkinter",
"dialog"
] | I want to select a file from a dialog box. [Here](http://www.java2s.com/Code/Python/GUI-Tk/Fileopendialog.htm) is code that does all I need, but when I run it:
`ImportError: No module named 'tkMessageBox'`
How can I make this example work with Python 3? | The package `Tkinter` has been renamed to `tkinter` in Python 3, as well as other modules related to it. Here are the name changes:
* `Tkinter` â `tkinter`
* `tkMessageBox` â `tkinter.messagebox`
* `tkColorChooser` â `tkinter.colorchooser`
* `tkFileDialog` â `tkinter.filedialog`
* `tkCommonDialog` â `tkinter... |
How to read from an os.pipe() without getting blocked? | 673,844 | 7 | 2009-03-23T15:27:53Z | 674,508 | 13 | 2009-03-23T17:54:55Z | [
"python",
"file",
"pipe"
] | I'm trying to read from an open `os.pipe()` to see if it's empty at the moment of the reading. The problem is that calling `read()` causes the program to block there until there is actually something to read there however there won't be any, if the test I'm doing succeeded.
I know I can use `select.select()` with a ti... | You might try this.
```
import os, fcntl
fcntl.fcntl(thePipe, fcntl.F_SETFL, os.O_NONBLOCK)
```
With this `thePipe.read()` should be non-blocking.
From [pipe(7)](http://man7.org/linux/man-pages/man7/pipe.7.html) man page:
> If a process attempts to read from an
> empty pipe, then read(2) will block
> until data is ... |
python: arbitrary order by | 673,867 | 3 | 2009-03-23T15:33:24Z | 673,892 | 13 | 2009-03-23T15:40:10Z | [
"python",
"order"
] | In Oracle sql there is a feature to order as follow:
```
order by decode("carrot" = 2
,"banana" = 1
,"apple" = 3)
```
What will be the best way to implement this in python?
I want to be able to order a dict on its keys. And that order isn't alphabetically or anything, I determine the or... | Use the `key` named keyword argument of `sorted()`.
```
#set up the order you want the keys to appear here
order = ["banana", "carrot", "apple"]
# this uses the order list to sort the actual keys.
sorted(keys, key=order.index)
```
For higher performance than `list.index`, you could use `dict.get` instead.
```
#this... |
Python list.index throws exception when index not found | 674,229 | 9 | 2009-03-23T16:58:07Z | 674,250 | 10 | 2009-03-23T17:02:18Z | [
"python",
"indexing",
"list"
] | Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this?
To me it looks cleaner to deal with special values, etc than exceptions.
EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None? | Because `-1` is itself a valid index. It could use a different value, such as `None`, but that wouldn't be useful, which `-1` can be in other situations (thus `str.find()`), and would amount simply to error-checking, which is exactly what exceptions are for. |
Python list.index throws exception when index not found | 674,229 | 9 | 2009-03-23T16:58:07Z | 674,268 | 7 | 2009-03-23T17:05:02Z | [
"python",
"indexing",
"list"
] | Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this?
To me it looks cleaner to deal with special values, etc than exceptions.
EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None? | To add to Devin's response: This is an old debate between special return values versus exceptions. Many programming gurus prefer an exception because on an exception, I get to see the whole stacktrace and immediate infer what is wrong. |
Python's use of __new__ and __init__? | 674,304 | 313 | 2009-03-23T17:13:01Z | 674,345 | 108 | 2009-03-23T17:20:19Z | [
"python",
"design-patterns",
"class-design"
] | I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.
However, I'm a bit confused as to why `__init__` is always called after `__new__`. I wasn't expecting this. Can anyone tell me why this is happening and how I implement this functio... | **`__new__`** is static class method, while **`__init__`** is instance method.
**`__new__`** has to create the instance first, so **`__init__`** can initialize it. Note that **`__init__`** takes **`self`** as parameter. Until you create instance there is no **`self`**.
Now, I gather, that you're trying to implement [s... |
Python's use of __new__ and __init__? | 674,304 | 313 | 2009-03-23T17:13:01Z | 674,369 | 332 | 2009-03-23T17:23:04Z | [
"python",
"design-patterns",
"class-design"
] | I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.
However, I'm a bit confused as to why `__init__` is always called after `__new__`. I wasn't expecting this. Can anyone tell me why this is happening and how I implement this functio... | > Use **\_\_new\_\_** when you need to control
> the creation of a new instance. Use
> **\_\_init\_\_** when you need to control initialization of a new instance.
>
> **\_\_new\_\_** is the first step of instance creation. It's called first, and is
> responsible for returning a new
> instance of your class. In contrast... |
Python's use of __new__ and __init__? | 674,304 | 313 | 2009-03-23T17:13:01Z | 674,399 | 14 | 2009-03-23T17:29:23Z | [
"python",
"design-patterns",
"class-design"
] | I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.
However, I'm a bit confused as to why `__init__` is always called after `__new__`. I wasn't expecting this. Can anyone tell me why this is happening and how I implement this functio... | To quote the [documentation](http://www.wingide.com/psupport/python-manual/2.4/ref/customization.html):
> Typical implementations create a new instance of the class by invoking
> the superclass's \_\_new\_\_() method using "super(currentclass,
> cls).\_\_new\_\_(cls[, ...])"with appropriate arguments and then
> modify... |
Python's use of __new__ and __init__? | 674,304 | 313 | 2009-03-23T17:13:01Z | 8,665,179 | 68 | 2011-12-29T07:39:47Z | [
"python",
"design-patterns",
"class-design"
] | I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.
However, I'm a bit confused as to why `__init__` is always called after `__new__`. I wasn't expecting this. Can anyone tell me why this is happening and how I implement this functio... | In most well-known OO languages, an expression like `SomeClass(arg1, arg2)` will allocate a new instance, initialise the instance's attributes, and then return it.
In most well-known OO languages, the "initialise the instance's attributes" part can be customised for each class by defining a **constructor**, which is b... |
How do I iterate over a Python dictionary, ordered by values? | 674,509 | 11 | 2009-03-23T17:55:11Z | 674,522 | 24 | 2009-03-23T17:59:20Z | [
"python"
] | I've got a dictionary like:
```
{ 'a': 6, 'b': 1, 'c': 2 }
```
I'd like to iterate over it *by value*, not by key. In other words:
```
(b, 1)
(c, 2)
(a, 6)
```
What's the most straightforward way? | ```
sorted(dictionary.items(), key=lambda x: x[1])
```
for these of you that hate lambda :-)
```
import operator
sorted(dictionary.items(), key=operator.itemgetter(1))
```
However `operator` version requires CPython 2.5+ |
How do I iterate over a Python dictionary, ordered by values? | 674,509 | 11 | 2009-03-23T17:55:11Z | 674,784 | 7 | 2009-03-23T19:02:36Z | [
"python"
] | I've got a dictionary like:
```
{ 'a': 6, 'b': 1, 'c': 2 }
```
I'd like to iterate over it *by value*, not by key. In other words:
```
(b, 1)
(c, 2)
(a, 6)
```
What's the most straightforward way? | For non-Python 3 programs, you'll want to use iteritems to get the performance boost of generators, which yield values one at a time instead of returning all of them at once.
```
sorted(d.iteritems(), key=lambda x: x[1])
```
For even larger dictionaries, we can go a step further and have the key function [be in C](ht... |
How can I convert a Python dictionary to a list of tuples? | 674,519 | 110 | 2009-03-23T17:58:32Z | 674,531 | 207 | 2009-03-23T18:01:38Z | [
"python"
] | If I have a dictionary like:
```
{ 'a': 1, 'b': 2, 'c': 3 }
```
How can I convert it to this?
```
[ ('a', 1), ('b', 2), ('c', 3) ]
```
And how can I convert it to this?
```
[ (1, 'a'), (2, 'b'), (3, 'c') ]
``` | ```
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
```
It's not in the order you want, but dicts don't have any specific order anyway. Sort it or organize it as necessary.
See: [items()](http://docs.python.org/libra... |
How can I convert a Python dictionary to a list of tuples? | 674,519 | 110 | 2009-03-23T17:58:32Z | 674,536 | 12 | 2009-03-23T18:02:50Z | [
"python"
] | If I have a dictionary like:
```
{ 'a': 1, 'b': 2, 'c': 3 }
```
How can I convert it to this?
```
[ ('a', 1), ('b', 2), ('c', 3) ]
```
And how can I convert it to this?
```
[ (1, 'a'), (2, 'b'), (3, 'c') ]
``` | You can use list comprehensions.
```
[(k,v) for k,v in a.iteritems()]
```
will get you [ ('a', 1), ('b', 2), ('c', 3) ] and
```
[(v,k) for k,v in a.iteritems()]
```
the other example.
[Read more about list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) if you like, it's ve... |
How can I convert a Python dictionary to a list of tuples? | 674,519 | 110 | 2009-03-23T17:58:32Z | 674,594 | 19 | 2009-03-23T18:19:15Z | [
"python"
] | If I have a dictionary like:
```
{ 'a': 1, 'b': 2, 'c': 3 }
```
How can I convert it to this?
```
[ ('a', 1), ('b', 2), ('c', 3) ]
```
And how can I convert it to this?
```
[ (1, 'a'), (2, 'b'), (3, 'c') ]
``` | since no one else did, I'll add py3k versions:
```
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.items()]
[(1, 'a'), (3, 'c'), (2, 'b')]
``` |
Python, __init__ and self confusion | 674,600 | 3 | 2009-03-23T18:20:44Z | 674,619 | 8 | 2009-03-23T18:23:11Z | [
"python",
"self",
"init"
] | Alright, so I was taking a look at some source when I came across this:
```
>>> def __parse(self, filename):
... "parse ID3v1.0 tags from MP3 file"
... self.clear()
... try:
... fsock = open(filename, "rb", 0)
... try:
... fsock.seek(-128, 2)
... ... | The `def __parse` was inside some class definition.
You can't pull the method defs out of the class definitions. The method function definition is part of the class.
Look at these two examples:
```
def add( a, b ):
return a + b
```
And
```
class Adder( object ):
def __init__( self ):
self.grand_tot... |
Examples for string find in Python | 674,764 | 45 | 2009-03-23T18:57:43Z | 674,774 | 87 | 2009-03-23T19:00:13Z | [
"python",
"string",
"find"
] | I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1. | I'm not sure what you're looking for, do you mean [`find()`](http://docs.python.org/library/stdtypes.html#str.find)?
```
>>> x = "Hello World"
>>> x.find('World')
6
>>> x.find('Aloha');
-1
``` |
Examples for string find in Python | 674,764 | 45 | 2009-03-23T18:57:43Z | 674,775 | 37 | 2009-03-23T19:00:24Z | [
"python",
"string",
"find"
] | I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1. | you can use [`str.index`](http://docs.python.org/library/stdtypes.html?highlight=index#str.index) too:
```
>>> 'sdfasdf'.index('cc')
Traceback (most recent call last):
File "<pyshell#144>", line 1, in <module>
'sdfasdf'.index('cc')
ValueError: substring not found
>>> 'sdfasdf'.index('df')
1
``` |
Examples for string find in Python | 674,764 | 45 | 2009-03-23T18:57:43Z | 674,781 | 14 | 2009-03-23T19:02:04Z | [
"python",
"string",
"find"
] | I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1. | Honestly, this is the sort of situation where I just open up Python on the command line and start messing around:
```
>>> x = "Dana Larose is playing with find()"
>>> x.find("Dana")
0
>>> x.find("ana")
1
>>> x.find("La")
5
>>> x.find("La", 6)
-1
```
Python's interpreter makes this sort of experimentation eas... |
Examples for string find in Python | 674,764 | 45 | 2009-03-23T18:57:43Z | 674,790 | 27 | 2009-03-23T19:03:50Z | [
"python",
"string",
"find"
] | I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1. | From [here](http://docs.python.org/library/stdtypes.html):
str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found."
So... |
OCR for sheet music | 675,077 | 17 | 2009-03-23T20:24:49Z | 1,872,875 | 8 | 2009-12-09T10:07:36Z | [
"python",
"ocr"
] | Im considering doing a small project as a part of my masters for doing ocr just for sheetmusic instead of text.
I think PIL and Python would be fine for simple proof of concept O"notes"R.
My question is: Has anyone got any "dont do it with PIL use xyz instead" or something in that alley?
EDIT: My delicius links rega... | My project ended with a report and some python software. Find it here:
* [Report](https://dl.dropboxusercontent.com/u/204603/Noder/project.latest.pdf)
* [Code](https://github.com/svrist/preomr)
The gist of it is: It is hard to do good OMR and takes a lot of effort. I didn't have the time to do complete OMR (and it lo... |
Is it possible to implement properties in languages other than C#? | 675,161 | 2 | 2009-03-23T20:43:04Z | 675,198 | 19 | 2009-03-23T20:54:43Z | [
"c#",
"php",
"javascript",
"python",
"properties"
] | During a bout of C# and WPF recently, I got to like C#'s properties:
```
public double length_inches
{
get { return length_metres * 39.0; }
set { length_metres = value/39.0; }
}
```
Noticing, of course, that length\_metres may change from being a field to a property, and the code need not care. WPF can also b... | Python definitely supports properties:
```
class Foo(object):
def get_length_inches(self):
return self.length_meters * 39.0
def set_length_inches(self, val):
self.length_meters = val/39.0
length_inches = property(get_length_inches, set_length_inches)
```
Starting in Python 2.5, syntacti... |
Is it possible to implement properties in languages other than C#? | 675,161 | 2 | 2009-03-23T20:43:04Z | 675,281 | 8 | 2009-03-23T21:21:40Z | [
"c#",
"php",
"javascript",
"python",
"properties"
] | During a bout of C# and WPF recently, I got to like C#'s properties:
```
public double length_inches
{
get { return length_metres * 39.0; }
set { length_metres = value/39.0; }
}
```
Noticing, of course, that length\_metres may change from being a field to a property, and the code need not care. WPF can also b... | In [JavaScript](https://developer.mozilla.org/En/Core%5FJavaScript%5F1.5%5FGuide:Creating%5FNew%5FObjects:Defining%5FGetters%5Fand%5FSetters):
```
var object = {
// .. other property definitions ...
get length_inches(){ return this.length_metres * 39.0; },
set length_inches(value){ this.length_metres = value/39.... |
Tab-completion in Python interpreter in OS X Terminal | 675,370 | 21 | 2009-03-23T21:48:29Z | 685,421 | 8 | 2009-03-26T11:47:57Z | [
"python",
"osx",
"configuration",
"interpreter",
"tab-completion"
] | Several months ago, I wrote a [blog post](http://igotgenes.blogspot.com/2009/01/tab-completion-and-history-in-python.html) detailing how to achieve tab-completion in the standard Python interactive interpreter--a feature I once thought only available in IPython. I've found it tremendously handy given that I sometimes h... | To avoid having to use more GPL code, Apple doesn't include a real readline. Instead it uses the BSD-licensed [libedit](http://www.thrysoee.dk/editline/), which is only mostly-readline-compatible. Build your own Python (or use Fink or MacPorts) if you want completion. |
Tab-completion in Python interpreter in OS X Terminal | 675,370 | 21 | 2009-03-23T21:48:29Z | 987,402 | 54 | 2009-06-12T15:43:41Z | [
"python",
"osx",
"configuration",
"interpreter",
"tab-completion"
] | Several months ago, I wrote a [blog post](http://igotgenes.blogspot.com/2009/01/tab-completion-and-history-in-python.html) detailing how to achieve tab-completion in the standard Python interactive interpreter--a feature I once thought only available in IPython. I've found it tremendously handy given that I sometimes h... | This should work under Leopard's python:
```
import rlcompleter
import readline
readline.parse_and_bind ("bind ^I rl_complete")
```
Whereas this one does not:
```
import readline, rlcompleter
readline.parse_and_bind("tab: complete")
```
Save it in ~/.pythonrc.py and execute in .bash\_profile
```
export PYTHONSTART... |
Tab-completion in Python interpreter in OS X Terminal | 675,370 | 21 | 2009-03-23T21:48:29Z | 1,258,115 | 11 | 2009-08-11T01:52:21Z | [
"python",
"osx",
"configuration",
"interpreter",
"tab-completion"
] | Several months ago, I wrote a [blog post](http://igotgenes.blogspot.com/2009/01/tab-completion-and-history-in-python.html) detailing how to achieve tab-completion in the standard Python interactive interpreter--a feature I once thought only available in IPython. I've found it tremendously handy given that I sometimes h... | here is a full cross platform version of loading tab completion for Windows/OS X/Linux in one shot:
```
#Code UUID = '9301d536-860d-11de-81c8-0023dfaa9e40'
import sys
try:
import readline
except ImportError:
try:
import pyreadline as readline
# throw open a browser if we fail b... |
Full examples of using pySerial package | 676,172 | 63 | 2009-03-24T04:38:58Z | 676,240 | 40 | 2009-03-24T05:26:04Z | [
"python",
"modem",
"pyserial"
] | Can someone please show me a full python sample code that uses **pyserial**, i have the package and am wondering how to send the AT commands and read them back! | ```
import serial
ser = serial.Serial(0) # open first serial port
print ser.portstr # check which port was really used
ser.write("hello") # write a string
ser.close() # close port
```
use <http://pyserial.wiki.sourceforge.net/pySerial> for more examples |
Full examples of using pySerial package | 676,172 | 63 | 2009-03-24T04:38:58Z | 7,654,527 | 66 | 2011-10-04T21:57:12Z | [
"python",
"modem",
"pyserial"
] | Can someone please show me a full python sample code that uses **pyserial**, i have the package and am wondering how to send the AT commands and read them back! | Blog post [Serial RS232 connections in Python](http://www.varesano.net/blog/fabio/serial%20rs232%20connections%20python)
```
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyUSB1',
baudrate=9600,
pa... |
Full examples of using pySerial package | 676,172 | 63 | 2009-03-24T04:38:58Z | 15,589,849 | 14 | 2013-03-23T17:29:18Z | [
"python",
"modem",
"pyserial"
] | Can someone please show me a full python sample code that uses **pyserial**, i have the package and am wondering how to send the AT commands and read them back! | <http://www.roman10.net/serial-port-communication-in-python/comment-page-1/#comment-1877>
```
#!/usr/bin/python
import serial, time
#initialization and open the port
#possible timeout values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float ... |
Python and text manipulation | 676,253 | 8 | 2009-03-24T05:36:54Z | 676,271 | 18 | 2009-03-24T05:51:36Z | [
"python",
"text"
] | I want to learn a text manipulation language and I have zeroed in on Python. Apart from text manipulation Python is also used for numerical applications, machine learning, AI, etc.
My question is how do I approach the learning of Python language so that I am quickly able to write sophisticated text manipulation utilit... | Beyond regular expressions here are some important features:
* Generators, see [Generator Tricks for Systems Programmers](http://www.dabeaz.com/generators-uk/) by David Beazley for a lot of great examples to pipeline unlimited amounts of text through generators.
For tools, I recommend looking at the following:
* [Wh... |
Are there any built-in cross-thread events in python? | 676,485 | 8 | 2009-03-24T08:04:41Z | 677,120 | 10 | 2009-03-24T12:11:51Z | [
"python",
"events",
"delegates"
] | Is there any built-in syntax in python that allows me to post a message to specific python thread inside my problem? Like 'queued connected signal' in pyQt or ::PostMessage() in Windows. I need this for asynchronous communication between program parts: there is a number of threads that handle network events and they ne... | The [Queue](http://docs.python.org/library/queue.html) module is python is well suited to what you're describing.
You could have one queue set up that is shared between all your threads. The threads that handle the network events can use queue.put to post events onto the queue. The logic thread would use queue.get to ... |
Is there a cross-platform python low-level API to capture or generate keyboard events? | 676,713 | 11 | 2009-03-24T09:48:25Z | 676,773 | 8 | 2009-03-24T10:15:09Z | [
"python",
"cross-platform",
"keyboard-events",
"low-level-api"
] | I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this could be handy to have Ctrl-@ mapped to "my.email@address", so that every time some program ... | There is no such API. My solution was to write a helper module which would use a different helper depending on the value of `os.name`.
On Windows, use the [Win32 extensions](http://python.net/crew/mhammond/win32/Downloads.html).
On Linux, things are a bit more complex since real OSes protect their users against keylo... |
condition coverage in python | 677,219 | 17 | 2009-03-24T12:47:09Z | 1,714,970 | 7 | 2009-11-11T12:44:20Z | [
"python",
"unit-testing",
"code-coverage"
] | Is there any tool/library that calculate percent of "condition/decision coverage" of python code. I found only coverage.py but it calculates only percent of "statement coverage". | [Coverage.py now includes branch coverage](http://nedbatchelder.com/code/coverage/branch.html).
For the curious: the code is not modified before running. The trace function tracks which lines follow which in the execution, and compare that information with static analysis of the compiled byte code to find path possibi... |
Python SVN bindings for Windows | 677,252 | 18 | 2009-03-24T12:58:01Z | 677,345 | 45 | 2009-03-24T13:18:35Z | [
"python",
"windows",
"svn",
"swig",
"precompiled"
] | Where can I find precompiled Python SWIG SVN bindings for Windows? | The (old) [Windows binaries](http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=8100) page at tigris.org contains an installer for *python bindings for SVN*. View the source for the SWIG bindings at [/trunk/subversion/bindings/swig/python](http://svn.apache.org/viewvc/subversion/trunk/subversion/binding... |
What's the best online tutorial for starting with Spring Python | 677,255 | 5 | 2009-03-24T12:58:23Z | 677,357 | 10 | 2009-03-24T13:19:51Z | [
"python",
"spring"
] | Spring Python seems to be the gold-standard for how to define good quality APIs in Python - it's based on Spring which also seems to be the gold-standard for Java APIs.
My manager has complained (with good reason) that our APIs are in a mess - we need to impose some order on them. Since we will be re-factoring it make... | How did you come to decide on Spring Python as your API of choice? Spring works well on Java where there's a tradition of declarative programming; defining your application primarily using XML to control a core engine is a standard pattern in Java.
In Python, while the underlying patterns like Inversion of Control are... |
distutils: How to pass a user defined parameter to setup.py? | 677,577 | 34 | 2009-03-24T14:12:04Z | 680,473 | 8 | 2009-03-25T06:48:40Z | [
"python",
"distutils"
] | Please prompt me how to pass a user-defined parameter both from the command line and setup.cfg configuration file to distutils' setup.py script. I want to write a setup.py script, which accepts my package specific parameters. For example:
```
python setup.py install -foo myfoo
```
Thank you,
Mher | You can't really pass custom parameters to the script. However the following things are possible and could solve your problem:
* optional features can be enabled using `--with-featurename`, standard features can be disabled using `--without-featurename`. [AFAIR this requires setuptools]
* you can use environment varia... |
distutils: How to pass a user defined parameter to setup.py? | 677,577 | 34 | 2009-03-24T14:12:04Z | 4,792,601 | 14 | 2011-01-25T10:54:17Z | [
"python",
"distutils"
] | Please prompt me how to pass a user-defined parameter both from the command line and setup.cfg configuration file to distutils' setup.py script. I want to write a setup.py script, which accepts my package specific parameters. For example:
```
python setup.py install -foo myfoo
```
Thank you,
Mher | Here is a very simple solution, all you have to do is filter out `sys.argv` and handle it yourself before you call to distutils `setup(..)`.
Something like this:
```
if "--foo" in sys.argv:
do_foo_stuff()
sys.argv.remove("--foo")
...
setup(..)
```
The documentation on how to do this with distutils is terrible... |
distutils: How to pass a user defined parameter to setup.py? | 677,577 | 34 | 2009-03-24T14:12:04Z | 20,248,942 | 29 | 2013-11-27T17:17:29Z | [
"python",
"distutils"
] | Please prompt me how to pass a user-defined parameter both from the command line and setup.cfg configuration file to distutils' setup.py script. I want to write a setup.py script, which accepts my package specific parameters. For example:
```
python setup.py install -foo myfoo
```
Thank you,
Mher | As Setuptools/Distuils are horribly documented, I had problems finding the answer to this myself. But eventually I stumbled across [this](http://marc.merlins.org/linux/talks/SvnScalingGvn/svn-tree/gvn-release/setup.py) example. Also, [this](http://stackoverflow.com/questions/1710839/custom-distutils-commands) similar q... |
How to extract from a list of objects a list of specific attribute? | 677,656 | 7 | 2009-03-24T14:31:43Z | 677,685 | 14 | 2009-03-24T14:36:50Z | [
"python"
] | I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class.
Is there any built-in functions to do that? | A list comprehension would work just fine:
```
[o.my_attr for o in my_list]
```
But there is a combination of built-in functions, since you ask :-)
```
from operator import attrgetter
map(attrgetter('my_attr'), my_list)
``` |
Specifying different template names in Django generic views | 677,793 | 2 | 2009-03-24T15:00:49Z | 678,441 | 8 | 2009-03-24T17:35:51Z | [
"python",
"django",
"django-urls"
] | I have the code in my urls.py for my generic views;
```
infodict = {
'queryset': Post.objects.all(),
'date_field': 'date',
'template_name': 'index.html',
'template_object_name': 'latest_post_list',
}
urlpatterns += patterns('django.views.generic.date_based',
(r'^gindex/$', 'archive_index', infodict),
)
```
So going ... | Use the dict() constructor:
```
infodict = {
'queryset': Post.objects.all(),
'date_field': 'date',
'template_name': 'index.html',
'template_object_name': 'latest_post_list',
}
urlpatterns = patterns('django.views.generic.date_based',
url(r'^gindex/$', 'archive_index', dict(infodict, template_name=... |
Doctest for dynamically created objects | 677,931 | 3 | 2009-03-24T15:30:12Z | 678,050 | 8 | 2009-03-24T15:53:03Z | [
"python",
"testing",
"sqlalchemy",
"doctest",
"docstring"
] | What is the best way to test code like this (the one below obviously fails while object is created in different block every time):
```
def get_session(db_name, verbose, test):
"""Returns current DB session from SQLAlchemy pool.
>>> get_session('Mmusc20090126', False, True)
<sqlalchemy.orm.session.Session object at 0x... | I think you want to use ellipsis, like this:
```
>>> get_session('Mmusc20090126', False, True) #doctest: +ELLIPSIS
<sqlalchemy.orm.session.Session object at 0x...>
```
See [here](http://docs.python.org/library/doctest.html#doctest.ELLIPSIS) for more info. |
How to get the filename without the extension from a path in Python? | 678,236 | 294 | 2009-03-24T16:41:03Z | 678,242 | 425 | 2009-03-24T16:43:15Z | [
"python",
"string",
"path"
] | How to get the filename without the extension from a path in Python?
I found out a method called `os.path.basename` to get the filename with extension. But even when I import os, I am not able to call it `path.basename`. Is it possible to call it as directly as basename? | Getting the name of the file without the extension :
```
import os
print(os.path.splitext("path_to_file")[0])
```
As for your import problem, you solve it this way :
```
from os.path import basename
# now you can call it directly with basename
print(basename("/a/b/c.txt"))
``` |
How to get the filename without the extension from a path in Python? | 678,236 | 294 | 2009-03-24T16:41:03Z | 678,247 | 7 | 2009-03-24T16:45:02Z | [
"python",
"string",
"path"
] | How to get the filename without the extension from a path in Python?
I found out a method called `os.path.basename` to get the filename with extension. But even when I import os, I am not able to call it `path.basename`. Is it possible to call it as directly as basename? | > But even when I import os, I am not able to call it path.basename. Is it possible to call it as directly as basename?
`import os`, and then use `os.path.basename`
`import`ing `os` doesn't mean you can use `os.foo` without referring to `os`. |
How to get the filename without the extension from a path in Python? | 678,236 | 294 | 2009-03-24T16:41:03Z | 678,266 | 143 | 2009-03-24T16:49:53Z | [
"python",
"string",
"path"
] | How to get the filename without the extension from a path in Python?
I found out a method called `os.path.basename` to get the filename with extension. But even when I import os, I am not able to call it `path.basename`. Is it possible to call it as directly as basename? | Just roll it:
```
>>> base=os.path.basename('/root/dir/sub/file.ext')
>>> base
'file.ext'
>>> os.path.splitext(base)
('file', '.ext')
>>> os.path.splitext(base)[0]
'file'
>>>
``` |
How to get the filename without the extension from a path in Python? | 678,236 | 294 | 2009-03-24T16:41:03Z | 1,228,618 | 91 | 2009-08-04T16:44:50Z | [
"python",
"string",
"path"
] | How to get the filename without the extension from a path in Python?
I found out a method called `os.path.basename` to get the filename with extension. But even when I import os, I am not able to call it `path.basename`. Is it possible to call it as directly as basename? | ```
>>> print os.path.splitext(os.path.basename("hemanth.txt"))[0]
hemanth
``` |
How to get the filename without the extension from a path in Python? | 678,236 | 294 | 2009-03-24T16:41:03Z | 19,488,791 | 9 | 2013-10-21T07:46:11Z | [
"python",
"string",
"path"
] | How to get the filename without the extension from a path in Python?
I found out a method called `os.path.basename` to get the filename with extension. But even when I import os, I am not able to call it `path.basename`. Is it possible to call it as directly as basename? | If you want to keep the path to the file and just remove the extension
```
>>> file = '/root/dir/sub.exten/file.data.1.2.dat'
>>> print ('.').join(file.split('.')[:-1])
/root/dir/sub.exten/file.data.1.2
``` |
How can I add non-sequential numbers to a range? | 678,410 | 5 | 2009-03-24T17:28:44Z | 678,421 | 21 | 2009-03-24T17:31:23Z | [
"python",
"range"
] | I am trying to iterate through the range(750, 765) and add the non-sequential numbers 769, 770, 774. If I try adding the numbers after the range function, it returns the range list, then the individual numbers:
```
>>> for x in range(750, 765), 769, 770, 774: print x
...
[750, 751, 752, 753, 754, 755, 756, 757, 758, ... | Use the built-in + operator to append your non-sequential numbers to the range.
```
for x in range(750, 765) + [769, 770, 774]: print x
``` |
How can I add non-sequential numbers to a range? | 678,410 | 5 | 2009-03-24T17:28:44Z | 678,429 | 13 | 2009-03-24T17:33:50Z | [
"python",
"range"
] | I am trying to iterate through the range(750, 765) and add the non-sequential numbers 769, 770, 774. If I try adding the numbers after the range function, it returns the range list, then the individual numbers:
```
>>> for x in range(750, 765), 769, 770, 774: print x
...
[750, 751, 752, 753, 754, 755, 756, 757, 758, ... | There are two ways to do it.
```
>>> for x in range(5, 7) + [8, 9]: print x
...
5
6
8
9
>>> import itertools
>>> for x in itertools.chain(xrange(5, 7), [8, 9]): print x
...
5
6
8
9
```
[itertools.chain()](http://docs.python.org/library/itertools.html#itertools.chain) is by far superior, since it allows you to use arb... |
Select Distinct Years and Months for Django Archive Page | 678,927 | 7 | 2009-03-24T19:37:30Z | 679,105 | 28 | 2009-03-24T20:26:37Z | [
"python",
"django",
"datetime",
"django-views",
"django-queryset"
] | I want to make an archive\_index page for my django site. However, the date-based generic views really aren't any help. I want the dictionary returned by the view to have all the years and months for which at least one instance of the object type exists. So if my blog started in September 2007, but there were no posts ... | This will give you a list of unique posting dates:
```
Posts.objects.filter(draft=False).dates('post_date','month',order='DESC')
```
Of course you might not need the draft filter, and change 'post\_date' to your field name, etc. |
Select Distinct Years and Months for Django Archive Page | 678,927 | 7 | 2009-03-24T19:37:30Z | 679,164 | 9 | 2009-03-24T20:39:09Z | [
"python",
"django",
"datetime",
"django-views",
"django-queryset"
] | I want to make an archive\_index page for my django site. However, the date-based generic views really aren't any help. I want the dictionary returned by the view to have all the years and months for which at least one instance of the object type exists. So if my blog started in September 2007, but there were no posts ... | I found the answer to my own question.
[It's on this page](http://docs.djangoproject.com/en/dev/ref/models/querysets/) in the documentation.
There's a function called dates that will give you distinct dates. So I can do
Entry.objects.dates('pub\_date','month') to get a list of datetime objects, one for each year/mon... |
Best way to profile/optimize a website on google's appengine | 679,670 | 15 | 2009-03-24T23:27:38Z | 680,832 | 13 | 2009-03-25T09:24:50Z | [
"python",
"google-app-engine"
] | I'm currently trying to optimize my website, which run on the google's appengine. It's not an easy task, because I'm not using any powerful tool.
Does anyone have experience in optimizing python code for this purpose?
Have you find a good python profiler? | I have found [Gprof2Dot](http://code.google.com/p/jrfonseca/wiki/Gprof2Dot) extremely useful. The output of the profiling modules I've tried as pretty unintuitive to interpret.
Gprof2Dot turns the cProfile output into a pretty looking graph, with the slowest chain(?) highlighted, and a bit of information on each funct... |
Best way to profile/optimize a website on google's appengine | 679,670 | 15 | 2009-03-24T23:27:38Z | 6,809,225 | 8 | 2011-07-24T19:49:08Z | [
"python",
"google-app-engine"
] | I'm currently trying to optimize my website, which run on the google's appengine. It's not an easy task, because I'm not using any powerful tool.
Does anyone have experience in optimizing python code for this purpose?
Have you find a good python profiler? | [App Engine Mini Profiler](https://github.com/kamens/gae_mini_profiler) is a new, drop-in app engine performance tool that gives both API call perf information (via Appstats) and standard profiling data for all function calls (via cProfiler)
<https://github.com/kamens/gae_mini_profiler> |
min heap in python | 679,731 | 9 | 2009-03-24T23:52:58Z | 679,742 | 12 | 2009-03-25T00:01:28Z | [
"python",
"object",
"heap",
"min-heap"
] | I'd like to store a set of objects in a min heap by defining a custom comparison function. I see there is a heapq module available as part of the python distribution. Is there a way to use a custom comparator with this module? If not, has someone else built a custom min heap? | Yes, there is a way. Define a wrapping class that implements your custom comparator, and use a list of those instead of a list of your actual objects. That's about the best there is while still using the heapq module, since it provides no key= or cmp= arguments like the sorting functions/methods do.
```
def gen_wrappe... |
min heap in python | 679,731 | 9 | 2009-03-24T23:52:58Z | 679,831 | 15 | 2009-03-25T00:49:56Z | [
"python",
"object",
"heap",
"min-heap"
] | I'd like to store a set of objects in a min heap by defining a custom comparison function. I see there is a heapq module available as part of the python distribution. Is there a way to use a custom comparator with this module? If not, has someone else built a custom min heap? | Two options (aside from Devin Jeanpierre's suggestion):
1. Decorate your data before using the heap. This is the equivalent of the `key=` option to sorting. e.g. if you (for some reason) wanted to heapify a list of numbers according to their sine:
```
data = [ # list of numbers ]
heap = [(math.sin(x), x) for... |
What are the viable database abstraction layers for Python | 679,806 | 11 | 2009-03-25T00:34:50Z | 679,814 | 18 | 2009-03-25T00:40:50Z | [
"python",
"sql",
"mysql",
"database",
"sqlite"
] | I'm starting to get involved in an open source project [Gramps](http://www.gramps-project.org/wiki/index.php?title=Main%5FPage) which is exploring switching their backend from BSDDB to a relational database. Either SQLite or MySQL we haven't fully decided and may even try to do both in some limited capacity. I'm a prof... | Look very closely at SQLAlchemy.
You can test and develop with SQLite.
You can go into production with MySQL -- making essentially no changes to your applications.
The DB-API, while widely adhered-to, has enough flexibility that (1) you aren't insulated from SQL variation in the underlying RDBMS and (2) there are st... |
Python: How to extract variable name of a dictionary entry? | 680,032 | 2 | 2009-03-25T02:36:07Z | 680,051 | 9 | 2009-03-25T02:47:39Z | [
"python",
"dictionary",
"variables",
"lookup"
] | I'm wondering how I would go about finding the variable name of a dictionary element:
For example:
```
>>>dict1={}
>>>dict2={}
>>>dict1['0001']='0002'
>>>dict2['nth_dict_item']=dict1
>>>print dict2
{'nth_dict_item': {'0001': '0002'}}
>>>print dict2['nth_dict_item']
{'001': '002'}
```
... | A variable name is just a name--it has no real meaning as far as the program is concerned, except as a convenience to the programmer (this isn't quite true in Python, but bear with me). As far as the Python interpreter is concerned, the name `dict1` is just the programmer's way of telling Python to look at memory addre... |
Python: How to extract variable name of a dictionary entry? | 680,032 | 2 | 2009-03-25T02:36:07Z | 680,101 | 7 | 2009-03-25T03:11:28Z | [
"python",
"dictionary",
"variables",
"lookup"
] | I'm wondering how I would go about finding the variable name of a dictionary element:
For example:
```
>>>dict1={}
>>>dict2={}
>>>dict1['0001']='0002'
>>>dict2['nth_dict_item']=dict1
>>>print dict2
{'nth_dict_item': {'0001': '0002'}}
>>>print dict2['nth_dict_item']
{'001': '002'}
```
... | To add what zenazn said:
> But how can I turn that id back into a variable name?
The short answer is that you don't want really want to. If you think you need to, there's something very wrong with the design of your program. If you told us more concretely what problem you were trying to solve, we could help you work ... |
Using MultipartPostHandler to POST form-data with Python | 680,305 | 44 | 2009-03-25T05:14:37Z | 681,182 | 29 | 2009-03-25T11:29:54Z | [
"python",
"file",
"upload",
"urllib2",
"multipartform-data"
] | Problem: When POSTing data with Python's urllib2, all data is URL encoded and sent as Content-Type: application/x-www-form-urlencoded. When uploading files, the Content-Type should instead be set to multipart/form-data and the contents be MIME encoded. A discussion of this problem is here:
<http://code.activestate.com/... | Found this recipe to post multipart using `httplib` directly (no external libraries involved)
```
import httplib
import mimetypes
def post_multipart(host, selector, fields, files):
content_type, body = encode_multipart_formdata(fields, files)
h = httplib.HTTP(host)
h.putrequest('POST', selector)
h.put... |
Using MultipartPostHandler to POST form-data with Python | 680,305 | 44 | 2009-03-25T05:14:37Z | 688,193 | 55 | 2009-03-27T01:31:25Z | [
"python",
"file",
"upload",
"urllib2",
"multipartform-data"
] | Problem: When POSTing data with Python's urllib2, all data is URL encoded and sent as Content-Type: application/x-www-form-urlencoded. When uploading files, the Content-Type should instead be set to multipart/form-data and the contents be MIME encoded. A discussion of this problem is here:
<http://code.activestate.com/... | It seems that the easiest and most compatible way to get around this problem is to use the 'poster' module.
```
# test_client.py
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
# Register the streaming http handlers with urllib2
register_openers()
# Start t... |
Using MultipartPostHandler to POST form-data with Python | 680,305 | 44 | 2009-03-25T05:14:37Z | 18,120,930 | 24 | 2013-08-08T08:04:24Z | [
"python",
"file",
"upload",
"urllib2",
"multipartform-data"
] | Problem: When POSTing data with Python's urllib2, all data is URL encoded and sent as Content-Type: application/x-www-form-urlencoded. When uploading files, the Content-Type should instead be set to multipart/form-data and the contents be MIME encoded. A discussion of this problem is here:
<http://code.activestate.com/... | Just use [**python-requests**](http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file), it will set proper headers and do upload for you:
```
import requests
files = {"form_input_field_name": open("filename", "rb")}
requests.post("http://httpbin.org/post", files=files)
``` |
Python dynamic function names | 680,941 | 9 | 2009-03-25T10:04:26Z | 680,954 | 35 | 2009-03-25T10:08:32Z | [
"python",
"factory"
] | I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function
```
if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
... | you might find [`getattr`](http://docs.python.org/library/functions.html?highlight=getattr#getattr) useful, I guess
```
import module
getattr(module, status.lower())(*args, **kwargs)
``` |
Python dynamic function names | 680,941 | 9 | 2009-03-25T10:04:26Z | 680,958 | 15 | 2009-03-25T10:10:11Z | [
"python",
"factory"
] | I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function
```
if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
... | assuming that these functions belong to some module:
```
import module
return getattr(module, status.lower()).__call__(*args, **kwargs)
``` |
Python dynamic function names | 680,941 | 9 | 2009-03-25T10:04:26Z | 680,967 | 15 | 2009-03-25T10:13:15Z | [
"python",
"factory"
] | I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function
```
if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
... | The canonical way to do this is to use a dictionary to emulate `switch` or `if/elif`. You will find several questions to similar problems here on SO.
Put your functions into a dictionary with your status codes as keys:
```
funcs = {
'CONNECT': connect,
'RAWFEED': rawfeed,
'RAWCONFIG' : rawconfig,
'TES... |
Whats the difference between list[-1:][0] and list[len(list)-1]? | 681,123 | 7 | 2009-03-25T11:11:46Z | 681,135 | 14 | 2009-03-25T11:15:40Z | [
"python",
"list",
"slice"
] | Lest say you want the last element of a python list: what is the difference between
```
myList[-1:][0]
```
and
```
myList[len(myList)-1]
```
I thought there was no difference but then I tried this
```
>>> list = [0]
>>> list[-1:][0]
0
>>> list[-1:][0] += 1
>>> list
[0]
>>> list[len(list)-1] += 1
>>> list
[1]
```
... | if you use slicing [-1:], the returned list is a shallow-copy, not reference. so [-1:][0] modifies the new list. [len(list)-1] is reference to last object. |
Whats the difference between list[-1:][0] and list[len(list)-1]? | 681,123 | 7 | 2009-03-25T11:11:46Z | 681,138 | 9 | 2009-03-25T11:17:16Z | [
"python",
"list",
"slice"
] | Lest say you want the last element of a python list: what is the difference between
```
myList[-1:][0]
```
and
```
myList[len(myList)-1]
```
I thought there was no difference but then I tried this
```
>>> list = [0]
>>> list[-1:][0]
0
>>> list[-1:][0] += 1
>>> list
[0]
>>> list[len(list)-1] += 1
>>> list
[1]
```
... | `list[-1:]` creates a new list. To get the same behaviour as `list[len(list)-1]` it would have to return a view of some kind of `list`, but as I said, it creates a new temporary list. You then proceed to edit the temporary list.
Anyway, you know you can use `list[-1]` for the same thing, right? |
Nullable ForeignKeys and deleting a referenced model instance | 681,497 | 7 | 2009-03-25T13:06:42Z | 681,614 | 13 | 2009-03-25T13:31:54Z | [
"python",
"django",
"django-models"
] | I have a ForeignKey which can be null in my model to model a loose coupling between the models. It looks somewhat like that:
```
class Message(models.Model):
sender = models.ForeignKey(User, null=True, blank=True)
sender_name = models.CharField(max_length=255)
```
On save the senders name is written to the sender... | Django does indeed emulate SQL's `ON DELETE CASCADE` behaviour, and there's no out-of-the box documented way to change this. The docs where they mention this are near the end of this section: [Deleting objects](http://docs.djangoproject.com/en/dev/topics/db/queries/#deleting-objects).
You are right that Django's colle... |
How is string.find implemented in CPython? | 681,649 | 6 | 2009-03-25T13:41:42Z | 681,666 | 15 | 2009-03-25T13:49:00Z | [
"python"
] | I was wondering if the 'find' method on strings was implemented with a linear search, or if python did something more sophisticated. The Python documentation doesn't discuss implementation details, so <http://docs.python.org/library/stdtypes.html> is of no help. Could someone please point me to the relevant source code... | I suppose so:
> [fast search/count implementation,
> based on a mix between boyer-moore
> and horspool, with a few more bells
> and whistles on the top](http://svn.python.org/view/python/trunk/Objects/stringlib/fastsearch.h?revision=68811&view=markup) |
Python Class Decorator | 681,953 | 89 | 2009-03-25T14:52:02Z | 681,999 | 11 | 2009-03-25T15:01:38Z | [
"python",
"decorator",
"python-2.5"
] | In Python 2.5, is there a way to create a decorator that decorates a class? Specifically, I want to use a decorator to add a member to a class and change the constructor to take a value for that member.
Looking for something like the following (which has a syntax error on 'class Foo:':
```
def getId(self): return sel... | That's not a good practice and there is no mechanism to do that because of that. The right way to accomplish what you want is inheritance.
Take a look into the [class documentation](http://docs.python.org/tutorial/classes.html#inheritance).
A little example:
```
class Employee(object):
def __init__(self, age, s... |
Python Class Decorator | 681,953 | 89 | 2009-03-25T14:52:02Z | 682,052 | 62 | 2009-03-25T15:14:34Z | [
"python",
"decorator",
"python-2.5"
] | In Python 2.5, is there a way to create a decorator that decorates a class? Specifically, I want to use a decorator to add a member to a class and change the constructor to take a value for that member.
Looking for something like the following (which has a syntax error on 'class Foo:':
```
def getId(self): return sel... | I would second the notion that you may wish to consider a subclass instead of the approach you've outlined. However, not knowing your specific scenario, YMMV :-)
What you're thinking of is a metaclass. The `__new__` function in a metaclass is passed the full proposed definition of the class, which it can then rewrite ... |
Python Class Decorator | 681,953 | 89 | 2009-03-25T14:52:02Z | 682,242 | 168 | 2009-03-25T15:58:22Z | [
"python",
"decorator",
"python-2.5"
] | In Python 2.5, is there a way to create a decorator that decorates a class? Specifically, I want to use a decorator to add a member to a class and change the constructor to take a value for that member.
Looking for something like the following (which has a syntax error on 'class Foo:':
```
def getId(self): return sel... | Apart from the question whether class decorators are the right solution to your problem:
in Python 2.6 and higher, there are class decorators with the @-syntax, so you can write:
```
@addID
class Foo:
pass
```
in older versions, you can do it another way:
```
class Foo:
pass
Foo = addID(Foo)
```
Note howe... |
Python Class Decorator | 681,953 | 89 | 2009-03-25T14:52:02Z | 18,938,008 | 8 | 2013-09-21T21:47:44Z | [
"python",
"decorator",
"python-2.5"
] | In Python 2.5, is there a way to create a decorator that decorates a class? Specifically, I want to use a decorator to add a member to a class and change the constructor to take a value for that member.
Looking for something like the following (which has a syntax error on 'class Foo:':
```
def getId(self): return sel... | no-one has explained that you can dynamically define classes. so you can have a decorator that defines (and returns) a subclass:
```
def addId(cls):
class AddId(cls):
def __init__(self, id, *args, **kargs):
super(AddId, self).__init__(*args, **kargs)
self.__id = id
def ge... |
Which version of python added the else clause for for loops? | 682,185 | 11 | 2009-03-25T15:48:24Z | 682,234 | 7 | 2009-03-25T15:57:15Z | [
"python",
"for-loop"
] | Which was the first version of python to include the [else clause for for loops](http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)?
I find that the python docs usually does a good job of documenting when features were added, but I can't seem to find the info on t... | It's been around since at least [1.4](http://www.python.org/doc/1.4/ref/ref7.html#HDR2), which is the [oldest version of the documentation](http://www.python.org/doc/versions/) I know of. |
Which version of python added the else clause for for loops? | 682,185 | 11 | 2009-03-25T15:48:24Z | 684,134 | 28 | 2009-03-26T01:05:03Z | [
"python",
"for-loop"
] | Which was the first version of python to include the [else clause for for loops](http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)?
I find that the python docs usually does a good job of documenting when features were added, but I can't seem to find the info on t... | It's been present since the beginning. To see that, get the source from alt.sources, specifically the message titled "[Python 0.9.1 part 17/21](http://groups.google.com/group/alt.sources/browse_thread/thread/74a577bbcfc4be0a/cbaaec4fbfebbbb6)". The date is Feb 21, 1991. This post included the grammar definition, which ... |
Splitting out the output of ps using Python | 682,446 | 9 | 2009-03-25T16:50:57Z | 682,464 | 19 | 2009-03-25T16:53:31Z | [
"python",
"regex",
"linux"
] | On Linux, the command ps aux outputs a list of processes with multiple columns for each stat. e.g.
```
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
...
postfix 22611 0.0 0.2 54136 2544 ? S 15:26 0:00 pickup -l -t fifo -u
apache 22920 0.0 1.5 198340 16588 ? S 0... | Use the second parameter to `split` which specifies the maximum number of fields to split the string into. I guess you can find the number by counting the number of fields in the first line, i.e. the column titles.
```
ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('... |
Splitting out the output of ps using Python | 682,446 | 9 | 2009-03-25T16:50:57Z | 3,367,742 | 11 | 2010-07-29T23:27:40Z | [
"python",
"regex",
"linux"
] | On Linux, the command ps aux outputs a list of processes with multiple columns for each stat. e.g.
```
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
...
postfix 22611 0.0 0.2 54136 2544 ? S 15:26 0:00 pickup -l -t fifo -u
apache 22920 0.0 1.5 198340 16588 ? S 0... | Check out the [python.psutils](http://pypi.python.org/pypi/psutil/) package.
`psutil.process_iter` returns a generator which you can use to iterate over all processes.
`p.cmdline` is a list of each Process object's cmdline arguments, separated just the way you want.
You can create a dictionary of pids vs `(pid,cmdlin... |
What is a clean, pythonic way to have multiple constructors in Python? | 682,504 | 385 | 2009-03-25T17:00:21Z | 682,513 | 542 | 2009-03-25T17:03:38Z | [
"coding-style",
"python"
] | I can't find a definitive answer for this. AFAIK, you can't have multiple `__init__` functions in a Python class. So what is a good way to solve this problem?
Suppose I have an class called `Cheese` with the `number_of_holes` property. How can I have two ways of creating cheese-objects...
* one that takes a number of... | Actually `None` is much better for "magic" values:
```
class Cheese():
def __init__(self, num_holes = None):
if num_holes is None:
...
```
Now if you want complete freedom of adding more parameters:
```
class Cheese():
def __init__(self, *args, **kwargs):
#args -- tuple of anonymo... |
What is a clean, pythonic way to have multiple constructors in Python? | 682,504 | 385 | 2009-03-25T17:00:21Z | 682,545 | 356 | 2009-03-25T17:11:24Z | [
"coding-style",
"python"
] | I can't find a definitive answer for this. AFAIK, you can't have multiple `__init__` functions in a Python class. So what is a good way to solve this problem?
Suppose I have an class called `Cheese` with the `number_of_holes` property. How can I have two ways of creating cheese-objects...
* one that takes a number of... | Using `num_holes=None` as the default is fine if you are going to have just `__init__`.
If you want multiple, independent "constructors", you can provide these as class methods. These are usually called factory methods. In this case you could have the default for `num_holes` be `0`.
```
class Cheese(object):
def ... |
What is a clean, pythonic way to have multiple constructors in Python? | 682,504 | 385 | 2009-03-25T17:00:21Z | 682,546 | 14 | 2009-03-25T17:11:35Z | [
"coding-style",
"python"
] | I can't find a definitive answer for this. AFAIK, you can't have multiple `__init__` functions in a Python class. So what is a good way to solve this problem?
Suppose I have an class called `Cheese` with the `number_of_holes` property. How can I have two ways of creating cheese-objects...
* one that takes a number of... | Why do you think your solution is "clunky"? Personally I would prefer one constructor with default values over multiple overloaded constructors in situations like yours (Python does not support method overloading anyway):
```
def __init__(self, num_holes=None):
if num_holes is None:
# Construct a gouda
... |
What is a clean, pythonic way to have multiple constructors in Python? | 682,504 | 385 | 2009-03-25T17:00:21Z | 682,563 | 13 | 2009-03-25T17:16:04Z | [
"coding-style",
"python"
] | I can't find a definitive answer for this. AFAIK, you can't have multiple `__init__` functions in a Python class. So what is a good way to solve this problem?
Suppose I have an class called `Cheese` with the `number_of_holes` property. How can I have two ways of creating cheese-objects...
* one that takes a number of... | All of these answers are excellent if you want to use optional parameters, but another Pythonic possibility is to use a classmethod to generate a factory-style pseudo-constructor:
```
def __init__(self, num_holes):
# do stuff with the number
@classmethod
def fromRandom(cls):
return cls( # some-random-number )
`... |
What is a clean, pythonic way to have multiple constructors in Python? | 682,504 | 385 | 2009-03-25T17:00:21Z | 683,155 | 8 | 2009-03-25T19:48:35Z | [
"coding-style",
"python"
] | I can't find a definitive answer for this. AFAIK, you can't have multiple `__init__` functions in a Python class. So what is a good way to solve this problem?
Suppose I have an class called `Cheese` with the `number_of_holes` property. How can I have two ways of creating cheese-objects...
* one that takes a number of... | The best answer is the one above about default arguments, but I had fun writing this, and it certainly does fit the bill for "multiple constructors". Use at your own risk.
What about the [**new**](http://docs.python.org/reference/datamodel.html#object.%5F%5Fnew%5F%5F) method.
"Typical implementations create a new ins... |
What is a clean, pythonic way to have multiple constructors in Python? | 682,504 | 385 | 2009-03-25T17:00:21Z | 7,891,419 | 11 | 2011-10-25T15:06:03Z | [
"coding-style",
"python"
] | I can't find a definitive answer for this. AFAIK, you can't have multiple `__init__` functions in a Python class. So what is a good way to solve this problem?
Suppose I have an class called `Cheese` with the `number_of_holes` property. How can I have two ways of creating cheese-objects...
* one that takes a number of... | Those are good ideas for your implementation, but if you are presenting a cheese making interface to a user. They don't care how many holes the cheese has or what internals go into making cheese. The user of your code just wants "gouda" or "parmesean" right?
So why not do this:
```
# cheese_user.py
from cheeses impor... |
Python Virtual Machine architecture diagrams/references | 682,675 | 10 | 2009-03-25T17:42:49Z | 682,897 | 9 | 2009-03-25T18:36:39Z | [
"python",
"architecture",
"language-design",
"vm-implementation"
] | Someone could point out sites/books where I can find introductory documentation about the architecture of the Python VM?
I'm interested in the C version, but if there are easy-to-follow references about other implementations it could be helpful too.
I'm trying to find any kind of resources of higher level than plain ... | You should be able to find the information you need at <http://svn.python.org/view/python/trunk/Python/ceval.c?view=markup>
If that's too low level for you, try
* <http://www.python.org/dev/peps/pep-0339/>
* <http://codespeak.net/pypy/dist/pypy/doc/interpreter.html>
* <http://thermalnoise.wordpress.com/2007/12/30/exp... |
What to do with "The input line is too long" error message? | 682,799 | 10 | 2009-03-25T18:08:42Z | 3,583,282 | 16 | 2010-08-27T10:29:48Z | [
"python",
"command-line",
"windows-console"
] | I am trying to use os.system() to call another program that takes an input and an output file. The command I use is ~250 characters due to the long folder names.
When I try to call the command, I'm getting an error: `The input line is too long`.
I'm guessing there's a `255 character limit` (its built using a C system... | Even it's a good idea to use `subprocess.Popen()`, this does not solve the issue.
**Your problem is not the 255 characters limit**, this was true on DOS times, later increased to 2048 for Windows NT/2000, and increased again to 8192 for Windows XP+.
The **real solution** is to workaround a very old bug in Windows API... |
Redirecting function definitions in python | 682,822 | 2 | 2009-03-25T18:14:49Z | 682,877 | 7 | 2009-03-25T18:29:16Z | [
"python",
"class-attributes"
] | This is a very contrived example as it's not easy to explain the context in which I have ended up implementing this solution. However, if anyone can answer why this particular peculiarity happens, I'd be grateful.
The example:
```
class A(dict):
def __init__(self):
self['a'] = 'success'
def __getitem_... | When you use brackets *`[]`* python looks in the class. You must set the method in the class.
Here's your code adapted:
```
class A(dict):
def __init__(self):
self['a'] = 'success'
def __getitem__(self, name):
print 'getitem!'
return dict.__getitem__(self, name)
class B(object):
... |
Dynamically change the choices in a wx.ComboBox() | 682,923 | 13 | 2009-03-25T18:42:34Z | 682,978 | 23 | 2009-03-25T18:58:43Z | [
"python",
"wxpython",
"wxwidgets"
] | I didn't find a better way to change the different choices in a wx.ComboBox() than swap the old ComboBox with a new one. Is there a better way?
Oerjan Pettersen
```
#!/usr/bin/python
#20_combobox.py
import wx
import wx.lib.inspection
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame._... | [wx.ComboBox](http://docs.wxwidgets.org/stable/classwx_combo_box.html) derives from [wx.ItemContainer](http://docs.wxwidgets.org/stable/classwx_item_container.html), which has methods for [Appending](http://docs.wxwidgets.org/stable/classwx_item_container.html#a8fdc0090e3eabc762ff0e49e925f8bc4), [Clearing](http://docs.... |
Best way to integrate Python and JavaScript? | 683,462 | 44 | 2009-03-25T21:08:11Z | 683,481 | 15 | 2009-03-25T21:13:09Z | [
"javascript",
"python"
] | Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if **anyone has done it within a "serious" project or product**.
I'm guessi... | Here's something, a Python wrapper around the SeaMonkey Javascript interpreter... <http://pypi.python.org/pypi/python-spidermonkey> |
Best way to integrate Python and JavaScript? | 683,462 | 44 | 2009-03-25T21:08:11Z | 683,682 | 21 | 2009-03-25T22:00:23Z | [
"javascript",
"python"
] | Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if **anyone has done it within a "serious" project or product**.
I'm guessi... | How about [pyjs](http://pyjs.org/)?
From the above website:
> pyjs is a Rich Internet Application (RIA) Development Platform for both Web and Desktop. With pyjs you can write your JavaScript-powered web applications entirely in Python. |
Best way to integrate Python and JavaScript? | 683,462 | 44 | 2009-03-25T21:08:11Z | 731,196 | 8 | 2009-04-08T18:18:28Z | [
"javascript",
"python"
] | Is it possible to integrate Python and JavaScript? For example, imagine you wanted to be able to define classes in JavaScript and use them from Python (or vice versa). If so, what's the best way? I'm interested not only if this is possible but if **anyone has done it within a "serious" project or product**.
I'm guessi... | there are two projects that allow an "obvious" transition between python objects and javascript objects, with "obvious" translations from int or float to Number and str or unicode to String: [PyV8](http://code.google.com/p/pyv8) and, as one writer has already mentioned: [python-spidermonkey](http://pypi.python.org/pypi... |
How to save an xml file to disk? | 683,494 | 2 | 2009-03-25T21:17:56Z | 683,505 | 11 | 2009-03-25T21:19:59Z | [
"python",
"xml"
] | I did something similar to [this](http://www.postneo.com/projects/pyxml/), but couldn't find a way to write the result to an xml file. | The code on the web page you linked to uses `doc.toprettyxml` to create a string from the XML DOM, so you can just write that string to a file:
```
f = open("output.xml", "w")
try:
f.write(doc.toprettyxml(indent=" "))
finally:
f.close()
```
In Python 2.6 (or 2.7 I suppose, whenever it comes out), you can use... |
How to save an xml file to disk? | 683,494 | 2 | 2009-03-25T21:17:56Z | 683,978 | 8 | 2009-03-25T23:43:41Z | [
"python",
"xml"
] | I did something similar to [this](http://www.postneo.com/projects/pyxml/), but couldn't find a way to write the result to an xml file. | coonj is kind of right, but xml.dom.ext.PrettyPrint is part of the increasingly neglected PyXML extension package. If you want to stay within the supplied-as-standard minidom, you'd say:
```
f= open('yourfile.xml', 'wb')
doc.writexml(f, encoding= 'utf-8')
f.close()
```
(Or using the âwithâ statement as mentioned ... |
how to put a function and arguments into python queue? | 683,542 | 8 | 2009-03-25T21:27:52Z | 683,611 | 20 | 2009-03-25T21:46:41Z | [
"python",
"multithreading"
] | I have a python program with 2 threads ( let's name them 'source' and
'destination' ). Source thread sometimes post a message to destination
thread with some arguments. Than destination thread picks a message it
must call a corresponding function with aruments saved in message.
This task can be solved multiple ways. T... | So simple:
```
def DestinationThread( a ) :
while True :
items = q.get()
func = items[0]
args = items[1:]
func(*args)
``` |
how to put a function and arguments into python queue? | 683,542 | 8 | 2009-03-25T21:27:52Z | 683,612 | 7 | 2009-03-25T21:46:45Z | [
"python",
"multithreading"
] | I have a python program with 2 threads ( let's name them 'source' and
'destination' ). Source thread sometimes post a message to destination
thread with some arguments. Than destination thread picks a message it
must call a corresponding function with aruments saved in message.
This task can be solved multiple ways. T... | ```
from Queue import *
from thread import *
from time import *
q = Queue()
def HandleMsg( arg1, arg2 ) :
print arg1, arg2
def HandleAnotherMsg( arg1, arg2, arg3 ) :
print arg1, arg2, arg3
def DestinationThread() :
while True :
f, args = q.get()
f(*args)
start_new_thread( DestinationThread, tuple() )... |
how to put a function and arguments into python queue? | 683,542 | 8 | 2009-03-25T21:27:52Z | 683,969 | 10 | 2009-03-25T23:41:43Z | [
"python",
"multithreading"
] | I have a python program with 2 threads ( let's name them 'source' and
'destination' ). Source thread sometimes post a message to destination
thread with some arguments. Than destination thread picks a message it
must call a corresponding function with aruments saved in message.
This task can be solved multiple ways. T... | Another interesting option is simply to pass in a lambda.
```
q.put(lambda: HandleMsg(1,2))
q.put(lambda: HandleAnother(8, "hello", extra="foo"))
def DestinationThread() :
while True :
f = q.get()
f()
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.