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
What would a "frozen dict" be?
2,703,599
83
2010-04-24T07:19:50Z
2,703,730
11
2010-04-24T08:24:50Z
[ "python", "dictionary", "data-structures", "immutability" ]
* A frozen set is a frozenset. * A frozen list could be a tuple. * What would a frozen dict be? An immutable, hashable dict. I guess it could be something like `collections.namedtuple`, but that is more like a frozen-keys dict (a half-frozen dict). Isn't it? A "frozendict" should be a frozen dictionary, it should hav...
Assuming the keys and values of the dictionary are themselves immutable (e.g. strings) then: ``` >>> d {'forever': 'atones', 'minks': 'cards', 'overhands': 'warranted', 'hardhearted': 'tartly', 'gradations': 'snorkeled'} >>> t = tuple((k, d[k]) for k in sorted(d.keys())) >>> hash(t) 1524953596 ```
What would a "frozen dict" be?
2,703,599
83
2010-04-24T07:19:50Z
2,704,866
66
2010-04-24T14:52:17Z
[ "python", "dictionary", "data-structures", "immutability" ]
* A frozen set is a frozenset. * A frozen list could be a tuple. * What would a frozen dict be? An immutable, hashable dict. I guess it could be something like `collections.namedtuple`, but that is more like a frozen-keys dict (a half-frozen dict). Isn't it? A "frozendict" should be a frozen dictionary, it should hav...
Python doesn't have a builtin frozendict type. It turns out this wouldn't be useful too often (though it would still probably be useful more often than `frozenset` is). The most common reason to want such a type is when memoizing function calls for functions with unknown arguments. The most common solution to store a ...
What would a "frozen dict" be?
2,703,599
83
2010-04-24T07:19:50Z
30,638,022
18
2015-06-04T07:52:39Z
[ "python", "dictionary", "data-structures", "immutability" ]
* A frozen set is a frozenset. * A frozen list could be a tuple. * What would a frozen dict be? An immutable, hashable dict. I guess it could be something like `collections.namedtuple`, but that is more like a frozen-keys dict (a half-frozen dict). Isn't it? A "frozendict" should be a frozen dictionary, it should hav...
Curiously, although we have the seldom useful `frozenset` in python, there's still no frozen mapping. The idea was rejected in [PEP 416](http://www.python.org/dev/peps/pep-0416/). So the python 2 solution to this: ``` def foo(config={'a': 1}): ... ``` Still seems to be the somewhat lame: ``` def foo(config=None...
Process list on Linux via Python
2,703,640
53
2010-04-24T07:44:39Z
2,703,700
8
2010-04-24T08:09:21Z
[ "python", "linux" ]
How can I get running process list using Python on Linux?
You can use a third party library, such as [PSI](http://bitbucket.org/chrismiles/psi/wiki/Home): > PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported p...
Process list on Linux via Python
2,703,640
53
2010-04-24T07:44:39Z
2,704,947
86
2010-04-24T15:20:04Z
[ "python", "linux" ]
How can I get running process list using Python on Linux?
IMO looking at the `/proc` filesystem is less nasty than hacking the text output of `ps`. ``` import os pids = [pid for pid in os.listdir('/proc') if pid.isdigit()] for pid in pids: try: print open(os.path.join('/proc', pid, 'cmdline'), 'rb').read() except IOError: # proc has already terminated ...
Process list on Linux via Python
2,703,640
53
2010-04-24T07:44:39Z
6,390,799
51
2011-06-17T19:25:59Z
[ "python", "linux" ]
How can I get running process list using Python on Linux?
You could use [psutil](https://github.com/giampaolo/psutil) as a platform independent solution! ``` import psutil psutil.pids() [1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224, 268, 1215, 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355, 2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 42...
Intercept method calls in Python
2,704,434
30
2010-04-24T12:22:15Z
2,704,528
37
2010-04-24T12:57:50Z
[ "python" ]
I'm implementing a RESTful web service in python and would like to add some QOS logging functionality by intercepting function calls and logging their execution time and so on. Basically i thought of a class from which all other services can inherit, that automatically overrides the default method implementations and ...
Something like this? This implictly adds a decorator to your method (you can also make an explicit decorator based on this if you prefer that): ``` class Foo(object): def __getattribute__(self,name): attr = object.__getattribute__(self, name) if hasattr(attr, '__call__'): def newfunc(*a...
Why is '\x' invalid in Python?
2,704,654
21
2010-04-24T13:43:39Z
2,704,681
18
2010-04-24T13:51:58Z
[ "python", "string", "ascii", "backslash", "control-characters" ]
I was experimenting with '\' characters, using '\a\b\c...' just to enumerate for myself which characters Python interprets as control characters, and to what. Here's what I found: ``` \a - BELL \b - BACKSPACE \f - FORMFEED \n - LINEFEED \r - RETURN \t - TAB \v - VERTICAL TAB ``` Most of the other characters I tried, ...
There is a table listing all the escape codes and their meanings in the [documentation](http://docs.python.org/reference/lexical_analysis.html#string-literals). ``` Escape Sequence Meaning Notes \xhh Character with hex value hh (4,5) ``` > Notes: > > 4. Unlike in Standard C,...
Type hinting in Eclipse with PyDev
2,704,769
18
2010-04-24T14:20:27Z
2,704,896
13
2010-04-24T15:03:17Z
[ "python", "pydev", "type-hinting" ]
I'm studying Python, after a lot of PHP experience, and it would be handy to have *type-hinting* in Python. Looks like Eclipse with PyDev doesn't support this. Any suggestions? For example, I want my IDE to show function *docstrings* and *types*, when I use it, like: ``` def f(x: int) -> int: r"""Adds 3 to x""" ...
Python is a dynamically-typed language, where variable types don't need to be declared. You can add information about the *expected* types intended to be passed to the function in docstrings though, e.g. ``` def f(x): """ @x: int Adds 3 to x returns an int """ return x + 3 ``` But in this case...
Type hinting in Eclipse with PyDev
2,704,769
18
2010-04-24T14:20:27Z
6,874,794
12
2011-07-29T14:37:24Z
[ "python", "pydev", "type-hinting" ]
I'm studying Python, after a lot of PHP experience, and it would be handy to have *type-hinting* in Python. Looks like Eclipse with PyDev doesn't support this. Any suggestions? For example, I want my IDE to show function *docstrings* and *types*, when I use it, like: ``` def f(x: int) -> int: r"""Adds 3 to x""" ...
# Present Python 2/3 For local scope variables and function parameters PyDev has this: ``` assert isinstance(obj, MyClass) obj. # here hint will work ``` Though I guess it's a not documented feature. Here's PyDev's [official page for type hints](http://pydev.org/manual_adv_type_hints.html) and couple of excerpts whi...
Type hinting in Eclipse with PyDev
2,704,769
18
2010-04-24T14:20:27Z
26,103,767
8
2014-09-29T15:44:19Z
[ "python", "pydev", "type-hinting" ]
I'm studying Python, after a lot of PHP experience, and it would be handy to have *type-hinting* in Python. Looks like Eclipse with PyDev doesn't support this. Any suggestions? For example, I want my IDE to show function *docstrings* and *types*, when I use it, like: ``` def f(x: int) -> int: r"""Adds 3 to x""" ...
As of August 2014 there is a [proposal](https://mail.python.org/pipermail/python-ideas/2014-August/028618.html) by Guido Van Rossum to use [mypy](http://mypy-lang.org/) syntax annotate type in function definitions, stating that the new syntax is actually valid Python 3. An example from his proposal (not yet a PEP as of...
Python debugging in Eclipse+PyDev
2,704,932
7
2010-04-24T15:13:56Z
2,739,358
8
2010-04-29T17:16:18Z
[ "python", "eclipse", "pydev" ]
I try Eclipse+PyDev pair for some of my work. (Eclipse v3.5.0 + PyDev v1.5.6) I couldn't find a way to expose all of my variables to the PyDev console (Through PyDev console -> Console for current active editor option) I use a simple code to describe the issue. When I step-by-step go through the code I can't access my ...
Update: In the latest PyDev versions, it's possible to right-click a frame in the stack and select PyDev > Debug console to have the interactive console with more functions associated to a context during a debug session. --- Unfortunately, the actual interactive console, which would be the preferred way of playing w...
lambda vs. operator.attrgetter('xxx') as sort key function in Python
2,705,104
17
2010-04-24T15:56:37Z
2,705,127
16
2010-04-24T16:03:45Z
[ "python", "lambda", "code-review" ]
I am looking at some code that has a lot of sort calls using comparison functions, and it seems like it should be using key functions. If you were to change `seq.sort(lambda x,y: cmp(x.xxx, y.xxx))`, which is preferable: ``` seq.sort(key=operator.attrgetter('xxx')) ``` or: ``` seq.sort(key=lambda a:a.xxx) ``` I wo...
"Making changes to existing code that works" is how programs evolve;-). Write a good battery of tests that give known results with the existing code, save those results (that's normally known as "golden files" in a testing context); then make the changes, rerun the tests, and verify (ideally in an automated way) that t...
How do I extend a python module? (python-twitter)
2,705,964
11
2010-04-24T20:12:44Z
2,706,023
16
2010-04-24T20:33:41Z
[ "python", "module", "tweepy", "python-twitter" ]
What are the best practices for extending a python module -- in this case I want to extend python-twitter by adding new methods to the base API class. I've looked at tweepy, and I like that as well, I just find python-twitter easier to understand and extend with the functionality I want. I have the methods written al...
A few ways. **The easy way:** Don't extend the module, extend the classes. exttwitter.py ``` import twitter class Api(twitter.Api): pass # override/add any functions here. ``` Downside : Every class in twitter must be in exttwitter.py, even if it's just a stub (as above) **A harder (possibly un-pythonic...
class __init__ (not instance __init__)
2,706,408
8
2010-04-24T22:32:30Z
2,706,431
12
2010-04-24T22:41:58Z
[ "python", "class", "initialization", "self-reference" ]
Here's a very simple example of what I'm trying to get around: ``` class Test(object): some_dict = {Test: True} ``` The problem is that I cannot refer to Test while it's still being defined Normally, I'd just do this: ``` class Test(object): some_dict = {} def __init__(self): if self.__class__.s...
The class does in fact not exist while it is being defined. The way the `class` statement works is that the body of the statement is executed, as a block of code, in a separate namespace. At the end of the execution, that namespace is passed to the metaclass (such as `type`) and the metaclass creates the class using th...
Sorting a 2D numpy array by multiple axes
2,706,605
15
2010-04-24T23:39:55Z
2,706,751
26
2010-04-25T01:00:13Z
[ "python", "sorting", "numpy" ]
I have a 2D numpy array of shape (N,2) which is holding N points (x and y coordinates). For example: ``` array([[3, 2], [6, 2], [3, 6], [3, 4], [5, 3]]) ``` I'd like to sort it such that my points are ordered by x-coordinate, and then by y in cases where the x coordinate is the same. So th...
Using [lexsort](http://docs.scipy.org/doc/numpy/reference/generated/numpy.lexsort.html#numpy.lexsort): ``` import numpy as np a = np.array([(3, 2), (6, 2), (3, 6), (3, 4), (5, 3)]) ind = np.lexsort((a[:,1],a[:,0])) a[ind] # array([[3, 2], # [3, 4], # [3, 6], # [5, 3], # [6, 2]]) ``` ...
Sorting a 2D numpy array by multiple axes
2,706,605
15
2010-04-24T23:39:55Z
26,036,376
9
2014-09-25T10:33:17Z
[ "python", "sorting", "numpy" ]
I have a 2D numpy array of shape (N,2) which is holding N points (x and y coordinates). For example: ``` array([[3, 2], [6, 2], [3, 6], [3, 4], [5, 3]]) ``` I'd like to sort it such that my points are ordered by x-coordinate, and then by y in cases where the x coordinate is the same. So th...
The title says "sorting 2D arrays". Although the question asker uses a `(N,2)`-shaped array, it's possible to generalize unutbu's solution to work with any `(N,M)` array, as that's what people might actually be looking for. One could `transpose` the array and use slice notation with negative `step` to pass all the col...
Python: using doctests for classes
2,708,178
24
2010-04-25T12:24:25Z
2,708,239
18
2010-04-25T12:45:27Z
[ "python", "unit-testing", "doctest" ]
Is it possible to use Python's doctest concept for classes, not just functions? If so, where shall I put the doctests - at the class' docstring, or at the constructor's docstring? To clarify, I'm looking for something like: ``` class Test: """ >>> a=Test(5) >>> a.multiply_by_2() 10 """ def __...
You're missing the code to actually run the doctests at the bottom of the file: ``` class Test: <snip> if __name__ == "__main__": import doctest doctest.testmod() ``` As for where to put the tests: * If it's testing the class as a whole, I'd put them in the class' docstring. * If it's testing the constr...
Python: using doctests for classes
2,708,178
24
2010-04-25T12:24:25Z
3,936,125
35
2010-10-14T18:02:14Z
[ "python", "unit-testing", "doctest" ]
Is it possible to use Python's doctest concept for classes, not just functions? If so, where shall I put the doctests - at the class' docstring, or at the constructor's docstring? To clarify, I'm looking for something like: ``` class Test: """ >>> a=Test(5) >>> a.multiply_by_2() 10 """ def __...
Instead of instantiating the object in every method, you could do something like this: ``` class Test: def multiply_by_2(self): """ >>> t.multiply_by_2() 10 """ return self._number*2 if __name__ == "__main__": import doctest doctest.testmod(extraglobs={'t': Test()})...
Strange Syntax Parsing Error in Python?
2,708,614
7
2010-04-25T14:50:24Z
2,708,660
9
2010-04-25T15:03:52Z
[ "python", "syntax-error" ]
Am I missing something here? Why shouldn't the code under the "Broken" section work? I'm using Python 2.6. ``` #!/usr/bin/env python def func(a,b,c): print a,b,c #Working: Example #1: p={'c':3} func(1, b=2, c=3, ) #Working: Example #2: func(1, b=2, **p) #Broken: Example #3: func(1,...
This is the relevant bit from the [grammar](http://docs.python.org/reference/grammar.html): ``` arglist: (argument ',')* (argument [','] |'*' test (',' argument)* [',' '**' test] |'**' test) ``` The first line here allows putting a comma after the last parameter when...
How can I test to see if a class contains a particular attribute?
2,708,781
3
2010-04-25T15:42:49Z
2,708,846
8
2010-04-25T16:02:52Z
[ "python", "django", "reflection" ]
How can I test to see if a class contains a particular attribute? ``` In [14]: user = User.objects.get(pk=2) In [18]: user.__dict__ Out[18]: {'date_joined': datetime.datetime(2010, 3, 17, 15, 20, 45), 'email': u'IloveDick@nwo.gov', 'first_name': u'', 'id': 2L, 'is_active': 1, 'is_staff': 0, '...
as far as I know there is no method like hasattr() for Django models. But there is a way to check if a Django model has a certain field. To test this I would recommend you to access the Django (Python) shell: ``` $> python manage.py shell ``` Now import the User model: ``` $> from django.contrib.auth.models import ...
Python script to calculate aded combinations from a dictionary
2,708,913
4
2010-04-25T16:24:26Z
2,709,163
7
2010-04-25T17:34:18Z
[ "python", "algorithm", "language-agnostic", "combinatorics", "combinations" ]
I am trying to write a script that will take a dictionary of items, each containing properties of values from 0 - 10, and add the various elements to select which combination of items achieve the desired totals. I also need the script to do this, using only items that have the same "slot" in common. For example: ``` ...
Since the properties can have both positive and negative values, and you need *all* satisfactory combinations, I believe there is no "essential" optimization possible -- that is, no polynomial-time solution (assuming P != NP...;-). All solutions will come down to enumerating all the one-per-slot combinations and checki...
Setting the vim color theme for highlighted braces
2,709,064
8
2010-04-25T17:05:18Z
2,709,853
11
2010-04-25T20:30:59Z
[ "python", "vim" ]
How do you change the vim color scheme for highlighted braces? I'm looking to actually edit the .vim theme file to make the change permanent. Regards, Craig
The automatic highlight colour for matching brackets is called `MatchParen`. You can change the colour in your .vimrc by doing eg: ``` highlight MatchParen cterm=bold ctermfg=cyan ```
Python Beginner: Selective Printing in loops
2,709,425
2
2010-04-25T18:45:47Z
2,709,450
9
2010-04-25T18:51:44Z
[ "python", "for-loop" ]
I'm a very new python user (had only a little prior experience with html/javascript as far as programming goes), and was trying to find some ways to output only intermittent numbers in my loop for a basic bicycle racing simulation (10,000 lines of biker positions would be pretty excessive :P). I tried in this loop sev...
The for loop auto increments for you, so you don't need to use `i = i + 1`. You don't need `t`, just use `%` (modulo) operator to find multiples of a number. ``` # Log every 1000 lines. LOG_EVERY_N = 1000 for i in range(1000): ... # calculations with i if (i % LOG_EVERY_N) == 0: print "logging: ..." ```
How to pickle yourself?
2,709,800
29
2010-04-25T20:16:24Z
2,709,848
12
2010-04-25T20:29:12Z
[ "python", "pickle" ]
I want my class to implement Save and Load functions which simply do a pickle of the class. But apparently you cannot use 'self' in the fashion below. How can you do this? ``` self = cPickle.load(f) cPickle.dump(self,f,2) ```
The dump part should work as you suggested. for the loading part, you can define a [@classmethod](http://docs.python.org/library/functions.html#classmethod) that loads an instance from a given file and returns it. ``` @classmethod def loader(cls,f): return cPickle.load(f) ``` then the caller would do something li...
How to pickle yourself?
2,709,800
29
2010-04-25T20:16:24Z
2,842,727
23
2010-05-16T06:01:54Z
[ "python", "pickle" ]
I want my class to implement Save and Load functions which simply do a pickle of the class. But apparently you cannot use 'self' in the fashion below. How can you do this? ``` self = cPickle.load(f) cPickle.dump(self,f,2) ```
This is what I ended up doing. Updating the `__dict__` means we keep any new member variables I add to the class and just update the ones that were there when the object was last pickle'd. It seems the simplest while maintaining the saving and loading code inside the class itself so calling code just does an object.Sav...
Fastest Way to generate 1,000,000+ random numbers in python
2,709,818
20
2010-04-25T20:21:43Z
2,710,189
10
2010-04-25T22:15:19Z
[ "python", "performance", "random", "numpy" ]
I am currently writing an app in python that needs to generate large amount of random numbers, FAST. Currently I have a scheme going that uses numpy to generate all of the numbers in a giant batch (about ~500,000 at a time). While this seems to be faster than python's implementation. I still need it to go faster. Any i...
You can speed things up a bit from what mtrw posted above just by doing what you initially described (generating a bunch of random numbers and multiplying and dividing accordingly)... Also, you probably already know this, but be sure to do the operations in-place (\*=, /=, +=, etc) when working with large-ish numpy ar...
What is the purpose of self in Python?
2,709,821
586
2010-04-25T20:22:28Z
2,709,832
393
2010-04-25T20:25:37Z
[ "python", "class", "self" ]
What is the purpose of the `self` word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this: ``` class myClass def myFunc(name) @name = name end end ``...
The reason you need to use `self.` is because Python does not use the `@` syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be *passed* automatically, but not *received* automatically: the first parameter of methods is the instance the meth...
What is the purpose of self in Python?
2,709,821
586
2010-04-25T20:22:28Z
2,709,847
13
2010-04-25T20:29:08Z
[ "python", "class", "self" ]
What is the purpose of the `self` word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this: ``` class myClass def myFunc(name) @name = name end end ``...
The following excerpts are from the [Python documentation about self](http://docs.python.org/tutorial/classes.html): > As in Modula-3, there are no shorthands [in Python] for referencing the object’s members from its methods: the method function is declared with an explicit first argument representing the object, wh...
What is the purpose of self in Python?
2,709,821
586
2010-04-25T20:22:28Z
2,709,857
15
2010-04-25T20:31:43Z
[ "python", "class", "self" ]
What is the purpose of the `self` word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this: ``` class myClass def myFunc(name) @name = name end end ``...
As well as all the other reasons already stated, it allows for easier access to overridden methods; you can call `Class.some_method(inst)`. An example of where it’s useful: ``` class C1(object): def __init__(self): print "C1 init" class C2(C1): def __init__(self): #overrides C1.__init__ pr...
What is the purpose of self in Python?
2,709,821
586
2010-04-25T20:22:28Z
2,714,920
48
2010-04-26T16:02:48Z
[ "python", "class", "self" ]
What is the purpose of the `self` word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this: ``` class myClass def myFunc(name) @name = name end end ``...
I like this example: ``` class A: foo = [] a, b = A(), A() a.foo.append(5) b.foo ans: [5] class A: def __init__(self): self.foo = [] a, b = A(), A() a.foo.append(5) b.foo ans: [] ```
What is the purpose of self in Python?
2,709,821
586
2010-04-25T20:22:28Z
2,725,996
290
2010-04-28T00:03:33Z
[ "python", "class", "self" ]
What is the purpose of the `self` word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this: ``` class myClass def myFunc(name) @name = name end end ``...
I have been confused by this as well for quite a while and I don’t believe that the reason for this has got much to do with the often-pronounced *explicit is better than implicit* but that it is just following a simple analogy there. Let’s take a simple vector class: ``` class Vector: def __init__(self, x, y)...
What is the purpose of self in Python?
2,709,821
586
2010-04-25T20:22:28Z
6,433,556
27
2011-06-22T00:27:23Z
[ "python", "class", "self" ]
What is the purpose of the `self` word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this: ``` class myClass def myFunc(name) @name = name end end ``...
I will demonstrate with code that **does not use classes**: ``` def state_init(state): state['field'] = 'init' def state_add(state, x): state['field'] += x def state_mult(state, x): state['field'] *= x def state_getField(state): return state['field'] myself = {} state_init(myself) state_add(myself,...
What is the purpose of self in Python?
2,709,821
586
2010-04-25T20:22:28Z
12,201,574
7
2012-08-30T16:37:23Z
[ "python", "class", "self" ]
What is the purpose of the `self` word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this: ``` class myClass def myFunc(name) @name = name end end ``...
Its use is nearly the same as that of `this` keyword in Java, i.e. to give a reference to the current object.
What is the purpose of self in Python?
2,709,821
586
2010-04-25T20:22:28Z
21,366,809
153
2014-01-26T17:31:58Z
[ "python", "class", "self" ]
What is the purpose of the `self` word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this: ``` class myClass def myFunc(name) @name = name end end ``...
Let's say you have a class `ClassA` which contains a method `methodA` defined as: ``` def methodA(self, arg1, arg2): # do something ``` and `ObjectA` is an instance of this class. Now when `ObjectA.methodA(arg1, arg2)` is called, python internally converts it for you as: ``` ClassA.methodA(ObjectA, arg1, arg2) ...
What is the purpose of self in Python?
2,709,821
586
2010-04-25T20:22:28Z
31,096,552
70
2015-06-28T05:47:02Z
[ "python", "class", "self" ]
What is the purpose of the `self` word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this: ``` class myClass def myFunc(name) @name = name end end ``...
When objects are instantiated, the object itself is passed into the self parameter. ![enter image description here](http://i.stack.imgur.com/whCZm.png) Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how â...
How to make an executable file in Python?
2,709,925
7
2010-04-25T20:55:44Z
2,709,955
9
2010-04-25T21:02:45Z
[ "python", "executable" ]
I want to make an executable file (.exe) of my Python application. I want to know how to do it but have this in mind: I use a C++ DLL! Do I have to put the DLL along side with the .exe or is there some other way?
[py2exe](http://www.py2exe.org/) can generate single file executables. see [this link](http://www.py2exe.org/index.cgi/SingleFileExecutable) for examples. The setup.py I use uses the following combination of options: ``` 'compressed': 1, 'optimize':2, 'bundle_files': 1 ``` I usually add external dlls (p.e. msvcr71...
write error: Broken pipe
2,709,941
4
2010-04-25T21:00:43Z
2,709,987
9
2010-04-25T21:10:19Z
[ "python", "linux", "unix", "scripting" ]
I have to run a tool on around 300 directories. Each run take around 1 minute to 30 minute or even more than that. So, I wrote a python script having a loop to run the tool on all directories one after another. my python script has code something like: ``` for directory in directories: os.popen('runtool_exec ' + di...
The errors you see are because you're using `os.popen()` to run the command, which means a pipe is opened and connected to the command's `stdout`. Whenever the command (or anything it executes without redirecting `stdout`) wants to write to `stdout`, it'll try to write to the pipe. But you don't keep the pipe around, s...
Python regular expressions assigning to named groups
2,710,486
10
2010-04-26T00:14:20Z
2,710,492
10
2010-04-26T00:17:13Z
[ "python", "regex", "variables", "variable-assignment" ]
When you use variables (is that the correct word?) in python regular expressions like this: "blah (?P\w+)" ("value" would be the variable), how could you make the variable's value be the text after "blah " to the end of the line or to a certain character not paying any attention to the actual content of the variable. F...
For that you'd want a regular expression of ``` "say (?P<value>.+) endsay" ``` The period matches any character, and the plus sign indicates that that should be repeated one or more times... so `.+` means any sequence of one or more characters. When you put `endsay` at the end, the regular expression engine will make...
Python regular expressions assigning to named groups
2,710,486
10
2010-04-26T00:14:20Z
2,710,578
8
2010-04-26T00:53:56Z
[ "python", "regex", "variables", "variable-assignment" ]
When you use variables (is that the correct word?) in python regular expressions like this: "blah (?P\w+)" ("value" would be the variable), how could you make the variable's value be the text after "blah " to the end of the line or to a certain character not paying any attention to the actual content of the variable. F...
You need to specify what you want to match if the text is, for example, ``` say hello there and endsay but some more endsay ``` If you want to match the whole `hello there and endsay but some more` substring, @David's answer is correct. Otherwise, to match just `hello there and`, the pattern needs to be: ``` say (?P...
Best programming aids for a quadriplegic programmer
2,710,537
125
2010-04-26T00:30:21Z
2,710,672
19
2010-04-26T01:33:35Z
[ "python", "robotics" ]
Before you jump to conclusions, yes, this is programming related. It covers a situation that comes under the heading of, "There, but for the grace of God, go you or I." This is brand new territory for me so I'm asking for some serious help here. A young man, [Honza Ripa](http://www.pressdemocrat.com/article/20100418/a...
It's worth looking at the [Dasher Project](http://wol.ra.phy.cam.ac.uk/), which makes it possible to enter text reasonably quickly even for the severly disabled. Dasher is built on a probabilistic model of languages, so that more likely utterances are easier to enter into the system. The demonstration system comes with...
Best programming aids for a quadriplegic programmer
2,710,537
125
2010-04-26T00:30:21Z
2,710,686
92
2010-04-26T01:37:29Z
[ "python", "robotics" ]
Before you jump to conclusions, yes, this is programming related. It covers a situation that comes under the heading of, "There, but for the grace of God, go you or I." This is brand new territory for me so I'm asking for some serious help here. A young man, [Honza Ripa](http://www.pressdemocrat.com/article/20100418/a...
I have sports injuries, and I cannot type more than few characters without serious pain. Instead, I use emacs together with Dragon NaturallySpeaking. I have written macros and scripts to help it get by. The system is not perfect, but it works. I program mostly in C++, but I also use python. If you want to, I will hel...
Best programming aids for a quadriplegic programmer
2,710,537
125
2010-04-26T00:30:21Z
2,710,842
8
2010-04-26T02:39:56Z
[ "python", "robotics" ]
Before you jump to conclusions, yes, this is programming related. It covers a situation that comes under the heading of, "There, but for the grace of God, go you or I." This is brand new territory for me so I'm asking for some serious help here. A young man, [Honza Ripa](http://www.pressdemocrat.com/article/20100418/a...
This isn't part of any professional software, but when I saw this, I've thought it would be good for text entry using eye movement tracking or minimal mouse movement. See [Ken Perlin's Processing page](http://mrl.nyu.edu/~perlin/), and look at the applets for "pen input".
How to import modules in Google App Engine?
2,710,861
20
2010-04-26T02:45:49Z
2,710,892
29
2010-04-26T02:52:33Z
[ "python", "google-app-engine" ]
I have created a simple GAE app based on the default template. I want to add an external module like [short\_url](http://code.activestate.com/recipes/576918/). How do I do this? The directions that I have found so far are confusing and GAE doesn't seem to use PYTHONPATH for obvious reasons I guess.
Simply place the `short_url.py` file in your app's directory. Sample App Engine project: ``` myapp/ app.yaml index.yaml main.py short_url.py views.py ``` And in `views.py` (or wherever), you can then import like so: ``` import short_url ``` --- For more complex projects, perhaps a better metho...
Python `if x is not None` or `if not x is None`?
2,710,940
348
2010-04-26T03:10:30Z
2,710,949
54
2010-04-26T03:13:32Z
[ "python", "coding-style", "boolean-expression" ]
I've always thought of the `if not x is None` version to be more clear, but Google's [style guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=True/False_evaluations#True/False_evaluations) implies (based on this excerpt) that they use `if x is not None`. Is there any minor performance differ...
Both Google and [Python](http://www.python.org/dev/peps/pep-0008/#programming-recommendations)'s style guide is the best practice: ``` if x is not None: # Do something about x ``` Using `not x` can cause unwanted results. See below: ``` >>> x = 1 >>> not x False >>> x = [1] >>> not x False >>> x = 0 >>> not x Tr...
Python `if x is not None` or `if not x is None`?
2,710,940
348
2010-04-26T03:10:30Z
2,710,959
77
2010-04-26T03:15:55Z
[ "python", "coding-style", "boolean-expression" ]
I've always thought of the `if not x is None` version to be more clear, but Google's [style guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=True/False_evaluations#True/False_evaluations) implies (based on this excerpt) that they use `if x is not None`. Is there any minor performance differ...
Code should be written to be understandable to the programmer first, and the compiler or interpreter second. The "is not" construct resembles English more closely than "not is".
Python `if x is not None` or `if not x is None`?
2,710,940
348
2010-04-26T03:10:30Z
2,711,073
568
2010-04-26T03:55:04Z
[ "python", "coding-style", "boolean-expression" ]
I've always thought of the `if not x is None` version to be more clear, but Google's [style guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=True/False_evaluations#True/False_evaluations) implies (based on this excerpt) that they use `if x is not None`. Is there any minor performance differ...
There's no performance difference, as they compile to the same bytecode: ``` Python 2.6.2 (r262:71600, Apr 15 2009, 07:20:39) >>> import dis >>> def f(x): ... return x is not None ... >>> dis.dis(f) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 0 (None) 6 COMP...
Python `if x is not None` or `if not x is None`?
2,710,940
348
2010-04-26T03:10:30Z
2,711,168
8
2010-04-26T04:32:34Z
[ "python", "coding-style", "boolean-expression" ]
I've always thought of the `if not x is None` version to be more clear, but Google's [style guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=True/False_evaluations#True/False_evaluations) implies (based on this excerpt) that they use `if x is not None`. Is there any minor performance differ...
The `is not` operator is preferred over negating the result of `is` for stylistic reasons. "`if x is not None:`" reads just like English, but "`if not x is None:`" requires understanding of the operator precedence and does not read like english. If there is a performance difference my money is on `is not`, but this al...
Python `if x is not None` or `if not x is None`?
2,710,940
348
2010-04-26T03:10:30Z
2,711,669
18
2010-04-26T07:18:03Z
[ "python", "coding-style", "boolean-expression" ]
I've always thought of the `if not x is None` version to be more clear, but Google's [style guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=True/False_evaluations#True/False_evaluations) implies (based on this excerpt) that they use `if x is not None`. Is there any minor performance differ...
The answer is simpler than people are making it. There's no technical advantage either way, and "x is not y" is what *everybody else uses*, which makes it the clear winner. It doesn't matter that it "looks more like English" or not; everyone uses it, which means every user of Python--even Chinese users, whose language...
how code a Image button in PyQt?
2,711,033
7
2010-04-26T03:42:08Z
2,714,554
13
2010-04-26T15:12:03Z
[ "python", "qt", "pyqt", "pyqt4" ]
Im trying to do simple audio player, but I want use a image(icon) as a pushbutton.
You can subclass QAbstractButton and make a button of your own. Here is a basic simple example: ``` import sys from PyQt4.QtGui import * class PicButton(QAbstractButton): def __init__(self, pixmap, parent=None): super(PicButton, self).__init__(parent) self.pixmap = pixmap def paintEvent(self,...
a more pythonic way to express conditionally bounded loop?
2,711,289
5
2010-04-26T05:31:07Z
2,711,331
11
2010-04-26T05:45:55Z
[ "coding-style", "python" ]
I've got a loop that wants to execute to exhaustion or until some user specified limit is reached. I've got a construct that looks bad yet I can't seem to find a more elegant way to express it; is there one? ``` def ello_bruce(limit=None): for i in xrange(10**5): if predicate(i): if not limit i...
Maybe something like this would be a little better: ``` from itertools import ifilter, islice def ello_bruce(limit=None): for i in islice(ifilter(predicate, xrange(10**5)), limit): # do whatever you want with i here ```
Concatenate strings in python 2.4?
2,711,579
95
2010-04-26T06:58:09Z
2,711,589
154
2010-04-26T06:59:54Z
[ "python", "string", "concatenation" ]
How to concatenate strings in python? For example: ``` Section = 'C_type' ``` Concatenate it with `Sec_` to form the string: ``` Sec_C_type ```
The easiest way would be ``` Section = 'Sec_' + Section ``` But for efficiency, see: <http://www.skymind.com/~ocrow/python_string/>
Concatenate strings in python 2.4?
2,711,579
95
2010-04-26T06:58:09Z
2,711,617
38
2010-04-26T07:04:42Z
[ "python", "string", "concatenation" ]
How to concatenate strings in python? For example: ``` Section = 'C_type' ``` Concatenate it with `Sec_` to form the string: ``` Sec_C_type ```
you can also do this: ``` section = "C_type" new_section = "Sec_%s" % section ``` This allows you not only append, but also insert wherever in the string: ``` section = "C_type" new_section = "Sec_%s_blah" % section ```
Concatenate strings in python 2.4?
2,711,579
95
2010-04-26T06:58:09Z
13,881,162
18
2012-12-14T15:03:35Z
[ "python", "string", "concatenation" ]
How to concatenate strings in python? For example: ``` Section = 'C_type' ``` Concatenate it with `Sec_` to form the string: ``` Sec_C_type ```
More efficient ways of concatenating strings are: **join():** Very efficent, but a bit hard to read. ``` >>> Section = 'C_type' >>> new_str = ''.join(['Sec_', Section]) # inserting a list of strings >>> print new_str >>> 'Sec_C_type' ``` **String formatting:** Easy to read and in most cases faster than '+' con...
Concatenate strings in python 2.4?
2,711,579
95
2010-04-26T06:58:09Z
15,953,864
24
2013-04-11T16:16:32Z
[ "python", "string", "concatenation" ]
How to concatenate strings in python? For example: ``` Section = 'C_type' ``` Concatenate it with `Sec_` to form the string: ``` Sec_C_type ```
Just a comment, as someone may find it useful - you can concatenate more than one string in one go: ``` >>> a='a' >>> b='b' >>> print '%s and %s' %(a,b) a and b ```
installing simplejson on the google appengine
2,711,605
5
2010-04-26T07:02:42Z
2,712,178
14
2010-04-26T09:00:04Z
[ "python", "google-app-engine", "simplejson" ]
Super nub question time! I am trying to use simplejson on the google appengine. In a terminal on my machine I have simplejson installed and working. But my when I try to import it in a script running on the appengine I get an error saying no such library exists. If open the interactive console on my machine (from the l...
Look in django package: ``` from django.utils import simplejson as json obj = json.loads(json_string) ``` Since Sdk 1.4.2 Json can be imported with the following statement: ``` import simplejson ``` Note that on Python 2.7 runtime you can use the [native Json library](https://developers.google.com/appengine/docs/py...
installing simplejson on the google appengine
2,711,605
5
2010-04-26T07:02:42Z
5,035,298
10
2011-02-17T22:10:49Z
[ "python", "google-app-engine", "simplejson" ]
Super nub question time! I am trying to use simplejson on the google appengine. In a terminal on my machine I have simplejson installed and working. But my when I try to import it in a script running on the appengine I get an error saying no such library exists. If open the interactive console on my machine (from the l...
You no longer need to use the django package for simplejson on Google App Engine. ``` import simplejson as json ``` This is expecially handy for avoiding the flurry of warnings about django versions in your log file.
Database for Python Twisted
2,711,621
15
2010-04-26T07:06:11Z
2,713,342
13
2010-04-26T12:21:12Z
[ "python", "database", "scalability", "rdbms", "twisted" ]
There's an API for Twisted apps to talk to a database in a scalable way: [twisted.enterprise.dbapi](http://twistedmatrix.com/projects/core/documentation/howto/rdbms.html) The confusing thing is, which database to pick? The database will have a Twisted app that is mostly making inserts and updates and relatively few s...
**Scalability** `twisted.enterprise.adbapi` isn't necessarily an interface for talking to databases in a scalable way. Scalability is a problem you get to solve separately. The only thing `twisted.enterprise.adbapi` really claims to do is let you use DB-API 2.0 modules without the blocking that normally implies. **Po...
Database for Python Twisted
2,711,621
15
2010-04-26T07:06:11Z
8,730,922
8
2012-01-04T17:10:48Z
[ "python", "database", "scalability", "rdbms", "twisted" ]
There's an API for Twisted apps to talk to a database in a scalable way: [twisted.enterprise.dbapi](http://twistedmatrix.com/projects/core/documentation/howto/rdbms.html) The confusing thing is, which database to pick? The database will have a Twisted app that is mostly making inserts and updates and relatively few s...
There is the `txpostgres` library which is a drop in replacement for `twisted.enterprise.dbapi`, —instead of a thread pool and blocking DB IO, it is fully asynchronous, leveraging the built in async capabilities of `psycopg2`. We are using it in production in a big corporation and it's been serving us very well so f...
Reading a triangle of numbers into a 2d array of ints in Python
2,711,681
5
2010-04-26T07:21:41Z
2,711,723
9
2010-04-26T07:30:16Z
[ "python", "file" ]
I want to read a triangle of integer values from a file into a 2D array of ints using Python. The numbers would look like this: 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 ... The code I have so far is as follows: ``` f = open('input.txt', 'r') arr = [] for i in range(0, 15): arr.append([]) str = f.rea...
``` arr = [[int(i) for i in line.split()] for line in open('input.txt')] ```
Handling urllib2's timeout? - Python
2,712,524
46
2010-04-26T10:03:37Z
2,712,686
77
2010-04-26T10:30:46Z
[ "python", "timeout", "urllib2", "urllib" ]
I'm using the timeout parameter within the urllib2's urlopen. ``` urllib2.urlopen('http://www.example.org', timeout=1) ``` How do I tell Python that if the timeout expires a custom error should be raised? --- Any ideas?
There are very few cases where you want to use `except:`. Doing this captures *any* exception, which can be hard to debug, and it captures exceptions including `SystemExit` and `KeyboardInterupt`, which can make your program annoying to use.. At the very simplest, you would catch [`urllib2.URLError`](http://docs.pytho...
Handling urllib2's timeout? - Python
2,712,524
46
2010-04-26T10:03:37Z
14,632,387
14
2013-01-31T18:13:04Z
[ "python", "timeout", "urllib2", "urllib" ]
I'm using the timeout parameter within the urllib2's urlopen. ``` urllib2.urlopen('http://www.example.org', timeout=1) ``` How do I tell Python that if the timeout expires a custom error should be raised? --- Any ideas?
In Python 2.7.3: ``` import urllib2 import socket class MyException(Exception): pass try: urllib2.urlopen("http://example.com", timeout = 1) except urllib2.URLError as e: print type(e) #not catch except socket.timeout as e: print type(e) #catched raise MyException("There was an error: %r" %...
Log Unittest output to a text file
2,712,831
9
2010-04-26T10:56:36Z
2,713,010
13
2010-04-26T11:26:28Z
[ "python", "logging", "unit-testing" ]
I am trying to log the output of tests to a text file. I am using the unittest module and want to log results into a text file instead of the screen. I have some script here to explain what has been tryied so far. This is the test script. ``` import unittest, sys class TestOne(unittest.TestCase): def setUp(self)...
You can pass the text runner into the main method. The text runner must be set up to write to a file rather than the std.err as it wraps the stream in a decorator. The following worked for me in python 2.6 ``` if __name__ == '__main__': log_file = 'log_file.txt' f = open(log_file, "w") runner = unittest.TextT...
Why doesn't Python's `re.split()` split on zero-length matches?
2,713,060
15
2010-04-26T11:34:24Z
2,713,210
21
2010-04-26T12:00:08Z
[ "python", "regex" ]
One particular quirk of the (otherwise quite powerful) `re` module in Python is that `re.split()` [will never split a string on a zero-length match](http://docs.python.org/library/re.html#re.split), for example if I want to split a string along word boundaries: ``` >>> re.split(r"\s+|\b", "Split along words, preserve ...
It's a design decision that was made, and could have gone either way. Tim Peters made [this post](http://bugs.python.org/issue852532#msg19231) to explain: > For example, if you split "abc" by the pattern x\*, what do you > expect? The pattern matches (with length 0) at 4 places, > but I bet most people would be surpri...
python dict function on enumerate object
2,713,712
3
2010-04-26T13:21:38Z
2,713,820
16
2010-04-26T13:34:25Z
[ "python", "dictionary", "enumerate" ]
If I have an enumerate object x, why does doing the following: ``` dict(x) ``` clear all the items in the enumerate sequence?
`enumerate` creates an [iterator](http://docs.python.org/library/stdtypes.html#typeiter). A iterator is a python object that only knows about the current item of a sequence and how to get the next, but there is no way to restart it. Therefore, once you have used a iterator in a loop, it cannot give you any more items a...
Python package name conventions
2,713,874
31
2010-04-26T13:41:54Z
2,713,984
11
2010-04-26T13:54:23Z
[ "python", "naming-conventions", "namespaces", "packages" ]
Is there a package naming convention for Python like Java's `com.company.actualpackage`? Most of the time I see simple, potentially colliding package names like "[web](http://webpy.org/)". If there is no such convention, is there a reason for it? What do you think of using the Java naming convention in the Python worl...
The Java's conventions also has its own drawbacks. Not every opensource package has a stable website behind it. What should a maintainer do if his website changes? Also, using this scheme package names become long and hard to remember. Finally, the name of the package should represent the purpose of the package, not it...
Python package name conventions
2,713,874
31
2010-04-26T13:41:54Z
2,713,987
7
2010-04-26T13:54:50Z
[ "python", "naming-conventions", "namespaces", "packages" ]
Is there a package naming convention for Python like Java's `com.company.actualpackage`? Most of the time I see simple, potentially colliding package names like "[web](http://webpy.org/)". If there is no such convention, is there a reason for it? What do you think of using the Java naming convention in the Python worl...
There is no Java-like naming convention for Python packages. You can of course adopt one for any package you develop yourself, but you might have to invasively edit any package you may adopt from third parties, and the "culturally alien" naming convention will probably sap the changes of your own packages to be widely ...
Python package name conventions
2,713,874
31
2010-04-26T13:41:54Z
2,713,994
29
2010-04-26T13:55:46Z
[ "python", "naming-conventions", "namespaces", "packages" ]
Is there a package naming convention for Python like Java's `com.company.actualpackage`? Most of the time I see simple, potentially colliding package names like "[web](http://webpy.org/)". If there is no such convention, is there a reason for it? What do you think of using the Java naming convention in the Python worl...
Python has two "mantras" that cover this topic: > Explicit is better than implicit. and > Namespaces are one honking great idea -- let's do more of those! There is a convention for naming of and importing of modules that can be found in [The Python Style Guide](http://www.python.org/dev/peps/pep-0008/) (PEP 8). Th...
python decorator to modify variable in current scope
2,714,244
4
2010-04-26T14:29:19Z
2,714,332
9
2010-04-26T14:41:07Z
[ "python", "scope", "decorator" ]
Goal: Make a decorator which can modify the scope that it is used in. If it worked: ``` class Blah(): # or perhaps class Blah(ParentClassWhichMakesThisPossible) def one(self): pass @decorated def two(self): pass >>> Blah.decorated ["two"] ``` Why? I essentially want to write classes wh...
You can do what you want with a class decorator (in Python 2.6) or a metaclass. The class decorator version: ``` def rule(f): f.rule = True return f def getRules(cls): cls.rules = {} for attr, value in cls.__dict__.iteritems(): if getattr(value, 'rule', False): cls.rules[attr] = va...
Instance variables vs. class variables in Python
2,714,573
69
2010-04-26T15:14:29Z
2,714,590
112
2010-04-26T15:16:24Z
[ "python", "class", "variables", "static", "member" ]
I have Python classes, of which I need only one instance at runtime, so it would be sufficient to have the attributes only once per class and not per instance. If there would be more than one instance (what won't happen), all instance should have the same configuration. I wonder which of the following options would be ...
If you have only one instance anyway, it's best to make all variables per-instance, simply because they will be accessed (a little bit) faster (one less level of "lookup" due to the "inheritance" from class to instance), and there are no downsides to weigh against this small advantage.
Instance variables vs. class variables in Python
2,714,573
69
2010-04-26T15:14:29Z
2,714,632
15
2010-04-26T15:22:14Z
[ "python", "class", "variables", "static", "member" ]
I have Python classes, of which I need only one instance at runtime, so it would be sufficient to have the attributes only once per class and not per instance. If there would be more than one instance (what won't happen), all instance should have the same configuration. I wonder which of the following options would be ...
When in doubt, you probably want an instance attribute. Class attributes are best reserved for special cases where they make sense. The only very-common use case is methods. It isn't *uncommon* to use class attributes for read-only constants that instances need to know (though the only benefit to this is if you also w...
Instance variables vs. class variables in Python
2,714,573
69
2010-04-26T15:14:29Z
2,715,003
25
2010-04-26T16:14:23Z
[ "python", "class", "variables", "static", "member" ]
I have Python classes, of which I need only one instance at runtime, so it would be sufficient to have the attributes only once per class and not per instance. If there would be more than one instance (what won't happen), all instance should have the same configuration. I wonder which of the following options would be ...
further echoing mike's and alex's advice and adding my own color... using instance attributes are the typical, more idiomatic Python. class attributes are not oft-used -- at least not in production code in my last 13+ consecutive years of Python. the same is true for static and class methods... just not very common un...
Why would it be necessary to subclass from object in Python?
2,715,186
11
2010-04-26T16:43:11Z
2,715,208
11
2010-04-26T16:45:45Z
[ "python" ]
I've been using Python for quite a while now, and I'm still unsure as to why you would subclass from `object`. What is the difference between this: ``` class MyClass(): pass ``` And this: ``` class MyClass(object): pass ``` As far as I understand, `object` is the base class for all classes and the subclassi...
This is oldstyle and new style classes in python 2.x. The second form is the up to date version and exist from python 2.2 and above. For new code you should only use new style classes. In Python 3.x you can again use both form indifferently as the new style is the only one left and both form are truly equivalent. Howe...
CherryPy and RESTful web api
2,715,227
11
2010-04-26T16:48:51Z
2,831,479
10
2010-05-14T02:18:35Z
[ "python", "rest", "cherrypy" ]
What's the best approach of creating a RESTful web api in CherryPy? I've been looking around for a few days now and nothing seems great. For Django it seems that are lots of tools to do this, but not for CherryPy or I am not aware of them. **Later edit:** How should I use Cherrypy to transform a request like /getOrder...
I don't if it's the "best" way, but here's how I do it: ``` import cherrypy class RESTResource(object): """ Base class for providing a RESTful interface to a resource. To use this class, simply derive a class from it and implement the methods you want to support. The list of possible methods are: han...
CherryPy and RESTful web api
2,715,227
11
2010-04-26T16:48:51Z
9,113,973
7
2012-02-02T14:26:43Z
[ "python", "rest", "cherrypy" ]
What's the best approach of creating a RESTful web api in CherryPy? I've been looking around for a few days now and nothing seems great. For Django it seems that are lots of tools to do this, but not for CherryPy or I am not aware of them. **Later edit:** How should I use Cherrypy to transform a request like /getOrder...
> Because HTTP defines these invocation methods, the most direct way to implement REST using CherryPy is to utilize the MethodDispatcher instead of the default dispatcher. More can be found in CherryPy docs: <http://cherrypy.readthedocs.org/en/latest/tutorial/REST.html> Here is also detailed description on how to sen...
Passing list and dictionary type parameter with Python
2,715,751
3
2010-04-26T18:09:55Z
2,715,781
7
2010-04-26T18:13:24Z
[ "python", "parameter-passing" ]
When I run this code ``` def func(x, y, *w, **z): print x print y if w: print w if z: print z else: print "None" func(10,20, 1,2,3,{'k':'a'}) ``` I get the result as follows. ``` 10 20 (1, 2, 3, {'k': 'a'}) None ``` But, I expected as follows, I mean the list parameters (1,2,3) matchin...
Put two asterisks before the dictionary: ``` func(10,20, 1,2,3,**{'k':'a'}) ```
Python: read streaming input from subprocess.communicate()
2,715,847
45
2010-04-26T18:23:18Z
2,716,032
28
2010-04-26T18:54:04Z
[ "python", "subprocess" ]
I'm using Python's `subprocess.communicate()` to read stdout from a process that runs for about a minute. How can I print out each line of that process's stdout in a streaming fashion, so that I can see the output as it's generated, but still block on the process terminating before continuing? `subprocess.communicate...
**Please note, I think [J.F. Sebastian's method (below)](http://stackoverflow.com/a/17698359/190597) is better.** --- Here is an simple example (with no checking for errors): ``` import subprocess proc = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, ...
Python: read streaming input from subprocess.communicate()
2,715,847
45
2010-04-26T18:23:18Z
17,698,359
69
2013-07-17T11:15:57Z
[ "python", "subprocess" ]
I'm using Python's `subprocess.communicate()` to read stdout from a process that runs for about a minute. How can I print out each line of that process's stdout in a streaming fashion, so that I can see the output as it's generated, but still block on the process terminating before continuing? `subprocess.communicate...
To get subprocess' output line by line as soon as the subprocess flushes its stdout buffer: ``` #!/usr/bin/env python2 from subprocess import Popen, PIPE p = Popen(["cmd", "arg1"], stdout=PIPE, bufsize=1) with p.stdout: for line in iter(p.stdout.readline, b''): print line, p.wait() # wait for the subproce...
mysql LOAD DATA INFILE with auto-increment primary key
2,716,054
14
2010-04-26T18:56:11Z
2,716,168
20
2010-04-26T19:15:50Z
[ "python", "mysql", "import", "load-data-infile" ]
I am trying to load a data file into mysql table using "LOAD DATA LOCAL INFILE 'filename' INTO TABLE 'tablename'". The problem is the source data file contains data of every fields but the primary key is missing ('id' column). I add a unique id field while I create the database but now I need to import the data into t...
Specify a column list: > By default, when no column list is provided at the end of the LOAD DATA INFILE statement, input lines are expected to contain a field for each table column. If you want to load only some of a table's columns, specify a column list: `LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata (col...
SQLAlchemy - SQLite for testing and Postgresql for development - How to port?
2,716,847
2
2010-04-26T20:59:45Z
2,717,071
16
2010-04-26T21:34:52Z
[ "python", "sqlite", "postgresql", "sqlalchemy" ]
I want to use sqlite memory database for all my testing and Postgresql for my development/production server. But the SQL syntax is not same in both dbs. for ex: SQLite has autoincrement, and Postgresql has serial Is it easy to port the SQL script from sqlite to postgresql... what are your solutions? If you want me t...
My suggestion would be: don't. The capabilities of Postgresql are far beyond what SQLite can provide, particularly in the areas of date/numeric support, functions and stored procedures, ALTER support, constraints, sequences, other types like UUID, etc., and even using various SQLAlchemy tricks to try to smooth that ove...
SQLAlchemy - SQLite for testing and Postgresql for development - How to port?
2,716,847
2
2010-04-26T20:59:45Z
2,721,100
8
2010-04-27T12:27:45Z
[ "python", "sqlite", "postgresql", "sqlalchemy" ]
I want to use sqlite memory database for all my testing and Postgresql for my development/production server. But the SQL syntax is not same in both dbs. for ex: SQLite has autoincrement, and Postgresql has serial Is it easy to port the SQL script from sqlite to postgresql... what are your solutions? If you want me t...
Don't do it. Don't test in one environment and release and develop in another. Your asking for buggy software using this process.
Forwarding an email with python smtplib
2,717,196
5
2010-04-26T21:54:34Z
4,566,267
12
2010-12-30T21:04:37Z
[ "python", "email", "smtp", "imap", "smtplib" ]
I'm trying to put together a script that automatically forwards certain emails that match a specific criteria to another email. I've got the downloading and parsing of messages using imaplib and email working, but I can't figure out how to forward an entire email to another address. Do I need to build a new message fr...
I think the part you had wrong was how to replace the headers in the message, and the fact that you don't need to make a copy of the message, you can just operate directly on it after creating it from the raw data you fetched from the IMAP server. You did omit some detail so here's my complete solution with all detail...
Find all Chinese text in a string using Python and Regex
2,718,196
8
2010-04-27T01:34:29Z
2,718,203
13
2010-04-27T01:36:00Z
[ "python", "regex", "cjk" ]
I needed to strip the Chinese out of a bunch of strings today and was looking for a simple Python regex. Any suggestions?
Found this out on the internets and it seems to work perfectly. ``` #!/usr/bin/env python # -*- encoding: utf8 -*- import re sample = u'I am from 美国。We should be friends. 朋友。' for n in re.findall(ur'[\u4e00-\u9fff]+',sample): print n ``` Output: ``` 美国 朋友 ```
Find all Chinese text in a string using Python and Regex
2,718,196
8
2010-04-27T01:34:29Z
2,718,268
19
2010-04-27T01:57:52Z
[ "python", "regex", "cjk" ]
I needed to strip the Chinese out of a bunch of strings today and was looking for a simple Python regex. Any suggestions?
The short, but relatively comprehensive answer for narrow Unicode builds of python (excluding ordinals > 65535 which can only be represented in narrow Unicode builds via surrogate pairs): ``` RE = re.compile(u'[⺀-⺙⺛-⻳⼀-⿕々〇〡-〩〸-〺〻㐀-䶵一-鿃豈-鶴侮-頻並-龎]', re.UNICODE) nochinese = R...
Where do I get a list of all known viruses signatures?
2,718,648
3
2010-04-27T04:04:32Z
2,718,767
10
2010-04-27T04:38:09Z
[ "python", "signature", "antivirus", "signatures" ]
I have written some antivirus software in Python, but am unable to find virus signatures. The software works by dumping each file on the hard disk to hex, thus getting the hex signature. Where do i get signatures for all the known viruses?
There's [Clamav](http://www.clamav.net/lang/en/), the open source GPL anti-virus. You can read its source code to see how it implements heuristics and other stuff. It's written in C, though. You can download a virus database there as well. They're free and updated frequently.
how to diff / align Python lists using arbitrary matching function?
2,718,809
7
2010-04-27T04:49:02Z
2,719,228
8
2010-04-27T06:44:02Z
[ "python", "diff" ]
I'd like to align two lists in a similar way to what `difflib.Differ` would do except I want to be able to define a match function for comparing items, not just use string equality, and preferably a match function that can return a number between 0.0 and 1.0, not just a boolean. So, for example, say I had the two list...
I just wrote this implementation of Needleman-Wunsch and it seems to do what I want: ``` def nw_align(a, b, replace_func, insert, delete): ZERO, LEFT, UP, DIAGONAL = 0, 1, 2, 3 len_a = len(a) len_b = len(b) matrix = [[(0, ZERO) for x in range(len_b + 1)] for y in range(len_a + 1)] for i in rang...
How to set timeout on python's socket recv method?
2,719,017
55
2010-04-27T05:51:46Z
2,719,036
26
2010-04-27T05:56:30Z
[ "python", "sockets", "timeout" ]
I need to set timeout on python's socket recv method. How to do it?
there's [`socket.settimeout()`](http://docs.python.org/library/socket#socket.socket.settimeout)
How to set timeout on python's socket recv method?
2,719,017
55
2010-04-27T05:51:46Z
2,721,734
76
2010-04-27T13:49:30Z
[ "python", "sockets", "timeout" ]
I need to set timeout on python's socket recv method. How to do it?
The typical approach is to use [select()](http://docs.python.org/library/select.html#select.select) to wait until data is available or until the timeout occurs. Only call `recv()` when data is actually available. To be safe, we also set the socket to non-blocking mode to guarantee that `recv()` will never block indefin...
How to set timeout on python's socket recv method?
2,719,017
55
2010-04-27T05:51:46Z
25,533,241
10
2014-08-27T17:15:52Z
[ "python", "sockets", "timeout" ]
I need to set timeout on python's socket recv method. How to do it?
As mentioned both [`select.select()`](https://docs.python.org/library/select.html#select.select) and [`socket.settimeout()`](http://docs.python.org/library/socket#socket.socket.settimeout) will work. Note you might need to call `settimeout` twice for your needs, e.g. ``` sock = socket.socket(socket.AF_INET, socket.SO...
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
3,452,888
1,009
2010-08-10T19:56:49Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
There isn't a built-in flag yet, but you can use ``` pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U ``` Note: there are infinite potential variations for this. I'm trying to keep this answer short and simple, but please do suggest variations in the comments! Relevant edits: * Added ...
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
5,839,291
370
2011-04-30T03:31:16Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
You can use the following Python code. Unlike `pip freeze`, this will not print warnings and FIXME errors. ``` import pip from subprocess import call for dist in pip.get_installed_distributions(): call("pip install --upgrade " + dist.project_name, shell=True) ```
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
6,306,608
62
2011-06-10T12:50:49Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
You can just print the packages that are outdated ``` pip freeze | cut -d = -f 1 | xargs -n 1 pip search | grep -B2 'LATEST:' ```
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
7,399,772
10
2011-09-13T09:42:32Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
when using a virtualenv and if you just want to upgrade packages **added** to your virtualenv, you may want to do: ``` pip install `pip freeze -l | cut --fields=1 -d = -` --upgrade ```
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
9,446,559
59
2012-02-25T18:04:34Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
Windows version after consulting excellent [documentation](http://www.robvanderwoude.com/ntfor.php#FOR_F) for `FOR` by Rob van der Woude `for /F "delims===" %i in ('pip freeze -l') do pip install -U %i`
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
10,001,798
23
2012-04-03T21:38:18Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
From <https://github.com/cakebread/yolk> : ``` $ pip install -U `yolk -U | awk '{print $1}' | uniq` ``` however you need to get yolk first: ``` $ sudo pip install -U yolk ```
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
13,104,909
7
2012-10-27T22:56:07Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
@Ramana's worked the best for me, of those here, but I had to add a few catches: ``` import pip for dist in pip.get_installed_distributions(): if 'site-packages' in dist.location: try: pip.call_subprocess(['pip', 'install', '-U', dist.key]) except Exception, exc: print exc `...
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
16,269,635
276
2013-04-29T00:34:37Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
To upgrade all local packages; you could use [`pip-review`](https://github.com/jgonggrijp/pip-review): ``` $ pip install pip-review $ pip-review --local --interactive ``` --- `pip-review` is a fork of `pip-tools`. See [`pip-tools` issue](https://github.com/nvie/pip-tools/issues/185) mentioned by [@knedlsepp](http://...
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
16,692,085
19
2013-05-22T12:42:20Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
One-liner version of @Ramana's answer. ``` python -c 'import pip, subprocess; [subprocess.call("pip install -U " + d.project_name, shell=1) for d in pip.get_installed_distributions()]' ``` `
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
17,689,760
10
2013-07-17T01:43:47Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
You can try this : ``` for i in ` pip list|awk -F ' ' '{print $1}'`;do pip install --upgrade $i;done ```
Upgrading all packages with pip
2,720,014
859
2010-04-27T09:23:25Z
22,260,015
40
2014-03-07T20:25:15Z
[ "python", "pip" ]
Is it possible to upgrade all Python packages at one time with pip? Note that there is [a feature request](https://github.com/pypa/pip/issues/59) for this on the official issue tracker.
The following one-liner might prove of help: `pip list --outdated | sed 's/(.*//g' | xargs -n1 pip install -U` `xargs -n1` keeps going if an error occurs. If you need more fine grained control over what is omitted and what raises an error you should not add the `-n1` flag and explicitly define the errors to ignore, ...