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 |
|---|---|---|---|---|---|---|---|---|---|
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 103,081 | 674 | 2008-09-19T15:45:15Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | If you'd like defaults you could use the dictionary [`get(key[, default])`](https://docs.python.org/2/library/stdtypes.html#dict.get) method:
```
def f(x):
return {
'a': 1,
'b': 2,
}.get(x, 9) # 9 is default if x not found
``` |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 109,245 | 25 | 2008-09-20T20:20:05Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | A true `switch/case` in Python is going to be more difficult than a dictionary method or `if/elif/else` methods because the simple versions do not support fall through.
Another downfall of the `if/elif/else` method is the need for repeated comparisons.
The C implementation of a `switch/case` has a performance benefit... |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 323,259 | 341 | 2008-11-27T08:53:01Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | [Python Cookbook](http://www.activestate.com/ASPN/Python/Cookbook/) has several recipes (implementations and corresponding discussions) for switch statement. Please visit the following links:
1. [Readable switch construction without lambdas or dictionaries](http://code.activestate.com/recipes/410692/)
2. [Exception-ba... |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 3,828,986 | 16 | 2010-09-30T08:31:55Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | Let's say you don't want to just return a value, but want to use methods that change something on an object. Using the approach stated here would be:
```
result = {
'a': obj.increment(x),
'b': obj.decrement(x)
}.get(value, obj.default(x))
```
What happens here is that python evaluates all methods in the dictionar... |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 4,367,749 | 9 | 2010-12-06T15:08:12Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | If you're searching extra-statement, as "switch", I built a python module that extends Python. It's called [ESPY](http://elp.chronocv.fr/?lng=en) as "Enhanced Structure for Python" and it's available for both Python 2.x and Python 3.x.
For example, in this case, a switch statement could be performed by the following c... |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 6,606,504 | 56 | 2011-07-07T06:09:09Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | ```
class switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True
def case(*args):
return any((arg == switch.value for arg in args))
```
Usage:
```
while switch(n):
if case(0):
print "You typed zero."
break
if case(1, 4, 9):
... |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 6,606,540 | 32 | 2011-07-07T06:12:47Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | My favorite one is a really nice [recipe](http://code.activestate.com/recipes/410692/). You'll really like it. It's the closest one I've seen to actual switch case statements, especially in features.
Here's an example:
```
# The following example is pretty much the exact use-case of a dictionary,
# but is included fo... |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 10,272,369 | 10 | 2012-04-22T21:43:03Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | If you have a complicated case block you can consider using a function dictionary lookup table...
If you haven't done this before its a good idea to step into your debugger and view exactly how the dictionary looks up each function.
NOTE: Do *not* use "()" inside the case/dictionary lookup or it will call each of you... |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 19,335,626 | 7 | 2013-10-12T15:04:01Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | I didn't find the simple answer I was looking for anywhere on Google search. But I figured it out anyway. It's really quite simple. Decided to post it, and maybe prevent a few less scratches on someone else's head. The key is simply "in" and tuples. Here is the switch statement behavior with fall-through, including RAN... |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 27,746,465 | 7 | 2015-01-02T18:01:25Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | I found that a common switch structure:
```
switch ...parameter...
case p1: v1; break;
case p2: v2; break;
default: v3;
```
can be expressed in Python as follows:
```
(lambda x: v1 if p1(x) else v2 if p2(x) else v3)
```
or formatted in a clearer way:
```
(lambda x:
v1 if p1(x) else
v2 if p2(x) else
... |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 30,012,053 | 8 | 2015-05-03T09:05:43Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | ```
class Switch:
def __init__(self, value): self._val = value
def __enter__(self): return self
def __exit__(self, type, value, traceback): return False # Allows traceback to occur
def __call__(self, cond, *mconds): return self._val in (cond,)+mconds
from datetime import datetime
with Switch(datetime.t... |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 30,881,320 | 34 | 2015-06-17T02:25:10Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | My favorite Python recipe for switch/case is:
```
choices = {'a': 1, 'b': 2}
result = choices.get(key, 'default')
```
Short and simple for simple scenarios.
Compare to 11+ lines of C code:
```
// C Language version of a simple 'switch/case'.
switch( key )
{
case 'a' :
result = 1;
break;
cas... |
Windows Mobile development in Python | 60,446 | 3 | 2008-09-13T09:56:04Z | 60,448 | 9 | 2008-09-13T10:03:55Z | [
"python",
"windows-mobile"
] | What is the best way to start developing Windows Mobile Professional applications in Python? Is there a reasonable SDK including an emulator? Is it even possible without doing excessive amount of underlaying Windows API calls for UI for instance? | ## Python CE
Python port for Windows CE (Pocket PC) devices. Intended to be as close to desktop version as possible (console, current directory support, testsuite passed).
[](http://pythonce.sourceforge.net/)

Forget about python. Even if it's technically possible:
* your app will be big (you'll have to bundle the whole python runtime with your app)
* your app will use lots of memory (python is a memory hog, relative to C/C++)
* your app will be slow
* you wont find any d... |
cross platform IPC | 60,649 | 53 | 2008-09-13T16:10:34Z | 60,660 | 13 | 2008-09-13T16:19:10Z | [
"c++",
"python",
"linux",
"cross-platform",
"ipc"
] | I'm looking for suggestions on possible IPC mechanisms that are:
* **cross platform** (WIN32 and Linux at least)
* Simple to implement in **C++** as well as the **most common scripting languages** (perl, ruby python etc).
* Finally, **simple to use** from a programming point of view!
What are my options? I'm programm... | For C++, check out [Boost IPC](http://www.boost.org/doc/libs/1_36_0/doc/html/interprocess.html).
You can probably create or find some bindings for the scripting languages as well.
Otherwise if it's really important to be able to interface with scripting languages your best bet is simply to use files, pipes or socket... |
cross platform IPC | 60,649 | 53 | 2008-09-13T16:10:34Z | 65,924 | 42 | 2008-09-15T19:22:37Z | [
"c++",
"python",
"linux",
"cross-platform",
"ipc"
] | I'm looking for suggestions on possible IPC mechanisms that are:
* **cross platform** (WIN32 and Linux at least)
* Simple to implement in **C++** as well as the **most common scripting languages** (perl, ruby python etc).
* Finally, **simple to use** from a programming point of view!
What are my options? I'm programm... | In terms of speed, the best cross-platform IPC mechanism will be pipes. That assumes, however, that you want cross-platform IPC on the same machine. If you want to be able to talk to processes on remote machines, you'll want to look at using sockets instead. Luckily, if you're talking about TCP at least, sockets and pi... |
cross platform IPC | 60,649 | 53 | 2008-09-13T16:10:34Z | 67,532 | 7 | 2008-09-15T22:11:03Z | [
"c++",
"python",
"linux",
"cross-platform",
"ipc"
] | I'm looking for suggestions on possible IPC mechanisms that are:
* **cross platform** (WIN32 and Linux at least)
* Simple to implement in **C++** as well as the **most common scripting languages** (perl, ruby python etc).
* Finally, **simple to use** from a programming point of view!
What are my options? I'm programm... | You might want to try [YAMI](http://www.msobczak.com/prog/yami/) , it's very simple yet functional, portable and comes with binding to few languages |
cross platform IPC | 60,649 | 53 | 2008-09-13T16:10:34Z | 74,590 | 8 | 2008-09-16T17:04:46Z | [
"c++",
"python",
"linux",
"cross-platform",
"ipc"
] | I'm looking for suggestions on possible IPC mechanisms that are:
* **cross platform** (WIN32 and Linux at least)
* Simple to implement in **C++** as well as the **most common scripting languages** (perl, ruby python etc).
* Finally, **simple to use** from a programming point of view!
What are my options? I'm programm... | Why not D-Bus? It's a very simple message passing system that runs on almost all platforms and is designed for robustness. It's supported by pretty much every scripting language at this point.
<http://freedesktop.org/wiki/Software/dbus> |
How do I write a python HTTP server to listen on multiple ports? | 60,680 | 14 | 2008-09-13T16:42:38Z | 60,753 | 27 | 2008-09-13T18:22:06Z | [
"python",
"webserver"
] | I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?
What I'm doing now:
```
class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def doGET
[...]
class ThreadingHTTPServer... | Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both <http://localhost:1111/> and <http://localhost:2222/>
```... |
Getting random row through SQLAlchemy | 60,805 | 49 | 2008-09-13T19:58:02Z | 60,815 | 63 | 2008-09-13T20:09:28Z | [
"python",
"sql",
"database",
"sqlalchemy"
] | How do I select a(or some) random row(s) from a table using SQLAlchemy? | This is very much a database-specific issue.
I know that PostgreSQL and MySQL have the ability to order by a random function, so you can use this in SQLAlchemy:
```
from sqlalchemy.sql.expression import func, select
select.order_by(func.random()) # for PostgreSQL, SQLite
select.order_by(func.rand()) # for MySQL
s... |
Getting random row through SQLAlchemy | 60,805 | 49 | 2008-09-13T19:58:02Z | 390,676 | 20 | 2008-12-24T03:22:30Z | [
"python",
"sql",
"database",
"sqlalchemy"
] | How do I select a(or some) random row(s) from a table using SQLAlchemy? | If you are using the orm and the table is not big (or you have its amount of rows cached) and you want it to be database independent the really simple approach is.
```
import random
rand = random.randrange(0, session.query(Table).count())
row = session.query(Table)[rand]
```
This is cheating slightly but thats why y... |
Getting random row through SQLAlchemy | 60,805 | 49 | 2008-09-13T19:58:02Z | 14,906,244 | 10 | 2013-02-16T02:19:56Z | [
"python",
"sql",
"database",
"sqlalchemy"
] | How do I select a(or some) random row(s) from a table using SQLAlchemy? | There is a simple way to pull a random row that IS database independent.
Just use .offset() . No need to pull all rows:
```
import random
query = DBSession.query(Table)
rowCount = int(query.count())
randomRow = query.offset(int(rowCount*random.random())).first()
```
Where Table is your table (or you could put any que... |
How do you retrieve items from a dictionary in the order that they're inserted? | 60,848 | 44 | 2008-09-13T20:38:05Z | 60,862 | 44 | 2008-09-13T20:48:36Z | [
"python",
"dictionary"
] | Is it possible to retrieve items from a Python dictionary in the order that they were inserted? | The standard python `dict` isn't able to do this.
There is a proposal ([PEP 372](http://www.python.org/dev/peps/pep-0372/)) to add an "ordered dictionary" (that keeps track of the order of insertion) to the `collections` module in the standard library. It includes links to [various](http://babel.edgewall.org/browser/t... |
How do you retrieve items from a dictionary in the order that they're inserted? | 60,848 | 44 | 2008-09-13T20:38:05Z | 61,031 | 16 | 2008-09-14T00:58:30Z | [
"python",
"dictionary"
] | Is it possible to retrieve items from a Python dictionary in the order that they were inserted? | The other answers are correct; it's not possible, but you could write this yourself. However, in case you're unsure how to actually implement something like this, here's a complete and working implementation that subclasses dict which I've just written and tested. (Note that the order of values passed to the constructo... |
Where do the Python unit tests go? | 61,151 | 286 | 2008-09-14T05:41:11Z | 61,168 | 10 | 2008-09-14T06:46:03Z | [
"python",
"unit-testing",
"code-organization"
] | If you're writing a library, or an app, where do the unit test files go?
It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing.
Is there a best prac... | I don't believe there is an established "best practice".
I put my tests in another directory outside of the app code. I then add the main app directory to sys.path (allowing you to import the modules from anywhere) in my test runner script (which does some other stuff as well) before running all the tests. This way I ... |
Where do the Python unit tests go? | 61,151 | 286 | 2008-09-14T05:41:11Z | 61,169 | 36 | 2008-09-14T06:46:14Z | [
"python",
"unit-testing",
"code-organization"
] | If you're writing a library, or an app, where do the unit test files go?
It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing.
Is there a best prac... | A common practice is to put the tests directory in the same parent directory as your module/package. So if your module was called foo.py your directory layout would look like:
```
parent_dir/
foo.py
tests/
```
Of course there is no one way of doing it. You could also make a tests subdirectory and import the modul... |
Where do the Python unit tests go? | 61,151 | 286 | 2008-09-14T05:41:11Z | 61,531 | 13 | 2008-09-14T18:18:58Z | [
"python",
"unit-testing",
"code-organization"
] | If you're writing a library, or an app, where do the unit test files go?
It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing.
Is there a best prac... | I use a `tests/` directory, and then import the main application modules using relative imports. So in MyApp/tests/foo.py, there might be:
```
from .. import foo
```
to import the `MyApp.foo` module. |
Where do the Python unit tests go? | 61,151 | 286 | 2008-09-14T05:41:11Z | 62,527 | 102 | 2008-09-15T12:52:00Z | [
"python",
"unit-testing",
"code-organization"
] | If you're writing a library, or an app, where do the unit test files go?
It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing.
Is there a best prac... | For a file `module.py`, the unit test should normally be called `test_module.py`, following Pythonic naming conventions.
There are several commonly accepted places to put `test_module.py`:
1. In the same directory as `module.py`.
2. In `../tests/test_module.py` (at the same level as the code directory).
3. In `tests/... |
Where do the Python unit tests go? | 61,151 | 286 | 2008-09-14T05:41:11Z | 103,610 | 18 | 2008-09-19T16:46:53Z | [
"python",
"unit-testing",
"code-organization"
] | If you're writing a library, or an app, where do the unit test files go?
It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing.
Is there a best prac... | I also tend to put my unit tests in the file itself, as Jeremy Cantrell above notes, although I tend to not put the test function in the main body, but rather put everything in an
```
if __name__ == '__main__':
do tests...
```
block. This ends up adding documentation to the file as 'example code' for how to use th... |
Where do the Python unit tests go? | 61,151 | 286 | 2008-09-14T05:41:11Z | 815,212 | 23 | 2009-05-02T17:08:05Z | [
"python",
"unit-testing",
"code-organization"
] | If you're writing a library, or an app, where do the unit test files go?
It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing.
Is there a best prac... | We had the very same question when writing Pythoscope (<http://pythoscope.org>), which generates unit tests for Python programs. We polled people on the testing in python list before we chose a directory, there were many different opinions. In the end we chose to put a "tests" directory in the same directory as the sou... |
Where do the Python unit tests go? | 61,151 | 286 | 2008-09-14T05:41:11Z | 23,386,287 | 18 | 2014-04-30T10:58:51Z | [
"python",
"unit-testing",
"code-organization"
] | If you're writing a library, or an app, where do the unit test files go?
It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing.
Is there a best prac... | ## Only 1 test file
If doesn't have many test file, put in top-level directory is nice (I think this is python recommended way):
```
module/
lib/
__init__.py
module.py
test.py
```
## Many test file
If has many test file, put in a `tests` folder:
```
module/
lib/
__init__.py
module.py
tests/... |
Python dictionary from an object's fields | 61,517 | 174 | 2008-09-14T18:00:43Z | 61,522 | 45 | 2008-09-14T18:07:55Z | [
"python",
"dictionary",
"attributes",
"object",
"metaprogramming"
] | Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:
```
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
```
**NOTE:** It should not include methods. Only fields.
... | The `dir` builtin will give you all the object's attributes, including special methods like `__str__`, `__dict__` and a whole bunch of others which you probably don't want. But you can do something like:
```
>>> class Foo(object):
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> [name for name in dir(... |
Python dictionary from an object's fields | 61,517 | 174 | 2008-09-14T18:00:43Z | 61,551 | 19 | 2008-09-14T18:50:52Z | [
"python",
"dictionary",
"attributes",
"object",
"metaprogramming"
] | Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:
```
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
```
**NOTE:** It should not include methods. Only fields.
... | I've settled with a combination of both answers:
```
dict((key, value) for key, value in f.__dict__.iteritems()
if not callable(value) and not key.startswith('__'))
``` |
Python dictionary from an object's fields | 61,517 | 174 | 2008-09-14T18:00:43Z | 62,680 | 227 | 2008-09-15T13:08:56Z | [
"python",
"dictionary",
"attributes",
"object",
"metaprogramming"
] | Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:
```
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
```
**NOTE:** It should not include methods. Only fields.
... | Note that best practice in current versions of Python is to use *new-style* classes, i.e.
```
class Foo(object):
...
```
Also, there's a difference between an 'object' and a 'class'. To build a dictionary from an arbitrary *object*, it's sufficient to use `__dict__`. Usually, you'll declare your methods at class leve... |
Python dictionary from an object's fields | 61,517 | 174 | 2008-09-14T18:00:43Z | 63,635 | 10 | 2008-09-15T14:56:01Z | [
"python",
"dictionary",
"attributes",
"object",
"metaprogramming"
] | Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:
```
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
```
**NOTE:** It should not include methods. Only fields.
... | > To build a dictionary from an arbitrary *object*, it's sufficient to use `__dict__`.
This misses attributes that the object inherits from its class. For example,
```
class c(object):
x = 3
a = c()
```
hasattr(a, 'x') is true, but 'x' does not appear in a.\_\_dict\_\_ |
Python dictionary from an object's fields | 61,517 | 174 | 2008-09-14T18:00:43Z | 31,770,231 | 14 | 2015-08-02T08:57:29Z | [
"python",
"dictionary",
"attributes",
"object",
"metaprogramming"
] | Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:
```
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
```
**NOTE:** It should not include methods. Only fields.
... | Instead of `x.__dict__`, it's actually more pythonic to use `vars(x)`. |
Is it pythonic for a function to return multiple values? | 61,605 | 66 | 2008-09-14T20:15:19Z | 61,629 | 24 | 2008-09-14T20:42:01Z | [
"python",
"function",
"return-value"
] | In python, you can have a function return multiple values. Here's a contrived example:
```
def divide(x, y):
quotient = x/y
remainder = x % y
return quotient, remainder
(q, r) = divide(22, 7)
```
This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we... | Firstly, note that Python allows for the following (no need for the parenthesis):
```
q, r = divide(22, 7)
```
Regarding your question, there's no hard and fast rule either way. For simple (and usually contrived) examples, it may seem that it's always possible for a given function to have a single purpose, resulting ... |
Is it pythonic for a function to return multiple values? | 61,605 | 66 | 2008-09-14T20:15:19Z | 61,636 | 84 | 2008-09-14T20:54:14Z | [
"python",
"function",
"return-value"
] | In python, you can have a function return multiple values. Here's a contrived example:
```
def divide(x, y):
quotient = x/y
remainder = x % y
return quotient, remainder
(q, r) = divide(22, 7)
```
This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we... | Absolutely (for the example you provided).
### Tuples are first class citizens in Python
There is a builtin function [`divmod()`](http://docs.python.org/lib/built-in-funcs.html) that does exactly that.
```
q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x
```
There are other examples: `zip`, `enu... |
Is it pythonic for a function to return multiple values? | 61,605 | 66 | 2008-09-14T20:15:19Z | 61,637 | 12 | 2008-09-14T20:55:28Z | [
"python",
"function",
"return-value"
] | In python, you can have a function return multiple values. Here's a contrived example:
```
def divide(x, y):
quotient = x/y
remainder = x % y
return quotient, remainder
(q, r) = divide(22, 7)
```
This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we... | The example you give is actually a python builtin function, called `divmod`. So someone, at some point in time, thought that it was pythonic enough to include in the core functionality.
To me, if it makes the code cleaner, it is pythonic. Compare these two code blocks:
```
seconds = 1234
minutes, seconds = divmod(sec... |
Is there a way around coding in Python without the tab, indent & whitespace criteria? | 63,086 | 6 | 2008-09-15T13:55:14Z | 63,094 | 33 | 2008-09-15T13:56:47Z | [
"python"
] | I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?
I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting? | No. Indentation-as-grammar is an integral part of the Python language, for better and worse. |
Is there a way around coding in Python without the tab, indent & whitespace criteria? | 63,086 | 6 | 2008-09-15T13:55:14Z | 68,061 | 9 | 2008-09-15T23:56:17Z | [
"python"
] | I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?
I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting? | Emacs! Seriously, its use of "tab is a *command*, not a *character*", is absolutely perfect for python development. |
Is there a way around coding in Python without the tab, indent & whitespace criteria? | 63,086 | 6 | 2008-09-15T13:55:14Z | 68,702 | 36 | 2008-09-16T01:55:09Z | [
"python"
] | I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?
I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting? | ```
from __future__ import braces
``` |
When to create a new app (with startapp) in Django? | 64,237 | 48 | 2008-09-15T16:03:22Z | 64,308 | 7 | 2008-09-15T16:12:39Z | [
"python",
"django"
] | I've googled around for this, but I still have trouble relating to what Django defines as "apps".
Should I create a new app for each piece of functionality in a site, even though it uses models from the main project?
Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality to... | I tend to create new applications for each logically separate set of models. e.g.:
* User Profiles
* Forum Posts
* Blog posts |
When to create a new app (with startapp) in Django? | 64,237 | 48 | 2008-09-15T16:03:22Z | 64,464 | 11 | 2008-09-15T16:32:07Z | [
"python",
"django"
] | I've googled around for this, but I still have trouble relating to what Django defines as "apps".
Should I create a new app for each piece of functionality in a site, even though it uses models from the main project?
Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality to... | I prefer to think of Django applications as reusable modules or components than as "applications".
This helps me encapsulate and decouple certain features from one another, improving re-usability should I decide to share a particular "app" with the community at large, and maintainability.
My general approach is to bu... |
When to create a new app (with startapp) in Django? | 64,237 | 48 | 2008-09-15T16:03:22Z | 64,492 | 25 | 2008-09-15T16:35:16Z | [
"python",
"django"
] | I've googled around for this, but I still have trouble relating to what Django defines as "apps".
Should I create a new app for each piece of functionality in a site, even though it uses models from the main project?
Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality to... | James Bennett has a wonderful [set of slides](http://www.b-list.org/weblog/2008/mar/15/slides/) on how to organize reusable apps in Django. |
When to create a new app (with startapp) in Django? | 64,237 | 48 | 2008-09-15T16:03:22Z | 8,034,555 | 7 | 2011-11-07T09:15:00Z | [
"python",
"django"
] | I've googled around for this, but I still have trouble relating to what Django defines as "apps".
Should I create a new app for each piece of functionality in a site, even though it uses models from the main project?
Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality to... | Here is the updated presentation on 6 September 2008.
<http://www.youtube.com/watch?v=A-S0tqpPga4>
<http://media.b-list.org/presentations/2008/djangocon/reusable_apps.pdf>
> ## Taken from the slide
>
> Should this be its own application?
>
> * Is it completely unrelated to the appâs focus?
> * Is it orthogonal to ... |
Best Python supported server/client protocol? | 64,426 | 9 | 2008-09-15T16:27:47Z | 76,560 | 9 | 2008-09-16T20:23:37Z | [
"python",
"client"
] | I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol. | If you are looking to do file transfers, XMLRPC is likely a bad choice. It will require that you encode all of your data as XML (and load it into memory).
"Data requests" and "file transfers" sounds a lot like plain old HTTP to me, but your statement of the problem doesn't make your requirements clear. What kind of in... |
Best Python supported server/client protocol? | 64,426 | 9 | 2008-09-15T16:27:47Z | 292,659 | 7 | 2008-11-15T15:16:25Z | [
"python",
"client"
] | I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol. | [ProtocolBuffers](http://code.google.com/p/protobuf/) was released by Google as a way of serializing data in a very compact efficient way. They have support for C++, Java and Python. I haven't used it yet, but looking at the source, there seem to be RPC clients and servers for each language.
I personally have used XML... |
Sending mail from Python using SMTP | 64,505 | 70 | 2008-09-15T16:36:35Z | 64,890 | 74 | 2008-09-15T17:24:40Z | [
"python",
"smtp"
] | I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?
```
from smtplib import SMTP
import datetime
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')... | The script I use is quite similar; I post it here as an example of how to use the email.\* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.
I rely on my ISP to add the date time header.
My ISP requires me to use a secure smtp connection to send mail, I rely on the ssmt... |
Sending mail from Python using SMTP | 64,505 | 70 | 2008-09-15T16:36:35Z | 275,124 | 18 | 2008-11-08T20:12:26Z | [
"python",
"smtp"
] | I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?
```
from smtplib import SMTP
import datetime
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')... | Also if you want to do smtp auth with TLS as opposed to SSL then you just have to change the port (use 587) and do smtp.starttls(). This worked for me:
```
...
smtp.connect('YOUR.MAIL.SERVER', 587)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login('USERNAME@DOMAIN', 'PASSWORD')
...
``` |
Sending mail from Python using SMTP | 64,505 | 70 | 2008-09-15T16:36:35Z | 17,596,848 | 38 | 2013-07-11T14:59:54Z | [
"python",
"smtp"
] | I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?
```
from smtplib import SMTP
import datetime
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')... | The method I commonly use...not much different but a little bit
```
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
msg = MIMEMultipart()
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
ms... |
How to setup VIM autoindentation properly for editing Python files - *.py | 65,076 | 47 | 2008-09-15T17:48:22Z | 65,122 | 42 | 2008-09-15T17:53:33Z | [
"python",
"vim",
"configuration",
"spaces"
] | I've troubles setting VIM (7.1.xxx) for editing python files.
Indenting seems to be broken (optimal 4 spaces).
I've followed some tutorials I found via Google. Still no effect :/
Please help. | I use this on my macbook:
```
" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set noexpandtab
au BufRead,BufNewFile *.h set noexpandtab
au BufRead,BufNewFile Makefile* set noexpandtab
" ------------------------------------------------------------... |
Caching compiled regex objects in Python? | 65,266 | 17 | 2008-09-15T18:10:35Z | 65,440 | 12 | 2008-09-15T18:29:51Z | [
"python",
"regex",
"caching"
] | Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory.
```
a = re.compile("a.*b")
b = re.compile("c.*d")
...
```
Question: Is it possible to store these regular expressions in a ca... | > Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?
Not easily. You'd have to write a custom serializer that hooks into the C `sre` implementation of the Python regex engine. Any performance benefits would be ... |
How to add method using metaclass | 65,400 | 5 | 2008-09-15T18:24:14Z | 65,716 | 10 | 2008-09-15T19:01:27Z | [
"python",
"metaclass"
] | How do I add an instance method to a class using a metaclass (yes I do need to use a metaclass)? The following kind of works, but the func\_name will still be "foo":
```
def bar(self):
print "bar"
class MetaFoo(type):
def __new__(cls, name, bases, dict):
dict["foobar"] = bar
return type(name, ... | Try dynamically extending the bases that way you can take advantage of the mro and the methods are actual methods:
```
class Parent(object):
def bar(self):
print "bar"
class MetaFoo(type):
def __new__(cls, name, bases, dict):
return type(name, (Parent,) + bases, dict)
class Foo(object):
__me... |
How do I create a new signal in pygtk | 66,730 | 6 | 2008-09-15T20:41:58Z | 67,743 | 10 | 2008-09-15T22:52:27Z | [
"python",
"gtk",
"pygtk",
"gobject"
] | I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object. | You can also define signals inside the class definition:
```
class MyGObjectClass(gobject.GObject):
__gsignals__ = {
"some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
}
```
The contents of the tuple are the the same as the three last arguments to `gobject.signal_new`. |
Serving dynamically generated ZIP archives in Django | 67,454 | 41 | 2008-09-15T22:00:31Z | 72,180 | 36 | 2008-09-16T13:30:56Z | [
"python",
"django"
] | How to serve users a dynamically generated ZIP archive in Django?
I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't current... | The solution is as follows.
Use Python module [zipfile](http://docs.python.org/lib/module-zipfile.html) to create zip archive, but as the file specify [StringIO](http://docs.python.org/lib/module-StringIO.html) object (ZipFile constructor requires file-like object). Add files you want to compress. Then in your Django ... |
Serving dynamically generated ZIP archives in Django | 67,454 | 41 | 2008-09-15T22:00:31Z | 12,951,461 | 29 | 2012-10-18T09:32:10Z | [
"python",
"django"
] | How to serve users a dynamically generated ZIP archive in Django?
I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't current... | Here's a Django view to do this:
```
import os
import zipfile
import StringIO
from django.http import HttpResponse
def getfiles(request):
# Files (local path) to put in the .zip
# FIXME: Change this (get paths from DB etc)
filenames = ["/tmp/file1.txt", "/tmp/file2.txt"]
# Folder name in ZIP archiv... |
How to import a module given the full path? | 67,631 | 498 | 2008-09-15T22:30:55Z | 67,692 | 575 | 2008-09-15T22:41:16Z | [
"python",
"configuration",
"python-import",
"python-module"
] | How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option. | For Python 3.5+ use:
```
import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()
```
For Python 3.3 and 3.4 use:
```
from importlib.machinery import SourceFileLoader
foo = SourceFile... |
How to import a module given the full path? | 67,631 | 498 | 2008-09-15T22:30:55Z | 67,693 | 12 | 2008-09-15T22:41:24Z | [
"python",
"configuration",
"python-import",
"python-module"
] | How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option. | You can use the
```
load_source(module_name, path_to_file)
```
method from [imp module](https://docs.python.org/library/imp.html). |
How to import a module given the full path? | 67,631 | 498 | 2008-09-15T22:30:55Z | 67,708 | 13 | 2008-09-15T22:44:50Z | [
"python",
"configuration",
"python-import",
"python-module"
] | How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option. | You can also do something like this and add the directory that the configuration file is sitting in to the Python load path, and then just do a normal import, assuming you know the name of the file in advance, in this case "config".
Messy, but it works.
```
configfile = '~/config.py'
import os
import sys
sys.path.a... |
How to import a module given the full path? | 67,631 | 498 | 2008-09-15T22:30:55Z | 67,715 | 8 | 2008-09-15T22:46:35Z | [
"python",
"configuration",
"python-import",
"python-module"
] | How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option. | Do you mean load or import?
You can manipulate the sys.path list specify the path to your module, then import your module. For example, given a module at:
```
/foo/bar.py
```
You could do:
```
import sys
sys.path[0:0] = '/foo' # puts the /foo directory at the start of your path
import bar
``` |
How to import a module given the full path? | 67,631 | 498 | 2008-09-15T22:30:55Z | 68,628 | 9 | 2008-09-16T01:43:04Z | [
"python",
"configuration",
"python-import",
"python-module"
] | How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option. | ```
def import_file(full_path_to_module):
try:
import os
module_dir, module_file = os.path.split(full_path_to_module)
module_name, module_ext = os.path.splitext(module_file)
save_cwd = os.getcwd()
os.chdir(module_dir)
module_obj = __import__(module_name)
modul... |
How to import a module given the full path? | 67,631 | 498 | 2008-09-15T22:30:55Z | 129,374 | 185 | 2008-09-24T19:36:16Z | [
"python",
"configuration",
"python-import",
"python-module"
] | How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option. | The advantage of adding a path to sys.path (over using imp) is that it simplifies things when importing more than one module from a single package. For example:
```
import sys
# the mock-0.3.1 dir contains testcase.py, testutils.py & mock.py
sys.path.append('/foo/bar/mock-0.3.1')
from testcase import TestCase
from te... |
Why do you need explicitly have the "self" argument into a Python method? | 68,282 | 125 | 2008-09-16T00:39:55Z | 68,320 | 37 | 2008-09-16T00:47:18Z | [
"python"
] | When defining a method on a class in Python, it looks something like this:
```
class MyClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
```
But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declarin... | It's to minimize the difference between methods and functions. It allows you to easily generate methods in metaclasses, or add methods at runtime to pre-existing classes.
e.g.
```
>>> class C(object):
... def foo(self):
... print "Hi!"
...
>>>
>>> def bar(self):
... print "Bork bork bork!"
...
>>>
>>>... |
Why do you need explicitly have the "self" argument into a Python method? | 68,282 | 125 | 2008-09-16T00:39:55Z | 68,324 | 68 | 2008-09-16T00:47:55Z | [
"python"
] | When defining a method on a class in Python, it looks something like this:
```
class MyClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
```
But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declarin... | I like to quote Peters' Zen of Python. "Explicit is better than implicit."
In Java and C++, '`this.`' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't.
Python elects to make things like this explicit rather than based on a rule.
Addit... |
Why do you need explicitly have the "self" argument into a Python method? | 68,282 | 125 | 2008-09-16T00:39:55Z | 68,472 | 10 | 2008-09-16T01:15:16Z | [
"python"
] | When defining a method on a class in Python, it looks something like this:
```
class MyClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
```
But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declarin... | Python doesn't force you on using "self". You can give it whatever name you want. You just have to remember that the first argument in a method definition header is a reference to the object. |
Why do you need explicitly have the "self" argument into a Python method? | 68,282 | 125 | 2008-09-16T00:39:55Z | 308,045 | 38 | 2008-11-21T06:28:26Z | [
"python"
] | When defining a method on a class in Python, it looks something like this:
```
class MyClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
```
But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declarin... | I suggest that one should read [Guido van Rossum's blog](http://neopythonic.blogspot.com/) on this topic - [Why explicit self has to stay](http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html).
> When a method definition is decorated, we don't know whether to automatically give it a 'self' parame... |
Change command Method for Tkinter Button in Python | 68,327 | 3 | 2008-09-16T00:48:37Z | 68,524 | 12 | 2008-09-16T01:24:37Z | [
"python",
"user-interface",
"tkinter"
] | I create a new Button object but did not specify the `command` option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created? | Though [Eli Courtwright's](http://stackoverflow.com/questions/68327/change-command-method-for-tkinter-button-in-python#68455) program will work fine¹, what you really seem to want though is just a way to reconfigure after instantiation any attribute which you could have set when you instantiated². How you do so is by... |
How to copy a file to a remote server in Python using SCP or SSH? | 68,335 | 55 | 2008-09-16T00:50:10Z | 68,365 | 21 | 2008-09-16T00:55:43Z | [
"python",
"ssh",
"automation",
"scp"
] | I have a text file on my local machine that is generated by a daily Python script run in cron.
I would like to add a bit of code to have that file sent securely to my server over SSH. | If you want the simple approach, this should work.
You'll want to ".close()" the file first so you know it's flushed to disk from Python.
```
import os
os.system("scp FILE USER@SERVER:PATH")
#e.g. os.system("scp foo.bar [email protected]:/path/to/foo.bar")
```
You need to generate (on the source machine) and install (on ... |
How to copy a file to a remote server in Python using SCP or SSH? | 68,335 | 55 | 2008-09-16T00:50:10Z | 68,382 | 23 | 2008-09-16T00:58:49Z | [
"python",
"ssh",
"automation",
"scp"
] | I have a text file on my local machine that is generated by a daily Python script run in cron.
I would like to add a bit of code to have that file sent securely to my server over SSH. | You'd probably use the [subprocess module](http://docs.python.org/lib/module-subprocess.html). Something like this:
```
import subprocess
p = subprocess.Popen(["scp", myfile, destination])
sts = os.waitpid(p.pid, 0)
```
Where `destination` is probably of the form `user@remotehost:remotepath`. Thanks to
@Charles Duffy... |
How to copy a file to a remote server in Python using SCP or SSH? | 68,335 | 55 | 2008-09-16T00:50:10Z | 68,566 | 10 | 2008-09-16T01:32:08Z | [
"python",
"ssh",
"automation",
"scp"
] | I have a text file on my local machine that is generated by a daily Python script run in cron.
I would like to add a bit of code to have that file sent securely to my server over SSH. | There are a couple of different ways to approach the problem:
1. Wrap command-line programs
2. use a Python library that provides SSH capabilities (eg - [Paramiko](http://www.lag.net/paramiko/) or [Twisted Conch](http://twistedmatrix.com/trac/wiki/TwistedConch))
Each approach has its own quirks. You will need to setu... |
How to copy a file to a remote server in Python using SCP or SSH? | 68,335 | 55 | 2008-09-16T00:50:10Z | 69,596 | 76 | 2008-09-16T05:27:59Z | [
"python",
"ssh",
"automation",
"scp"
] | I have a text file on my local machine that is generated by a daily Python script run in cron.
I would like to add a bit of code to have that file sent securely to my server over SSH. | To do this in Python (i.e. not wrapping scp through subprocess.Popen or similar) with the [Paramiko](http://www.lag.net/paramiko/) library, you would do something like this:
```
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.c... |
Send file using POST from a Python script | 68,477 | 70 | 2008-09-16T01:16:24Z | 68,502 | 18 | 2008-09-16T01:21:20Z | [
"python",
"post",
"file-upload",
"http-post"
] | Is there a way to send a file using POST from a Python script? | Yes. You'd use the `urllib2` module, and encode using the `multipart/form-data` content type. Here is some sample code to get you started -- it's a bit more than just file uploading, but you should be able to read through it and see how it works:
```
user_agent = "image uploader"
default_message = "Image $current of $... |
Send file using POST from a Python script | 68,477 | 70 | 2008-09-16T01:16:24Z | 75,186 | 59 | 2008-09-16T18:05:01Z | [
"python",
"post",
"file-upload",
"http-post"
] | Is there a way to send a file using POST from a Python script? | Blatant self-promotion:
check out my [poster](http://atlee.ca/software/poster/) module for python. It handles the multipart/form-data encoding, as well as supporting streaming uploads (so you don't have to load the entire file into memory before submitting the HTTP POST request). |
Send file using POST from a Python script | 68,477 | 70 | 2008-09-16T01:16:24Z | 10,234,640 | 101 | 2012-04-19T18:40:02Z | [
"python",
"post",
"file-upload",
"http-post"
] | Is there a way to send a file using POST from a Python script? | From <http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file>
Requests makes it very simple to upload Multipart-encoded files:
```
>>> r = requests.post('http://httpbin.org/post', files={'report.xls': open('report.xls', 'rb')})
```
That's it. I'm not joking - this is one line of cod... |
Are tuples more efficient than lists in Python? | 68,630 | 101 | 2008-09-16T01:43:39Z | 68,712 | 131 | 2008-09-16T01:57:10Z | [
"python",
"performance",
"python-internals"
] | Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? | In general, you might expect tuples to be slightly faster. However you should definitely test your specific case (if the difference might impact the performance of your program -- remember "premature optimization is the root of all evil").
Python makes this very easy: [timeit](https://docs.python.org/2/library/timeit.... |
Are tuples more efficient than lists in Python? | 68,630 | 101 | 2008-09-16T01:43:39Z | 68,817 | 88 | 2008-09-16T02:13:29Z | [
"python",
"performance",
"python-internals"
] | Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? | The [`dis`](https://docs.python.org/3/library/dis.html) module disassembles the byte code for a function and is useful to see the difference between tuples and lists.
In this case, you can see that accessing an element generates identical code, but that assigning a tuple is much faster than assigning a list.
```
>>> ... |
Are tuples more efficient than lists in Python? | 68,630 | 101 | 2008-09-16T01:43:39Z | 70,968 | 26 | 2008-09-16T10:16:52Z | [
"python",
"performance",
"python-internals"
] | Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? | Tuples, being immutable, are more memory efficient; lists, for efficiency, overallocate memory in order to allow appends without constant `realloc`s. So, if you want to iterate through a constant sequence of values in your code (eg `for direction in 'up', 'right', 'down', 'left':`), tuples are preferred, since such tup... |
Are tuples more efficient than lists in Python? | 68,630 | 101 | 2008-09-16T01:43:39Z | 22,140,115 | 26 | 2014-03-03T06:30:39Z | [
"python",
"performance",
"python-internals"
] | Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? | There are several performance differences between tuples and lists when it comes to instantiation and retrieval of elements:
1. Tuples containing immutable entries can be optimized into constants by Python's peephole optimizer. Lists, on the other hand, get build-up from scratch:
```
>>> from dis import dis
... |
Static class variables in Python | 68,645 | 1,015 | 2008-09-16T01:46:36Z | 68,672 | 1,030 | 2008-09-16T01:51:06Z | [
"python",
"class",
"methods",
"static",
"class-variables"
] | Is it possible to have static class variables or methods in python? What syntax is required to do this? | Variables declared inside the class definition, but not inside a method are class or static variables:
```
>>> class MyClass:
... i = 3
...
>>> MyClass.i
3
```
As @[millerdev](http://stackoverflow.com/questions/68645/static-class-variables-in-python#answer-69067) points out, this creates a class-level "i" variabl... |
Static class variables in Python | 68,645 | 1,015 | 2008-09-16T01:46:36Z | 68,747 | 9 | 2008-09-16T02:02:45Z | [
"python",
"class",
"methods",
"static",
"class-variables"
] | Is it possible to have static class variables or methods in python? What syntax is required to do this? | Personally I would use a classmethod whenever I needed a static method. Mainly because I get the class as an argument.
```
class myObj(object):
def myMethod(cls)
...
myMethod = classmethod(myMethod)
```
or use a decorator
```
class myObj(object):
@classmethod
def myMethod(cls)
```
For static proper... |
Static class variables in Python | 68,645 | 1,015 | 2008-09-16T01:46:36Z | 69,067 | 400 | 2008-09-16T03:04:08Z | [
"python",
"class",
"methods",
"static",
"class-variables"
] | Is it possible to have static class variables or methods in python? What syntax is required to do this? | @Blair Conrad said static variables declared inside the class definition, but not inside a method are class or "static" variables:
```
>>> class Test(object):
... i = 3
...
>>> Test.i
3
```
There are a few gotcha's here. Carrying on from the example above:
```
>>> t = Test()
>>> t.i # static variable accesse... |
Static class variables in Python | 68,645 | 1,015 | 2008-09-16T01:46:36Z | 81,002 | 19 | 2008-09-17T08:06:22Z | [
"python",
"class",
"methods",
"static",
"class-variables"
] | Is it possible to have static class variables or methods in python? What syntax is required to do this? | You can also add class variables to classes on the fly
```
>>> class X:
... pass
...
>>> X.bar = 0
>>> x = X()
>>> x.bar
0
>>> x.foo
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: X instance has no attribute 'foo'
>>> X.foo = 1
>>> x.foo
1
```
And class insta... |
Static class variables in Python | 68,645 | 1,015 | 2008-09-16T01:46:36Z | 27,568,860 | 70 | 2014-12-19T15:16:36Z | [
"python",
"class",
"methods",
"static",
"class-variables"
] | Is it possible to have static class variables or methods in python? What syntax is required to do this? | ## Static and Class Methods
As the other answers have noted, static and class methods are easily accomplished using the built-in decorators:
```
class Test(object):
#regular instance method:
def MyMethod(self):
pass
#class method:
@classmethod
def MyClassMethod(klass):
pass
#st... |
Best way to open a socket in Python | 68,774 | 30 | 2008-09-16T02:06:11Z | 68,796 | 55 | 2008-09-16T02:09:46Z | [
"python",
"networking",
"tcp"
] | I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way? | Opening sockets in python is pretty simple. You really just need something like this:
```
import socket
sock = socket.socket()
sock.connect((address, port))
```
and then you can `send()` and `recv()` like any other socket |
Best way to open a socket in Python | 68,774 | 30 | 2008-09-16T02:06:11Z | 68,892 | 9 | 2008-09-16T02:28:38Z | [
"python",
"networking",
"tcp"
] | I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way? | For developing portable network programs of any sort in Python, [Twisted](http://twistedmatrix.com) is quite useful. One of its benefits is providing a convenient layer above low-level socket APIs. |
Best way to open a socket in Python | 68,774 | 30 | 2008-09-16T02:06:11Z | 68,911 | 13 | 2008-09-16T02:31:24Z | [
"python",
"networking",
"tcp"
] | I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way? | OK, this code worked
```
s = socket.socket()
s.connect((ip,port))
s.send("my request\r")
print s.recv(256)
s.close()
```
It was quite difficult to work that out from the Python socket module documentation. So I'll accept The.Anti.9's answer. |
Take a screenshot via a python script. [Linux] | 69,645 | 54 | 2008-09-16T05:44:54Z | 70,237 | 7 | 2008-09-16T08:01:18Z | [
"python",
"linux",
"screenshot"
] | I want to take a screenshot via a python script and unobtrusively save it.
I'm only interested in the Linux solution, and should support any X based environment. | ```
import ImageGrab
img = ImageGrab.grab()
img.save('test.jpg','JPEG')
```
this requires Python Imaging Library |
Take a screenshot via a python script. [Linux] | 69,645 | 54 | 2008-09-16T05:44:54Z | 769,221 | 17 | 2009-04-20T17:12:10Z | [
"python",
"linux",
"screenshot"
] | I want to take a screenshot via a python script and unobtrusively save it.
I'm only interested in the Linux solution, and should support any X based environment. | This one works on X11, and perhaps on Windows too (someone, please check). Needs [PyQt4](http://www.riverbankcomputing.co.uk/software/pyqt/intro):
```
import sys
from PyQt4.QtGui import QPixmap, QApplication
app = QApplication(sys.argv)
QPixmap.grabWindow(QApplication.desktop().winId()).save('test.png', 'png')
``` |
Take a screenshot via a python script. [Linux] | 69,645 | 54 | 2008-09-16T05:44:54Z | 782,768 | 53 | 2009-04-23T17:27:52Z | [
"python",
"linux",
"screenshot"
] | I want to take a screenshot via a python script and unobtrusively save it.
I'm only interested in the Linux solution, and should support any X based environment. | This works without having to use scrot or ImageMagick.
```
import gtk.gdk
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
if (pb != N... |
Take a screenshot via a python script. [Linux] | 69,645 | 54 | 2008-09-16T05:44:54Z | 6,380,186 | 7 | 2011-06-17T00:33:04Z | [
"python",
"linux",
"screenshot"
] | I want to take a screenshot via a python script and unobtrusively save it.
I'm only interested in the Linux solution, and should support any X based environment. | Cross platform solution using [wxPython](http://wxpython.org):
```
import wx
wx.App() # Need to create an App instance before doing anything
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.EmptyBitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem # Release bi... |
Take a screenshot via a python script. [Linux] | 69,645 | 54 | 2008-09-16T05:44:54Z | 7,711,106 | 35 | 2011-10-10T09:56:22Z | [
"python",
"linux",
"screenshot"
] | I want to take a screenshot via a python script and unobtrusively save it.
I'm only interested in the Linux solution, and should support any X based environment. | Compile all answers in one class.
Outputs PIL image.
```
#!/usr/bin/env python
# encoding: utf-8
"""
screengrab.py
Created by Alex Snet on 2011-10-10.
Copyright (c) 2011 CodeTeam. All rights reserved.
"""
import sys
import os
import Image
class screengrab:
def __init__(self):
try:
import g... |
Take a screenshot via a python script. [Linux] | 69,645 | 54 | 2008-09-16T05:44:54Z | 7,817,506 | 11 | 2011-10-19T06:44:20Z | [
"python",
"linux",
"screenshot"
] | I want to take a screenshot via a python script and unobtrusively save it.
I'm only interested in the Linux solution, and should support any X based environment. | I have a wrapper project ([pyscreenshot](https://github.com/ponty/pyscreenshot)) for scrot, imagemagick, pyqt, wx and pygtk.
If you have one of them, you can use it.
All solutions are included from this discussion.
Install:
```
easy_install pyscreenshot
```
Example:
```
import pyscreenshot as ImageGrab
# fullscree... |
Take a screenshot via a python script. [Linux] | 69,645 | 54 | 2008-09-16T05:44:54Z | 16,141,058 | 13 | 2013-04-22T06:52:08Z | [
"python",
"linux",
"screenshot"
] | I want to take a screenshot via a python script and unobtrusively save it.
I'm only interested in the Linux solution, and should support any X based environment. | Just for completeness:
Xlib - But it's somewhat slow when capturing the whole screen:
```
from Xlib import display, X
import Image #PIL
W,H = 200,200
dsp = display.Display()
root = dsp.screen().root
raw = root.get_image(0, 0, W,H, X.ZPixmap, 0xffffffff)
image = Image.fromstring("RGB", (W, H), raw.data, "raw", "BGRX")... |
Why are Python's 'private' methods not actually private? | 70,528 | 344 | 2008-09-16T08:59:32Z | 70,555 | 116 | 2008-09-16T09:03:45Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] | Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMeth... | From <http://www.faqs.org/docs/diveintopython/fileinfo_private.html>
> Strictly speaking, private methods are
> accessible outside their class, just
> not easily accessible. Nothing in
> Python is truly private; internally,
> the names of private methods and
> attributes are mangled and unmangled
> on the fly to make ... |
Why are Python's 'private' methods not actually private? | 70,528 | 344 | 2008-09-16T08:59:32Z | 70,562 | 24 | 2008-09-16T09:04:57Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] | Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMeth... | It's not like you absolutly can't get around privateness of members in any language (pointer arithmetics in C++, Reflections in .NET/Java).
The point is that you get an error if you try to call the private method by accident. But if you want to shoot yourself in the foot, go ahead and do it.
Edit: You don't try to se... |
Why are Python's 'private' methods not actually private? | 70,528 | 344 | 2008-09-16T08:59:32Z | 70,567 | 9 | 2008-09-16T09:05:52Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] | Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMeth... | The `class.__stuff` naming convention lets the programmer know he isn't meant to access `__stuff` from outside. The name mangling makes it unlikely anyone will do it by accident.
True, you still can work around this, it's even easier than in other languages (which BTW also let you do this), but no Python programmer wo... |
Why are Python's 'private' methods not actually private? | 70,528 | 344 | 2008-09-16T08:59:32Z | 70,583 | 10 | 2008-09-16T09:09:32Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] | Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMeth... | Its just one of those language design choices. On some level they are justified. They make it so you need to go pretty far out of your way to try and call the method, and if you really need it that badly, you must have a pretty good reason! Debugging hooks and testing come to mind as possible applications, used respons... |
Why are Python's 'private' methods not actually private? | 70,528 | 344 | 2008-09-16T08:59:32Z | 70,736 | 66 | 2008-09-16T09:33:18Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] | Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMeth... | The phrase commonly used is "we're all consenting adults here". By prepending a single underscore (don't expose) or double underscore (hide), you're telling the user of your class that you intend the member to be 'private' in some way. However, you're trusting everyone else to behave responsibly and respect that, unles... |
Why are Python's 'private' methods not actually private? | 70,528 | 344 | 2008-09-16T08:59:32Z | 70,900 | 354 | 2008-09-16T10:06:07Z | [
"python",
"python-2.7",
"encapsulation",
"information-hiding"
] | Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMeth... | The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside.
For example:
```
>>> class Foo(object):
... def __init__(self):
... self.__baz = 42
... def foo(self)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.