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 over `if/else` `if/else` in that only a single comparison is needed. The result of that comparison is used as an offset into a jump table (in the underlying `asm` generated).
Mimicking the true functionality in Python would be a pain. Does any one have an implementation that would allow for fall through while only using a single comparison? |
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-based Switch-Case](http://code.activestate.com/recipes/410695/)
3. [Using a Dictionary in place of a 'switch' statement](http://code.activestate.com/recipes/181064/) |
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 dictionary.
So even if your value is 'a', the object will get incremented **and** decremented by x.
Solution:
```
func, args = {
'a' : (obj.increment, (x,)),
'b' : (obj.decrement, (x,)),
}.get(value, (obj.default, (x,)))
result = func(*args)
```
So you get a list containing a function and its arguments. This way, only the function pointer and the argument list get returned, *not* evaluated. 'result' then evaluates the returned function call. |
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 code:
```
macro switch(arg1):
while True:
cont=False
val=%arg1%
socket case(arg2):
if val==%arg2% or cont:
cont=True
socket
socket else:
socket
break
```
that can be used like this:
```
a=3
switch(a):
case(0):
print("Zero")
case(1):
print("Smaller than 2"):
break
else:
print ("greater than 1")
```
so espy translate it in Python as:
```
a=3
while True:
cont=False
if a==0 or cont:
cont=True
print ("Zero")
if a==1 or cont:
cont=True
print ("Smaller than 2")
break
print ("greater than 1")
break
``` |
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):
print "n is a perfect square."
break
if case(2):
print "n is an even number."
if case(2, 3, 5, 7):
print "n is a prime number."
break
if case(6, 8):
print "n is an even number."
break
print "Only single-digit numbers are allowed."
break
```
Tests:
```
n = 2
#Result:
#n is an even number.
#n is a prime number.
n = 11
#Result:
#Only single-digit numbers are allowed.
``` |
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 for its simplicity. Note that you can include statements
# in each suite.
v = 'ten'
for case in switch(v):
if case('one'):
print 1
break
if case('two'):
print 2
break
if case('ten'):
print 10
break
if case('eleven'):
print 11
break
if case(): # default, could also just omit condition or 'if True'
print "something else!"
# No need to break here, it'll stop anyway
# break is used here to look as much like the real thing as possible, but
# elif is generally just as good and more concise.
# Empty suites are considered syntax errors, so intentional fall-throughs
# should contain 'pass'
c = 'z'
for case in switch(c):
if case('a'): pass # only necessary if the rest of the suite is empty
if case('b'): pass
# ...
if case('y'): pass
if case('z'):
print "c is lowercase!"
break
if case('A'): pass
# ...
if case('Z'):
print "c is uppercase!"
break
if case(): # default
print "I dunno what c was!"
# As suggested by Pierre Quentel, you can even expand upon the
# functionality of the classic 'case' statement by matching multiple
# cases in a single shot. This greatly benefits operations such as the
# uppercase/lowercase example above:
import string
c = 'A'
for case in switch(c):
if case(*string.lowercase): # note the * for unpacking as arguments
print "c is lowercase!"
break
if case(*string.uppercase):
print "c is uppercase!"
break
if case('!', '?', '.'): # normal argument passing style also applies
print "c is a sentence terminator!"
break
if case(): # default
print "I dunno what c was!"
``` |
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 your functions as the dictionary / case block is created. Remember this because you only want to call each function once using a hash style lookup.
```
def first_case():
print "first"
def second_case():
print "second"
def third_case():
print "third"
mycase = {
'first': first_case, #do not use ()
'second': second_case, #do not use ()
'third': third_case #do not use ()
}
myfunc = mycase['first']
myfunc()
``` |
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 RANDOM fall-through.
```
l = ['Dog', 'Cat', 'Bird', 'Bigfoot',
'Dragonfly', 'Snake', 'Bat', 'Loch Ness Monster']
for x in l:
if x in ('Dog', 'Cat'):
x += " has four legs"
elif x in ('Bat', 'Bird', 'Dragonfly'):
x += " has wings."
elif x in ('Snake',):
x += " has a forked tongue."
else:
x += " is a big mystery by default."
print(x)
print()
for x in range(10):
if x in (0, 1):
x = "Values 0 and 1 caught here."
elif x in (2,):
x = "Value 2 caught here."
elif x in (3, 7, 8):
x = "Values 3, 7, 8 caught here."
elif x in (4, 6):
x = "Values 4 and 6 caught here"
else:
x = "Values 5 and 9 caught in default."
print(x)
```
Provides:
```
Dog has four legs
Cat has four legs
Bird has wings.
Bigfoot is a big mystery by default.
Dragonfly has wings.
Snake has a forked tongue.
Bat has wings.
Loch Ness Monster is a big mystery by default.
Values 0 and 1 caught here.
Values 0 and 1 caught here.
Value 2 caught here.
Values 3, 7, 8 caught here.
Values 4 and 6 caught here
Values 5 and 9 caught in default.
Values 4 and 6 caught here
Values 3, 7, 8 caught here.
Values 3, 7, 8 caught here.
Values 5 and 9 caught in default.
``` |
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
v3)
```
Instead of being a statement, the python version is an expression, which evaluates to a value. |
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.today().weekday()) as case:
if case(0):
# Basic usage of switch
print("I hate mondays so much.")
# Note there is no break needed here
elif case(1,2):
# This switch also supports multiple conditions (in one line)
print("When is the weekend going to be here?")
elif case(3,4): print("The weekend is near.")
else:
# Default would occur here
print("Let's go have fun!") # Didn't use case for example purposes
``` |
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;
case 'b' :
result = 2;
break;
default :
result = -1;
}
```
You can even assign multiple variables by using tuples:
```
choices = {'a': (1, 2, 3), 'b': (4, 5, 6)}
(result1, result2, result3) = choices.get(key, ('default1', 'default2', 'default3'))
``` |
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/)
 |
Windows Mobile development in Python | 60,446 | 3 | 2008-09-13T09:56:04Z | 60,945 | 9 | 2008-09-13T22:30:01Z | [
"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? | (I used to write customer apps for Windows Mobile.)
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 documentation or discussion groups to help you when you (inevitably) encounter problems
Go with C/C++ (or C#). Visual Studio 2005/2008 have decent tools for those (SDK for winmo built-in, debugging on the emulator or device connected through USB), the best documentation is for those technologies plus there are active forums/discussion groups/mailing lists where you can ask for help. |
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 programming under Linux, but I'd like what I write to be portable to other OSes in the future. I've thought about using sockets, named pipes, or something like DBus.
Does anyone have any advice? | 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 sockets or even a higher level abstraction like HTTP. |
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 programming under Linux, but I'd like what I write to be portable to other OSes in the future. I've thought about using sockets, named pipes, or something like DBus.
Does anyone have any advice? | 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 pipes behave pretty much the same behavior. While the APIs for setting them up and connecting them are different, they both just act like streams of data.
The difficult part, however, is not the communication channel, but the messages you pass over it. You really want to look at something that will perform verification and parsing for you. I recommend looking at Google's [Protocol Buffers](http://code.google.com/apis/protocolbuffers/docs/overview.html). You basically create a spec file that describes the object you want to pass between processes, and there is a compiler that generates code in a number of different languages for reading and writing objects that match the spec. It's much easier (and less bug prone) than trying to come up with a messaging protocol and parser yourself. |
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 programming under Linux, but I'd like what I write to be portable to other OSes in the future. I've thought about using sockets, named pipes, or something like DBus.
Does anyone have any advice? | 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 programming under Linux, but I'd like what I write to be portable to other OSes in the future. I've thought about using sockets, named pipes, or something like DBus.
Does anyone have any advice? | 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(ThreadingMixIn, HTTPServer):
pass
server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler)
server.serve_forever()
``` | 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/>
```
from threading import Thread
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write("Hello World!")
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
pass
def serve_on_port(port):
server = ThreadingHTTPServer(("localhost",port), Handler)
server.serve_forever()
Thread(target=serve_on_port, args=[1111]).start()
serve_on_port(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
select.order_by('dbms_random.value') # For Oracle
```
Next, you need to limit the query by the number of records you need (for example using `.limit()`).
Bear in mind that at least in PostgreSQL, selecting random record has severe perfomance issues; [here](http://www.depesz.com/index.php/2007/09/16/my-thoughts-on-getting-random-row/) is good article about it. |
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 you use an orm. |
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 query there).
If you want a few rows, then you can just run this multiple times, and make sure that each row is not identical to the previous. |
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/trunk/babel/util.py?rev=374#L178) [implementations](http://www.xs4all.nl/~anthon/Python/ordereddict/) [of](http://code.djangoproject.com/browser/django/trunk/django/utils/datastructures.py?rev=7140#L53) [ordered](http://pypi.python.org/pypi/StableDict/0.2) [dictionaries](http://codespeak.net/svn/user/arigo/hack/pyfuse/OrderedDict.py) (see also these [two](http://code.activestate.com/recipes/107747/) [recipes](http://code.activestate.com/recipes/496761/) in the Python Cookbook).
You might want to stick with the reference implementation in the PEP if you want your code to be compatible with the "official" version (if the proposal is eventually accepted).
EDIT: The PEP was accepted and added in python 2.7 and 3.1. See [the docs](http://docs.python.org/library/collections.html#ordereddict-objects). |
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 constructor is undefined but will come before values passed later, and you could always just not allow ordered dicts to be initialized with values.)
```
class ordered_dict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self._order = self.keys()
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
if key in self._order:
self._order.remove(key)
self._order.append(key)
def __delitem__(self, key):
dict.__delitem__(self, key)
self._order.remove(key)
def order(self):
return self._order[:]
def ordered_items(self):
return [(key,self[key]) for key in self._order]
od = ordered_dict()
od["hello"] = "world"
od["goodbye"] = "cruel world"
print od.order() # prints ['hello', 'goodbye']
del od["hello"]
od["monty"] = "python"
print od.order() # prints ['goodbye', 'monty']
od["hello"] = "kitty"
print od.order() # prints ['goodbye', 'monty', 'hello']
print od.ordered_items()
# prints [('goodbye','cruel world'), ('monty','python'), ('hello','kitty')]
``` |
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 practice here? | 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 never have to remove the tests directory from the main code when I release it, saving me time and effort, if an ever so tiny amount. |
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 practice here? | 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 module using [absolute import](http://www.python.org/dev/peps/pep-0328/).
Wherever you put your tests, I would recommend you use [nose](http://nose.readthedocs.org/en/latest/) to run them. [Nose](http://nose.readthedocs.org/en/latest/) searches through your directories for tests. This way, you can put tests wherever they make the most sense organizationally. |
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 practice here? | 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 practice here? | 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/test_module.py` (one level under the code directory).
I prefer #1 for its simplicity of finding the tests and importing them. Whatever build system you're using can easily be configured to run files starting with `test_`. Actually, the [default `unittest` pattern used for test discovery is `test*.py`](https://docs.python.org/library/unittest.html#test-discovery). |
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 practice here? | 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 the python file you are testing.
I should add, I tend to write very tight modules/classes. If your modules require very large numbers of tests, you can put them in another, but even then, I'd still add:
```
if __name__ == '__main__':
import tests.thisModule
tests.thisModule.runtests
```
This lets anybody reading your source code know where to look for the test code. |
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 practice here? | 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 source code. In that directory we generate a test file for each module in the parent directory. |
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 practice here? | ## 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/
test_module.py
test_module2.py
```
but if put the tests in `tests` folder, test can't `import ..lib` in CLI because `__main__` can't import relative module, we can use [`nose`](https://nose.readthedocs.org/en/latest/), or we can add parent directory to python import path, for that I will create a
### env.py
```
import sys
import os
# append module root directory to sys.path
sys.path.append(
os.path.dirname(
os.path.dirname(
os.path.abspath(__file__)
)
)
)
```
in
```
module/
tests/
test_module.py
env.py
```
and `import env` before test import module
### test\_module.py
```
import unittest
# append parent directory to import path
import env
# now we can import the lib module
from lib import module
if __name__ == '__main__':
unittest.main()
``` |
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.
Thanks | 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(f) if not name.startswith('__')]
[ 'bar', 'baz' ]
>>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__'))
{ 'bar': 'hello', 'baz': 'world' }
```
So can extend this to only return data attributes and not methods, by defining your `props` function like this:
```
import inspect
def props(obj):
pr = {}
for name in dir(obj):
value = getattr(obj, name)
if not name.startswith('__') and not inspect.ismethod(value):
pr[name] = value
return pr
``` |
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.
Thanks | 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.
Thanks | 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 level and your attributes at instance level, so `__dict__` should be fine. For example:
```
>>> class A(object):
... def __init__(self):
... self.b = 1
... self.c = 2
... def do_nothing(self):
... pass
...
>>> a = A()
>>> a.__dict__
{'c': 2, 'b': 1}
```
Alternatively, depending on what you want to do, it might be nice to inherit from dict. Then your class is *already* a dictionary, and if you want you can override getattr and/or setattr to call through and set the dict. For example:
```
class Foo(dict):
def __init__(self):
pass
def __getattr__(self, attr):
return self[attr]
# etc...
``` |
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.
Thanks | > 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.
Thanks | 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 need as an intermediate value. Let's have X return that value also").
When should you draw the line and define a different method? | 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 in a single value. However, when using Python for real-world applications, you quickly run into many cases where returning multiple values is necessary, and results in cleaner code.
So, I'd say do whatever makes sense, and don't try to conform to an artificial convention. Python supports multiple return values, so use it when appropriate. |
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 need as an intermediate value. Let's have X return that value also").
When should you draw the line and define a different method? | 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`, `enumerate`, `dict.items`.
```
for i, e in enumerate([1, 3, 3]):
print "index=%d, element=%s" % (i, e)
# reverse keys and values in a dictionary
d = dict((v, k) for k, v in adict.items()) # or
d = dict(zip(adict.values(), adict.keys()))
```
BTW, parentheses are not necessary most of the time.
Citation from [Python Library Reference](http://docs.python.org/lib/typesseq.html):
> *Tuples are constructed by the comma
> operator* (not within square brackets),
> with or without enclosing parentheses,
> but an empty tuple must have the
> enclosing parentheses, such as a, b, c
> or (). A single item tuple must have a
> trailing comma, such as (d,).
### Functions should serve single purpose
Therefore they should return a single object. In your case this object is a tuple. Consider tuple as an ad-hoc compound data structure. There are languages where almost every single function returns multiple values (list in Lisp).
Sometimes it is sufficient to return `(x, y)` instead of `Point(x, y)`.
### Named tuples
With the introduction of named tuples in Python 2.6 it is preferable in many cases to return named tuples instead of plain tuples.
```
>>> import collections
>>> Point = collections.namedtuple('Point', 'x y')
>>> x, y = Point(0, 1)
>>> p = Point(x, y)
>>> x, y, p
(0, 1, Point(x=0, y=1))
>>> p.x, p.y, p[0], p[1]
(0, 1, 0, 1)
>>> for i in p:
... print(i)
...
0
1
``` |
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 need as an intermediate value. Let's have X return that value also").
When should you draw the line and define a different method? | 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(seconds, 60)
hours, minutes = divmod(minutes, 60)
seconds = 1234
minutes = seconds / 60
seconds = seconds % 60
hours = minutes / 60
minutes = minutes % 60
``` |
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 together with the "main project" or other apps? | 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 together with the "main project" or other apps? | 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 bucket up specific features or feature sets into "apps" as though I were going to release them publicly. The hard part here is figuring out how big each bucket is.
A good trick I use is to imagine how my apps would be used if they were released publicly. This often encourages me to shrink the buckets and more clearly define its "purpose". |
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 together with the "main project" or other apps? | 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 together with the "main project" or other apps? | 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 whatever else Iâm doing?
> * Will I need similar functionality on other sites?
>
> If any of them is "Yes"? Then best to break it into a
> separate application. |
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 information needs to be encoded in the request? Would a URL like "http://yourserver.example.com/service/request?color=yellow&flavor=banana" be good enough?
There are lots of HTTP clients and servers in Python, none of which are especially great, but all of which I'm sure will get the job done for basic file transfers. You can do security the "normal" web way, which is to use HTTPS and passwords, which will probably be sufficient.
If you want two-way communication then HTTP falls down, and a protocol like Twisted's [perspective broker (PB)](http://twistedmatrix.com/projects/core/documentation/howto/pb-intro.html) or [asynchronous messaging protocol (AMP)](http://twistedmatrix.com/documents/8.1.0/api/twisted.protocols.amp.html) might suit you better. These protocols are certainly well-supported by Twisted. |
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-RPC on several projects, and it always did exactly what I was hoping for. I was usually going between C++, Java and Python. I use libxmlrpc in Python often because it's easy to memorize and type interactively, but it is actually much slower than the alternative [pyxmlrpc](http://sourceforge.net/projects/py-xmlrpc/).
PyAMF is mostly for RPC with Flash clients, but it's a compact RPC format worth looking at too.
When you have Python on both ends, I don't believe anything beats [Pyro](http://pyro.sourceforge.net/) (Python Remote Objects.) Pyro even has a "name server" that lets services announce their availability to a network. Clients use the name server to find the services it needs no matter where they're active at a particular moment. This gives you free redundancy, and the ability to move services from one machine to another without any downtime.
For security, I'd tunnel over SSH, or use TLS or SSL at the connection level. Of course, all these options are essentially the same, they just have various difficulties of setup. |
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')
from_addr = "John Doe <[email protected]>"
to_addr = "[email protected]"
subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = "Hello\nThis is a mail from your server\n\nBye\n"
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
% ( from_addr, to_addr, subj, date, message_text )
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()
``` | 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 ssmtplib module (downloadable at <http://www1.cs.columbia.edu/~db2501/ssmtplib.py>)
As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.
=======================================
```
#! /usr/local/bin/python
SMTPserver = 'smtp.att.yahoo.com'
sender = 'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']
USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""\
Test message
"""
subject="Sent from Python"
import sys
import os
import re
from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.quit()
except Exception, exc:
sys.exit( "mail failed; %s" % str(exc) ) # give a error message
``` |
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')
from_addr = "John Doe <[email protected]>"
to_addr = "[email protected]"
subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = "Hello\nThis is a mail from your server\n\nBye\n"
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
% ( from_addr, to_addr, subj, date, message_text )
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()
``` | 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')
from_addr = "John Doe <[email protected]>"
to_addr = "[email protected]"
subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = "Hello\nThis is a mail from your server\n\nBye\n"
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
% ( from_addr, to_addr, subj, date, message_text )
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()
``` | 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'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.gmail.com',587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('[email protected]', 'mypassword')
mailserver.sendmail('[email protected]','[email protected]',msg.as_string())
mailserver.quit()
```
That's it |
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
" --------------------------------------------------------------------------------
" configure editor with tabs and nice stuff...
" --------------------------------------------------------------------------------
set expandtab " enter spaces when tab is pressed
set textwidth=120 " break lines when line length increases
set tabstop=4 " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4 " number of spaces to use for auto indent
set autoindent " copy indent from current line when starting a new line
" make backspaces more powerfull
set backspace=indent,eol,start
set ruler " show line and column number
syntax on " syntax highlighting
set showcmd " show (partial) command in status line
```
(edited to only show stuff related to indent / tabs) |
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 cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?
Pickling the object simply does the following, causing compilation to happen anyway:
```
>>> import pickle
>>> import re
>>> x = re.compile(".*")
>>> pickle.dumps(x)
"cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n."
```
And re objects are unmarshallable:
```
>>> import marshal
>>> import re
>>> x = re.compile(".*")
>>> marshal.dumps(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: unmarshallable object
``` | > 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 vastly outweighed by the time and effort required.
First, have you actually profiled the code? I doubt that compiling regexes is a significant part of the application's run-time. Remember that they are only compiled the first time the module is imported in the current execution -- thereafter, the module and its attributes are cached in memory.
If you have a program that basically spawns once, compiles a bunch of regexes, and then exits, you could try re-engineering it to perform multiple tests in one invocation. Then you could re-use the regexes, as above.
Finally, you could compile the regexes into C-based state machines and then link them in with an extension module. While this would likely be more difficult to maintain, it would eliminate regex compilation entirely from your application. |
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, bases, dict)
class Foo(object):
__metaclass__ = MetaFoo
>>> f = Foo()
>>> f.foobar()
bar
>>> f.foobar.func_name
'bar'
```
My problem is that some library code actually uses the func\_name and later fails to find the 'bar' method of the Foo instance. I could do:
```
dict["foobar"] = types.FunctionType(bar.func_code, {}, "foobar")
```
There is also types.MethodType, but I need an instance that does'nt exist yet to use that. Am I missing someting here? | 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):
__metaclass__ = MetaFoo
if __name__ == "__main__":
f = Foo()
f.bar()
print f.bar.func_name
``` |
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 currently have a good solution for serving dynamically generated files. | 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 application return the content of StringIO object in `HttpResponse` with mimetype set to `application/x-zip-compressed` (or at least `application/octet-stream`). If you want, you can set `content-disposition` header, but this should not be really required.
But beware, creating zip archives on each request is bad idea and this may kill your server (not counting timeouts if the archives are large). Performance-wise approach is to cache generated output somewhere in filesystem and regenerate it only if source files have changed. Even better idea is to prepare archives in advance (eg. by cron job) and have your web server serving them as usual statics. |
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 currently have a good solution for serving dynamically generated files. | 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 archive which contains the above files
# E.g [thearchive.zip]/somefiles/file2.txt
# FIXME: Set this to something better
zip_subdir = "somefiles"
zip_filename = "%s.zip" % zip_subdir
# Open StringIO to grab in-memory ZIP contents
s = StringIO.StringIO()
# The zip compressor
zf = zipfile.ZipFile(s, "w")
for fpath in filenames:
# Calculate path for file in zip
fdir, fname = os.path.split(fpath)
zip_path = os.path.join(zip_subdir, fname)
# Add file, at correct path
zf.write(fpath, zip_path)
# Must close zip for all contents to be written
zf.close()
# Grab ZIP file from in-memory, make response with correct MIME-type
resp = HttpResponse(s.getvalue(), mimetype = "application/x-zip-compressed")
# ..and correct content-disposition
resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
return resp
``` |
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 = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()
```
(Although this has been deprecated in Python 3.4.)
Python 2 use:
```
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
```
There are equivalent convenience functions for compiled Python files and DLLs.
See also. <http://bugs.python.org/issue21436>. |
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.append(os.path.dirname(os.path.expanduser(configfile)))
import config
``` |
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)
module_obj.__file__ = full_path_to_module
globals()[module_name] = module_obj
os.chdir(save_cwd)
except:
raise ImportError
import_file('/home/somebody/somemodule.py')
``` |
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 testutils import RunTests
from mock import Mock, sentinel, patch
``` |
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 declaring it as an argument in the method prototype.
Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument? | 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!"
...
>>>
>>> c = C()
>>> C.bar = bar
>>> c.bar()
Bork bork bork!
>>> c.foo()
Hi!
>>>
```
It also (as far as I know) makes the implementation of the python runtime easier. |
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 declaring it as an argument in the method prototype.
Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument? | 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.
Additionally, since nothing is implied or assumed, parts of the implementation are exposed. `self.__class__`, `self.__dict__` and other "internal" structures are available in an obvious way. |
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 declaring it as an argument in the method prototype.
Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument? | 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 declaring it as an argument in the method prototype.
Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument? | 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' parameter or not: the decorator could turn the function into a static method (which has no 'self'), or a class method (which has a funny kind of self that refers to a class instead of an instance), or it could do something completely different (it's trivial to write a decorator that implements '@classmethod' or '@staticmethod' in pure Python). There's no way without knowing what the decorator does whether to endow the method being defined with an implicit 'self' argument or not.
>
> I reject hacks like special-casing '@classmethod' and '@staticmethod'. |
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 way of the configure() method.
```
from Tkinter import Tk, Button
def goodbye_world():
print "Goodbye World!\nWait, I changed my mind!"
button.configure(text = "Hello World!", command=hello_world)
def hello_world():
print "Hello World!\nWait, I changed my mind!"
button.configure(text = "Goodbye World!", command=goodbye_world)
root = Tk()
button = Button(root, text="Hello World!", command=hello_world)
button.pack()
root.mainloop()
```
¹ "fine" if you use only the mouse; if you care about tabbing and using [Space] or [Enter] on buttons, then you will have to implement (duplicating existing code) keypress events too. Setting the `command` option through `.configure` is much easier.
² the only attribute that can't change after instantiation is `name`. |
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 the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password).
[ssh-keygen example](http://www.modwest.com/help/kb20-90.html) |
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 for pointing out the weakness in my original answer, which used a single string argument to specify the scp operation `shell=True` - that wouldn't handle whitespace in paths.
The module documentation has [examples of error checking that you may want to perform in conjunction with this operation.](http://docs.python.org/lib/node536.html)
Ensure that you've set up proper credentials so that you can perform an [unattended, passwordless scp between the machines](http://www.debian.org/devel/passwordlessssh). There is a [stackoverflow question for this already](http://stackoverflow.com/questions/7260/how-do-i-setup-public-key-authentication). |
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 setup SSH keys to enable password-less logins if you are wrapping system commands like "ssh", "scp" or "rsync." You can embed a password in a script using Paramiko or some other library, but you might find the lack of documentation frustrating, especially if you are not familiar with the basics of the SSH connection (eg - key exchanges, agents, etc). It probably goes without saying that SSH keys are almost always a better idea than passwords for this sort of stuff.
NOTE: its hard to beat rsync if you plan on transferring files via SSH, especially if the alternative is plain old scp.
I've used Paramiko with an eye towards replacing system calls but found myself drawn back to the wrapped commands due to their ease of use and immediate familiarity. You might be different. I gave Conch the once-over some time ago but it didn't appeal to me.
If opting for the system-call path, Python offers an array of options such as os.system or the commands/subprocess modules. I'd go with the subprocess module if using version 2.4+. |
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.connect(server, username=username, password=password)
sftp = ssh.open_sftp()
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()
```
(You would probably want to deal with unknown hosts, errors, creating any directories necessary, and so on). |
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 $total"
import logging
import os
from os.path import abspath, isabs, isdir, isfile, join
import random
import string
import sys
import mimetypes
import urllib2
import httplib
import time
import re
def random_string (length):
return ''.join (random.choice (string.letters) for ii in range (length + 1))
def encode_multipart_data (data, files):
boundary = random_string (30)
def get_content_type (filename):
return mimetypes.guess_type (filename)[0] or 'application/octet-stream'
def encode_field (field_name):
return ('--' + boundary,
'Content-Disposition: form-data; name="%s"' % field_name,
'', str (data [field_name]))
def encode_file (field_name):
filename = files [field_name]
return ('--' + boundary,
'Content-Disposition: form-data; name="%s"; filename="%s"' % (field_name, filename),
'Content-Type: %s' % get_content_type(filename),
'', open (filename, 'rb').read ())
lines = []
for name in data:
lines.extend (encode_field (name))
for name in files:
lines.extend (encode_file (name))
lines.extend (('--%s--' % boundary, ''))
body = '\r\n'.join (lines)
headers = {'content-type': 'multipart/form-data; boundary=' + boundary,
'content-length': str (len (body))}
return body, headers
def send_post (url, data, files):
req = urllib2.Request (url)
connection = httplib.HTTPConnection (req.get_host ())
connection.request ('POST', req.get_selector (),
*encode_multipart_data (data, files))
response = connection.getresponse ()
logging.debug ('response = %s', response.read ())
logging.debug ('Code: %s %s', response.status, response.reason)
def make_upload_file (server, thread, delay = 15, message = None,
username = None, email = None, password = None):
delay = max (int (delay or '0'), 15)
def upload_file (path, current, total):
assert isabs (path)
assert isfile (path)
logging.debug ('Uploading %r to %r', path, server)
message_template = string.Template (message or default_message)
data = {'MAX_FILE_SIZE': '3145728',
'sub': '',
'mode': 'regist',
'com': message_template.safe_substitute (current = current, total = total),
'resto': thread,
'name': username or '',
'email': email or '',
'pwd': password or random_string (20),}
files = {'upfile': path}
send_post (server, data, files)
logging.info ('Uploaded %r', path)
rand_delay = random.randint (delay, delay + 5)
logging.debug ('Sleeping for %.2f seconds------------------------------\n\n', rand_delay)
time.sleep (rand_delay)
return upload_file
def upload_directory (path, upload_file):
assert isabs (path)
assert isdir (path)
matching_filenames = []
file_matcher = re.compile (r'\.(?:jpe?g|gif|png)$', re.IGNORECASE)
for dirpath, dirnames, filenames in os.walk (path):
for name in filenames:
file_path = join (dirpath, name)
logging.debug ('Testing file_path %r', file_path)
if file_matcher.search (file_path):
matching_filenames.append (file_path)
else:
logging.info ('Ignoring non-image file %r', path)
total_count = len (matching_filenames)
for index, file_path in enumerate (matching_filenames):
upload_file (file_path, index + 1, total_count)
def run_upload (options, paths):
upload_file = make_upload_file (**options)
for arg in paths:
path = abspath (arg)
if isdir (path):
upload_directory (path, upload_file)
elif isfile (path):
upload_file (path)
else:
logging.error ('No such path: %r' % path)
logging.info ('Done!')
``` |
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 code. File was sent. Let's check:
```
>>> r.text
{
"origin": "179.13.100.4",
"files": {
"report.xls": "<censored...binary...data>"
},
"form": {},
"url": "http://httpbin.org/post",
"args": {},
"headers": {
"Content-Length": "3196",
"Accept-Encoding": "identity, deflate, compress, gzip",
"Accept": "*/*",
"User-Agent": "python-requests/0.8.0",
"Host": "httpbin.org:80",
"Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"
},
"data": ""
}
``` |
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.html) is your friend.
```
$ python -m timeit "x=(1,2,3,4,5,6,7,8)"
10000000 loops, best of 3: 0.0388 usec per loop
$ python -m timeit "x=[1,2,3,4,5,6,7,8]"
1000000 loops, best of 3: 0.363 usec per loop
```
and...
```
$ python -m timeit -s "x=(1,2,3,4,5,6,7,8)" "y=x[3]"
10000000 loops, best of 3: 0.0938 usec per loop
$ python -m timeit -s "x=[1,2,3,4,5,6,7,8]" "y=x[3]"
10000000 loops, best of 3: 0.0649 usec per loop
```
So in this case, instantiation is almost an order of magnitude faster for the tuple, but item access is actually somewhat faster for the list! So if you're creating a few tuples and accessing them many many times, it may actually be faster to use lists instead.
Of course if you want to *change* an item, the list will definitely be faster since you'd need to create an entire new tuple to change one item of it (since tuples are immutable). |
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.
```
>>> def a():
... x=[1,2,3,4,5]
... y=x[2]
...
>>> def b():
... x=(1,2,3,4,5)
... y=x[2]
...
>>> import dis
>>> dis.dis(a)
2 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 LOAD_CONST 3 (3)
9 LOAD_CONST 4 (4)
12 LOAD_CONST 5 (5)
15 BUILD_LIST 5
18 STORE_FAST 0 (x)
3 21 LOAD_FAST 0 (x)
24 LOAD_CONST 2 (2)
27 BINARY_SUBSCR
28 STORE_FAST 1 (y)
31 LOAD_CONST 0 (None)
34 RETURN_VALUE
>>> dis.dis(b)
2 0 LOAD_CONST 6 ((1, 2, 3, 4, 5))
3 STORE_FAST 0 (x)
3 6 LOAD_FAST 0 (x)
9 LOAD_CONST 2 (2)
12 BINARY_SUBSCR
13 STORE_FAST 1 (y)
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
``` |
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 tuples are pre-calculated in compile time.
Access speeds should be the same (they are both stored as contiguous arrays in the memory).
But, `alist.append(item)` is much preferred to `atuple+= (item,)` when you deal with mutable data. Remember, tuples are intended to be treated as records without field names. |
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
>>> dis(compile("(10, 'abc')", '', 'eval'))
1 0 LOAD_CONST 2 ((10, 'abc'))
3 RETURN_VALUE
>>> dis(compile("[10, 'abc']", '', 'eval'))
1 0 LOAD_CONST 0 (10)
3 LOAD_CONST 1 ('abc')
6 BUILD_LIST 2
9 RETURN_VALUE
```
2. Internally, tuples are stored a little more efficiently than lists, and also tuples can be accessed slightly faster.
Here is how the tuple `(10, 20)` is stored:
```
typedef struct {
Py_ssize_t ob_refcnt;
struct _typeobject *ob_type;
Py_ssize_t ob_size;
PyObject *ob_item[2]; /* store a pointer to 10 and a pointer to 20 */
} PyTupleObject;
```
Here is how the list `[10, 20]` is stored:
```
PyObject arr[2]; /* store a pointer to 10 and a pointer to 20 */
typedef struct {
Py_ssize_t ob_refcnt;
struct _typeobject *ob_type;
Py_ssize_t ob_size;
PyObject **ob_item = arr; /* store a pointer to the two-pointer array */
Py_ssize_t allocated;
} PyListObject;
```
Note that the tuple object incorporates the two data pointers directly while the list object has an additional layer of indirection to an external array holding the two data pointers. |
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" variable, but this is distinct from any instance-level "i" variable, so you could have
```
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
```
This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.
See [what the Python tutorial has to say on the subject of classes and class objects](https://docs.python.org/2/tutorial/classes.html#class-objects).
@Steve Johnson has already answered regarding [static methods](http://web.archive.org/web/20090214211613/http://pyref.infogami.com/staticmethod), also documented under ["Built-in Functions" in the Python Library Reference](https://docs.python.org/2/library/functions.html#staticmethod).
```
class C:
@staticmethod
def f(arg1, arg2, ...): ...
```
@beidy recommends [classmethod](https://docs.python.org/2/library/functions.html#classmethod)s over staticmethod, as the method then receives the class type as the first argument, but I'm still a little fuzzy on the advantages of this approach over staticmethod. If you are too, then it probably doesn't matter. |
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 properties.. Its time you look up some python definition.. variable can always change. There are two types of them mutable and immutable.. Also, there are class attributes and instance attributes.. Nothing really like static attributes in the sense of java & c++
Why use static method in pythonic sense, if it has no relation whatever to the class! If I were you, I'd either use classmethod or define the method independent from the class. |
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 accessed via instance
3
>>> t.i = 5 # but if we assign to the instance ...
>>> Test.i # we have not changed the static variable
3
>>> t.i # we have overwritten Test.i on t by creating a new attribute t.i
5
>>> Test.i = 6 # to change the static variable we do it by assigning to the class
>>> t.i
5
>>> Test.i
6
>>> u = Test()
>>> u.i
6 # changes to t do not affect new instances of Test
# Namespaces are one honking great idea -- let's do more of those!
>>> Test.__dict__
{'i': 6, ...}
>>> t.__dict__
{'i': 5}
>>> u.__dict__
{}
```
Notice how the instance variable `t.i` got out of sync with the "static" class variable when the attribute `i` was set directly on `t`. This is because `i` was re-bound within the `t` namespace, which is distinct from the `Test` namespace. If you want to change the value of a "static" variable, you must change it within the scope (or object) where it was originally defined. I put "static" in quotes because Python does not really have static variables in the sense that C++ and Java do.
Although it doesn't say anything specific about static variables or methods, the [Python tutorial](http://docs.python.org/tut/) has some relevant information on [classes and class objects](https://docs.python.org/2/tutorial/classes.html).
@Steve Johnson also answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.
```
class Test(object):
@staticmethod
def f(arg1, arg2, ...):
...
```
@beid also mentioned classmethod, which is similar to staticmethod. A classmethod's first argument is the class object. Example:
```
class Test(object):
i = 3 # class (or static) variable
@classmethod
def g(cls, arg):
# here we can use 'cls' instead of the class name (Test)
if arg > cls.i:
cls.i = arg # would the the same as Test.i = arg1
``` |
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 instances can change class variables
```
class X:
l = []
def __init__(self):
self.l.append(1)
print X().l
print X().l
>python test.py
[1]
[1, 1]
``` |
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
#static method:
@staticmethod:
def MyStaticMethod():
pass
```
As usual, the first argument to `MyMethod()` is bound to the class instance object. In contrast, the first argument to `MyClassMethod()` is *bound to the class object itself* (e.g., in this case, `Test`). For `MyStaticMethod()`, none of the arguments are bound, and having arguments at all is optional.
## "Static Variables"
However, implementing "static variables" (well, *mutable* static variables, anyway, if that's not a contradiction in terms...) is not as straight forward. As millerdev [pointed out in his answer](http://stackoverflow.com/a/69067/2437514), the problem is that Python's class attributes are not truly "static variables". Consider:
```
class Test(object):
i = 3 #This is a class attribute
x = Test()
x.i = 12 #Attempt to change the value of the class attribute using x instance
assert x.i == Test.i #ERROR
assert Test.i == 3 #Test.i was not affected
assert x.i == 12 #x.i is a different object than Test.i
```
This is because the line `x.i = 12` has added a new instance attribute `i` to `x` instead of changing the value of the `Test` class `i` attribute.
*Partial* expected static variable behavior, i.e., syncing of the attribute between multiple instances (but **not** with the class itself; see "gotcha" below), can be achieved by turning the class attribute into a property:
```
class Test(object):
_i = 3
@property
def i(self):
return self._i
@i.setter
def i(self,val):
self._i = val
## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##
## (except with separate methods for getting and setting i) ##
class Test(object):
_i = 3
def get_i(self):
return self._i
def set_i(self,val):
self._i = val
i = property(get_i, set_i)
```
Now you can do:
```
x1 = Test()
x2 = Test()
x1.i = 50
assert x2.i == x1.i # no error
assert x2.i == 50 # the property is synced
```
The static variable will now remain in sync *between all class instances*.
(NOTE: That is, unless a class instance decides to define its own version of `_i`! But if someone decides to do THAT, they deserve what they get, don't they???)
Note that technically speaking, `i` is still not a 'static variable' at all; it is a `property`, which is a special type of descriptor. However, the `property` behavior is now equivalent to a (mutable) static variable synced across all class instances.
## Immutable "Static Variables"
For immutable static variable behavior, simply omit the `property` setter:
```
class Test(object):
_i = 3
@property
def i(self):
return type(self)._i
## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##
## (except with separate methods for getting i) ##
class Test(object):
_i = 3
def get_i(self):
return type(self)._i
i = property(get_i)
```
Now attempting to set the instance `i` attribute will return an `AttributeError`:
```
x = Test()
assert x.i == 3 #success
x.i = 12 #ERROR
```
## One Gotcha to be Aware of
Note that the above methods only work with *instances* of your class - they will **not** work *when using the class itself*. So for example:
```
x = Test()
assert x.i == Test.i # ERROR
# x.i and Test.i are two different objects:
type(Test.i) # class 'property'
type(x.i) # class 'int'
```
The line `assert Test.i == x.i` produces an error, because the `i` attribute of `Test` and `x` are two different objects.
Many people will find this surprising. However, it should not be. If we go back and inspect our `Test` class definition (the second version), we take note of this line:
```
i = property(get_i)
```
Clearly, the member `i` of `Test` must be a `property` object, which is the type of object returned from the `property` function.
If you find the above confusing, you are most likely still thinking about it from the perspective of other languages (e.g. Java or c++). You should go study the `property` object, about the order in which Python attributes are returned, the descriptor protocol, and the method resolution order (MRO).
I present a solution to the above 'gotcha' below; however I would suggest - strenuously - that you do not try to do something like the following until - at minimum - you thoroughly understand why `assert Test.i = x.i` causes an error.
## *REAL, ACTUAL* Static Variables - `Test.i == x.i`
I present the (Python 3) solution below for informational purposes only. I am not endorsing it as a "good solution". I have my doubts as to whether emulating the static variable behavior of other languages in Python is ever actually necessary. However, regardless as to whether it is actually useful, the below should help further understanding of how Python works.
**Emulating static variable behavior of other languages using a metaclass**
A metaclass is the class of a class. The default metaclass for all classes in Python (i.e., the "new style" classes post Python 2.3 I believe) is `type`. For example:
```
type(int) # class 'type'
type(str) # class 'type'
class Test(): pass
type(Test) # class 'type'
```
However, you can define your own metaclass like this:
```
class MyMeta(type): pass
```
And apply it to your own class like this (Python 3 only):
```
class MyClass(metaclass = MyMeta):
pass
type(MyClass) # class MyMeta
```
Below is a metaclass I have created which attempts to emulate "static variable" behavior of other languages. It basically works by replacing the default getter, setter, and deleter with versions which check to see if the attribute being requested is a "static variable".
A catalog of the "static variables" is stored in the `StaticVarMeta.statics` attribute. All attribute requests are initially attempted to be resolved using a substitute resolution order. I have dubbed this the "static resolution order", or "SRO". This is done by looking for the requested attribute in the set of "static variables" for a given class (or its parent classes). If the attribute does not appear in the "SRO", the class will fall back on the default attribute get/set/delete behavior (i.e., "MRO").
```
from functools import wraps
class StaticVarsMeta(type):
'''A metaclass for creating classes that emulate the "static variable" behavior
of other languages. I do not advise actually using this for anything!!!
Behavior is intended to be similar to classes that use __slots__. However, "normal"
attributes and __statics___ can coexist (unlike with __slots__).
Example usage:
class MyBaseClass(metaclass = StaticVarsMeta):
__statics__ = {'a','b','c'}
i = 0 # regular attribute
a = 1 # static var defined (optional)
class MyParentClass(MyBaseClass):
__statics__ = {'d','e','f'}
j = 2 # regular attribute
d, e, f = 3, 4, 5 # Static vars
a, b, c = 6, 7, 8 # Static vars (inherited from MyBaseClass, defined/re-defined here)
class MyChildClass(MyParentClass):
__statics__ = {'a','b','c'}
j = 2 # regular attribute (redefines j from MyParentClass)
d, e, f = 9, 10, 11 # Static vars (inherited from MyParentClass, redefined here)
a, b, c = 12, 13, 14 # Static vars (overriding previous definition in MyParentClass here)'''
statics = {}
def __new__(mcls, name, bases, namespace):
# Get the class object
cls = super().__new__(mcls, name, bases, namespace)
# Establish the "statics resolution order"
cls.__sro__ = tuple(c for c in cls.__mro__ if isinstance(c,mcls))
# Replace class getter, setter, and deleter for instance attributes
cls.__getattribute__ = StaticVarsMeta.__inst_getattribute__(cls, cls.__getattribute__)
cls.__setattr__ = StaticVarsMeta.__inst_setattr__(cls, cls.__setattr__)
cls.__delattr__ = StaticVarsMeta.__inst_delattr__(cls, cls.__delattr__)
# Store the list of static variables for the class object
# This list is permanent and cannot be changed, similar to __slots__
try:
mcls.statics[cls] = getattr(cls,'__statics__')
except AttributeError:
mcls.statics[cls] = namespace['__statics__'] = set() # No static vars provided
# Check and make sure the statics var names are strings
if any(not isinstance(static,str) for static in mcls.statics[cls]):
typ = dict(zip((not isinstance(static,str) for static in mcls.statics[cls]), map(type,mcls.statics[cls])))[True].__name__
raise TypeError('__statics__ items must be strings, not {0}'.format(typ))
# Move any previously existing, not overridden statics to the static var parent class(es)
if len(cls.__sro__) > 1:
for attr,value in namespace.items():
if attr not in StaticVarsMeta.statics[cls] and attr != ['__statics__']:
for c in cls.__sro__[1:]:
if attr in StaticVarsMeta.statics[c]:
setattr(c,attr,value)
delattr(cls,attr)
return cls
def __inst_getattribute__(self, orig_getattribute):
'''Replaces the class __getattribute__'''
@wraps(orig_getattribute)
def wrapper(self, attr):
if StaticVarsMeta.is_static(type(self),attr):
return StaticVarsMeta.__getstatic__(type(self),attr)
else:
return orig_getattribute(self, attr)
return wrapper
def __inst_setattr__(self, orig_setattribute):
'''Replaces the class __setattr__'''
@wraps(orig_setattribute)
def wrapper(self, attr, value):
if StaticVarsMeta.is_static(type(self),attr):
StaticVarsMeta.__setstatic__(type(self),attr, value)
else:
orig_setattribute(self, attr, value)
return wrapper
def __inst_delattr__(self, orig_delattribute):
'''Replaces the class __delattr__'''
@wraps(orig_delattribute)
def wrapper(self, attr):
if StaticVarsMeta.is_static(type(self),attr):
StaticVarsMeta.__delstatic__(type(self),attr)
else:
orig_delattribute(self, attr)
return wrapper
def __getstatic__(cls,attr):
'''Static variable getter'''
for c in cls.__sro__:
if attr in StaticVarsMeta.statics[c]:
try:
return getattr(c,attr)
except AttributeError:
pass
raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))
def __setstatic__(cls,attr,value):
'''Static variable setter'''
for c in cls.__sro__:
if attr in StaticVarsMeta.statics[c]:
setattr(c,attr,value)
break
def __delstatic__(cls,attr):
'''Static variable deleter'''
for c in cls.__sro__:
if attr in StaticVarsMeta.statics[c]:
try:
delattr(c,attr)
break
except AttributeError:
pass
raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))
def __delattr__(cls,attr):
'''Prevent __sro__ attribute from deletion'''
if attr == '__sro__':
raise AttributeError('readonly attribute')
super().__delattr__(attr)
def is_static(cls,attr):
'''Returns True if an attribute is a static variable of any class in the __sro__'''
if any(attr in StaticVarsMeta.statics[c] for c in cls.__sro__):
return True
return False
``` |
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 != None):
pb.save("screenshot.png","png")
print "Screenshot saved to screenshot.png."
else:
print "Unable to get the screenshot."
```
Borrowed from <http://ubuntuforums.org/showpost.php?p=2681009&postcount=5> |
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 bitmap
bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
``` |
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 gtk
except ImportError:
pass
else:
self.screen = self.getScreenByGtk
try:
import PyQt4
except ImportError:
pass
else:
self.screen = self.getScreenByQt
try:
import wx
except ImportError:
pass
else:
self.screen = self.getScreenByWx
try:
import ImageGrab
except ImportError:
pass
else:
self.screen = self.getScreenByPIL
def getScreenByGtk(self):
import gtk.gdk
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
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 != None):
return False
else:
width,height = pb.get_width(),pb.get_height()
return Image.fromstring("RGB",(width,height),pb.get_pixels() )
def getScreenByQt(self):
from PyQt4.QtGui import QPixmap, QApplication
from PyQt4.Qt import QBuffer, QIODevice
import StringIO
app = QApplication(sys.argv)
buffer = QBuffer()
buffer.open(QIODevice.ReadWrite)
QPixmap.grabWindow(QApplication.desktop().winId()).save(buffer, 'png')
strio = StringIO.StringIO()
strio.write(buffer.data())
buffer.close()
del app
strio.seek(0)
return Image.open(strio)
def getScreenByPIL(self):
import ImageGrab
img = ImageGrab.grab()
return img
def getScreenByWx(self):
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 bitmap
#bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
myWxImage = wx.ImageFromBitmap( myBitmap )
PilImage = Image.new( 'RGB', (myWxImage.GetWidth(), myWxImage.GetHeight()) )
PilImage.fromstring( myWxImage.GetData() )
return PilImage
if __name__ == '__main__':
s = screengrab()
screen = s.screen()
screen.show()
``` |
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
# fullscreen
im=ImageGrab.grab()
im.show()
# part of the screen
im=ImageGrab.grab(bbox=(10,10,500,500))
im.show()
# to file
ImageGrab.grab_to_file('im.png')
``` |
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")
image.show()
```
One could try to trow some types in the bottleneck-files in PyXlib, and then compile it using Cython. That could increase the speed a bit.
---
**Edit:**
We can write the core of the function in C, and then use it in python from ctypes, here is something I hacked together:
```
#include <stdio.h>
#include <X11/X.h>
#include <X11/Xlib.h>
//Compile hint: gcc -shared -O3 -lX11 -fPIC -Wl,-soname,prtscn -o prtscn.so prtscn.c
void getScreen(const int, const int, const int, const int, unsigned char *);
void getScreen(const int xx,const int yy,const int W, const int H, /*out*/ unsigned char * data)
{
Display *display = XOpenDisplay(NULL);
Window root = DefaultRootWindow(display);
XImage *image = XGetImage(display,root, xx,yy, W,H, AllPlanes, ZPixmap);
unsigned long red_mask = image->red_mask;
unsigned long green_mask = image->green_mask;
unsigned long blue_mask = image->blue_mask;
int x, y;
int ii = 0;
for (y = 0; y < H; y++) {
for (x = 0; x < W; x++) {
unsigned long pixel = XGetPixel(image,x,y);
unsigned char blue = (pixel & blue_mask);
unsigned char green = (pixel & green_mask) >> 8;
unsigned char red = (pixel & red_mask) >> 16;
data[ii + 2] = blue;
data[ii + 1] = green;
data[ii + 0] = red;
ii += 3;
}
}
XDestroyImage(image);
XDestroyWindow(display, root);
XCloseDisplay(display);
}
```
And then the python-file:
```
import ctypes
import os
from PIL import Image
LibName = 'prtscn.so'
AbsLibPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + LibName
grab = ctypes.CDLL(AbsLibPath)
def grab_screen(x1,y1,x2,y2):
w, h = x1+x2, y1+y2
size = w * h
objlength = size * 3
grab.getScreen.argtypes = []
result = (ctypes.c_ubyte*objlength)()
grab.getScreen(x1,y1, w, h, result)
return Image.frombuffer('RGB', (w, h), result, 'raw', 'RGB', 0, 1)
if __name__ == '__main__':
im = grab_screen(0,0,1440,900)
im.show()
``` |
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 __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
What's the deal?!
I'll explain this a little for those who didn't quite get that.
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
```
What I did there is create a class with a public method and a private method and instantiate it.
Next, I call its public method.
```
>>> obj.myPublicMethod()
public method
```
Next, I try and call its private method.
```
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
```
Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running *dir()* on the object reveals a new magical method that python creates magically for all of your 'private' methods.
```
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
```
This new method's name is always an underscore, followed by the class name, followed by the method name.
```
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
So much for encapsulation, eh?
In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives? | 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 them seem
> inaccessible by their given names. You
> can access the \_\_parse method of the
> MP3FileInfo class by the name
> \_MP3FileInfo\_\_parse. Acknowledge that this is interesting, then promise to
> never, ever do it in real code.
> Private methods are private for a
> reason, but like many other things in
> Python, their privateness is
> ultimately a matter of convention, not
> force. |
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 __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
What's the deal?!
I'll explain this a little for those who didn't quite get that.
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
```
What I did there is create a class with a public method and a private method and instantiate it.
Next, I call its public method.
```
>>> obj.myPublicMethod()
public method
```
Next, I try and call its private method.
```
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
```
Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running *dir()* on the object reveals a new magical method that python creates magically for all of your 'private' methods.
```
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
```
This new method's name is always an underscore, followed by the class name, followed by the method name.
```
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
So much for encapsulation, eh?
In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives? | 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 secure your stuff by OO-encapsulation, do you? |
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 __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
What's the deal?!
I'll explain this a little for those who didn't quite get that.
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
```
What I did there is create a class with a public method and a private method and instantiate it.
Next, I call its public method.
```
>>> obj.myPublicMethod()
public method
```
Next, I try and call its private method.
```
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
```
Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running *dir()* on the object reveals a new magical method that python creates magically for all of your 'private' methods.
```
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
```
This new method's name is always an underscore, followed by the class name, followed by the method name.
```
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
So much for encapsulation, eh?
In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives? | 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 would do this if he cares about encapsulation. |
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 __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
What's the deal?!
I'll explain this a little for those who didn't quite get that.
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
```
What I did there is create a class with a public method and a private method and instantiate it.
Next, I call its public method.
```
>>> obj.myPublicMethod()
public method
```
Next, I try and call its private method.
```
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
```
Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running *dir()* on the object reveals a new magical method that python creates magically for all of your 'private' methods.
```
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
```
This new method's name is always an underscore, followed by the class name, followed by the method name.
```
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
So much for encapsulation, eh?
In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives? | 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 responsibly of course. |
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 __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
What's the deal?!
I'll explain this a little for those who didn't quite get that.
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
```
What I did there is create a class with a public method and a private method and instantiate it.
Next, I call its public method.
```
>>> obj.myPublicMethod()
public method
```
Next, I try and call its private method.
```
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
```
Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running *dir()* on the object reveals a new magical method that python creates magically for all of your 'private' methods.
```
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
```
This new method's name is always an underscore, followed by the class name, followed by the method name.
```
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
So much for encapsulation, eh?
In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives? | 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, unless they have a compelling reason not to (e.g. debuggers, code completion).
If you truly must have something that is private, then you can implement it in an extension (e.g. in C for CPython). In most cases, however, you simply learn the Pythonic way of doing things. |
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 __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
What's the deal?!
I'll explain this a little for those who didn't quite get that.
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
```
What I did there is create a class with a public method and a private method and instantiate it.
Next, I call its public method.
```
>>> obj.myPublicMethod()
public method
```
Next, I try and call its private method.
```
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
```
Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running *dir()* on the object reveals a new magical method that python creates magically for all of your 'private' methods.
```
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
```
This new method's name is always an underscore, followed by the class name, followed by the method name.
```
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
So much for encapsulation, eh?
In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives? | 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):
... print self.__baz
...
>>> class Bar(Foo):
... def __init__(self):
... super(Bar, self).__init__()
... self.__baz = 21
... def bar(self):
... print self.__baz
...
>>> x = Bar()
>>> x.foo()
42
>>> x.bar()
21
>>> print x.__dict__
{'_Bar__baz': 21, '_Foo__baz': 42}
```
Of course, it breaks down if two different classes have the same name. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.