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
Why are Python's 'private' methods not actually private?
70,528
344
2008-09-16T08:59:32Z
80,000
11
2008-09-17T04:29: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?
Similar behavior exists when module attribute names begin with a single underscore (e.g. \_foo). Module attributes named as such will not be copied into an importing module when using the `from*` method, e.g.: ``` from bar import * ``` However, this is a convention and not a language constraint. These are not private attributes; they can be referenced and manipulated by any importer. Some argue that because of this, Python can not implement true encapsulation.
Why are Python's 'private' methods not actually private?
70,528
344
2008-09-16T08:59:32Z
1,949,874
100
2009-12-22T23:25:42Z
[ "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?
When I first came from Java to Python i **hated** this. It scared me to death. Today it might just be the one thing **I love most** about Python. I love being on a platform, where people trust each other and don't feel like they need to build impenetrable walls around their code. In strongly encapsulated languages, if an API has a bug, and you have figured out what goes wrong, you may still be unable to work around it because the needed method is private. In Python the attitude is: "sure". If you think you understand the situation, perhaps you have even read it, then all we can say is "good luck!". Remember, encapsulation is not even weakly related to "security", or keeping the kids off the lawn. It is just another pattern that should be used to make a code base easier to understand.
Why are Python's 'private' methods not actually private?
70,528
344
2008-09-16T08:59:32Z
3,147,548
185
2010-06-30T08:24:05Z
[ "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?
### Example of private function ``` import re import inspect class MyClass : def __init__(self) : pass def private_function ( self ) : try : function_call = inspect.stack()[1][4][0].strip() # See if the function_call has "self." in the begining matched = re.match( '^self\.', function_call ) if not matched : print 'This is Private Function, Go Away' return except : print 'This is Private Function, Go Away' return # This is the real Function, only accessible inside class # print 'Hey, Welcome in to function' def public_function ( self ) : # i can call private function from inside the class self.private_function() ### End ### ```
Python Authentication API
70,653
5
2008-09-16T09:17:41Z
80,008
9
2008-09-17T04:31:02Z
[ "python", "authentication", "desktop" ]
I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing. I have found several method in web framework such as django or turbogears. I just want a kind of username-password association stored into a local file. I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).
dbr said: > ``` > def hash_password(password): > """Returns the hashed version of a string > """ > return hasher.new( str(password) ).hexdigest() > ``` This is a really insecure way to hash passwords. You *don't* want to do this. If you want to know why read the [Bycrypt Paper](http://www.openbsd.org/papers/bcrypt-paper.pdf) by the guys who did the password hashing system for OpenBSD. Additionally if want a good discussion on how passwords are broken check out [this interview](http://www.securityfocus.com/columnists/388) with the author of Jack the Ripper (the popular unix password cracker). Now B-Crypt is great but I have to admit I don't use this system because I didn't have the EKS-Blowfish algorithm available and did not want to implement it my self. I use a slightly updated version of the FreeBSD system which I will post below. The gist is this. Don't just hash the password. Salt the password then hash the password and repeat 10,000 or so times. If that didn't make sense here is the code: ``` #note I am using the Python Cryptography Toolkit from Crypto.Hash import SHA256 HASH_REPS = 50000 def __saltedhash(string, salt): sha256 = SHA256.new() sha256.update(string) sha256.update(salt) for x in xrange(HASH_REPS): sha256.update(sha256.digest()) if x % 10: sha256.update(salt) return sha256 def saltedhash_bin(string, salt): """returns the hash in binary format""" return __saltedhash(string, salt).digest() def saltedhash_hex(string, salt): """returns the hash in hex format""" return __saltedhash(string, salt).hexdigest() ``` For deploying a system like this the key thing to consider is the HASH\_REPS constant. This is the scalable cost factor in this system. You will need to do testing to determine what is the exceptable amount of time you want to wait for each hash to be computed versus the risk of an offline dictionary based attack on your password file. Security is hard, and the method I present is not the best way to do this, but it is significantly better than a simple hash. Additionally it is dead simple to implement. So even you don't choose a more complex solution this isn't the worst out there. hope this helps, Tim
Python: user input and commandline arguments
70,797
222
2008-09-16T09:44:59Z
70,814
296
2008-09-16T09:48:16Z
[ "python", "input", "command-line-arguments" ]
How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?
``` var = raw_input("Please enter something: ") print "you entered", var ```
Python: user input and commandline arguments
70,797
222
2008-09-16T09:44:59Z
70,818
22
2008-09-16T09:48:40Z
[ "python", "input", "command-line-arguments" ]
How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?
The best way to process command line arguments is the [`argparse` module.](https://docs.python.org/library/argparse.html) Use `raw_input()` to get user input. If you import the [`readline module`](https://docs.python.org/library/readline.html) your users will have line editing and history.
Python: user input and commandline arguments
70,797
222
2008-09-16T09:44:59Z
70,833
182
2008-09-16T09:50:40Z
[ "python", "input", "command-line-arguments" ]
How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?
To read user input you can try [the cmd module](http://docs.python.org/2/library/cmd.html) for easily creating a mini-command line interpreter (with help texts and autocompletion) and [raw\_input](http://docs.python.org/2/library/functions.html#raw_input) for less fancy stuff (just reading a line of text from the user). Command line inputs are in sys.argv. Try this in your script for Python 2: ``` import sys print sys.argv ``` For Python 3: ``` import sys print(sys.argv) ``` Since print has changed from a keyword in Python 2 into a function call in Python 3. There are two modules for parsing command line options: [optparse](http://docs.python.org/2/library/optparse.html) and [getopt](http://docs.python.org/2/library/getopt.html). If you just want to input files to your script, behold the power of [fileinput](http://docs.python.org/2/library/fileinput.html). The [Python library reference is your friend](http://docs.python.org/2/library/).
Python: user input and commandline arguments
70,797
222
2008-09-16T09:44:59Z
70,869
10
2008-09-16T09:58:33Z
[ "python", "input", "command-line-arguments" ]
How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?
Careful not to use the `input` function, unless you know what you're doing. Unlike `raw_input`, `input` will accept any python expression, so it's kinda like `eval`
Python: user input and commandline arguments
70,797
222
2008-09-16T09:44:59Z
8,334,188
127
2011-11-30T22:53:49Z
[ "python", "input", "command-line-arguments" ]
How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?
`raw_input` is no longer available in Python 3.x. But `raw_input` was renamed `input`, so the same functionality exists. ``` input_var = input("Enter something: ") print ("you entered " + input_var) ``` [Documentation of the change](http://docs.python.org/py3k/whatsnew/3.0.html#builtins)
HTML parser in Python
71,151
7
2008-09-16T10:49:36Z
71,161
12
2008-09-16T10:51:40Z
[ "python", "import" ]
Using the Python Documentation I found the [HTML parser](http://docs.python.org/lib/module-HTMLParser.html) but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).
Try: ``` import HTMLParser ``` In Python 3.0, the HTMLParser module has been renamed to html.parser you can check about this [here](http://docs.python.org/library/htmlparser.html) Python 3.0 ``` import html.parser ``` Python 2.2 and above ``` import HTMLParser ```
HTML parser in Python
71,151
7
2008-09-16T10:49:36Z
71,174
22
2008-09-16T10:54:05Z
[ "python", "import" ]
Using the Python Documentation I found the [HTML parser](http://docs.python.org/lib/module-HTMLParser.html) but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).
You probably really want [BeautifulSoup](http://stackoverflow.com/questions/55391/python-regular-expression-for-html-parsing-beautifulsoup#55424), check the link for an example. But in any case ``` >>> import HTMLParser >>> h = HTMLParser.HTMLParser() >>> h.feed('<html></html>') >>> h.get_starttag_text() '<html>' >>> h.close() ```
Python and "re"
72,393
6
2008-09-16T13:47:48Z
72,470
19
2008-09-16T13:53:03Z
[ "python", "regex" ]
A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed. After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change: ``` regex = ".*(a_regex_of_pure_awesomeness)" ``` into ``` regex = "a_regex_of_pure_awesomeness" ``` Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.
In Python, there's a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string. [Python regex docs](http://docs.python.org/lib/module-re.html) [Matching vs searching](http://docs.python.org/lib/matching-searching.html)
Python's unittest logic
72,422
3
2008-09-16T13:50:25Z
72,504
11
2008-09-16T13:55:02Z
[ "python", "unit-testing" ]
Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test. ``` >>> class MyTest(unittest.TestCase): def setUp(self): self.i = 1 def testA(self): self.i = 3 self.assertEqual(self.i, 3) def testB(self): self.assertEqual(self.i, 3) >>> unittest.main() .F ====================================================================== FAIL: testB (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "<pyshell#61>", line 8, in testB AssertionError: 1 != 3 ---------------------------------------------------------------------- Ran 2 tests in 0.016s ```
From <http://docs.python.org/lib/minimal-example.html> : > When a setUp() method is defined, the > test runner will run that method prior > to each test. So setUp() gets run before both testA and testB, setting i to 1 each time. Behind the scenes, the entire test object is actually being re-instantiated for each test, with setUp() being run on each new instantiation before the test is executed.
Python's unittest logic
72,422
3
2008-09-16T13:50:25Z
73,791
9
2008-09-16T15:47:30Z
[ "python", "unit-testing" ]
Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test. ``` >>> class MyTest(unittest.TestCase): def setUp(self): self.i = 1 def testA(self): self.i = 3 self.assertEqual(self.i, 3) def testB(self): self.assertEqual(self.i, 3) >>> unittest.main() .F ====================================================================== FAIL: testB (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "<pyshell#61>", line 8, in testB AssertionError: 1 != 3 ---------------------------------------------------------------------- Ran 2 tests in 0.016s ```
Each test is run using a new instance of the MyTest class. That means if you change self in one test, changes will not carry over to other tests, since self will refer to a different instance. Additionally, as others have pointed out, setUp is called before each test.
How to do relative imports in Python?
72,852
309
2008-09-16T14:24:02Z
73,149
189
2008-09-16T14:48:56Z
[ "python", "python-import", "python-module" ]
Imagine this directory structure: ``` app/ __init__.py sub1/ __init__.py mod1.py sub2/ __init__.py mod2.py ``` I'm coding `mod1`, and I need to import something from `mod2`. How should I do it? I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-package". I googled around but found only "`sys.path` manipulation" hacks. Isn't there a clean way? --- Edit: all my `__init__.py`'s are currently empty Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (`sub1`, `subX`, etc.). Edit3: The behaviour I'm looking for is the same as described in [PEP 366](http://www.python.org/dev/peps/pep-0366/) (thanks John B)
Everyone seems to want to tell you what you should be doing rather than just answering the question. The problem is that you're running the module as '\_\_main\_\_' by passing the mod1.py as an argument to the interpreter. From [PEP 328](http://www.python.org/dev/peps/pep-0328/): > Relative imports use a module's \_\_name\_\_ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '\_\_main\_\_') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system. In Python 2.6, they're adding the ability to reference modules relative to the main module. [PEP 366](http://python.org/dev/peps/pep-0366/) describes the change. **Update**: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.
How to do relative imports in Python?
72,852
309
2008-09-16T14:24:02Z
465,129
82
2009-01-21T12:42:11Z
[ "python", "python-import", "python-module" ]
Imagine this directory structure: ``` app/ __init__.py sub1/ __init__.py mod1.py sub2/ __init__.py mod2.py ``` I'm coding `mod1`, and I need to import something from `mod2`. How should I do it? I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-package". I googled around but found only "`sys.path` manipulation" hacks. Isn't there a clean way? --- Edit: all my `__init__.py`'s are currently empty Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (`sub1`, `subX`, etc.). Edit3: The behaviour I'm looking for is the same as described in [PEP 366](http://www.python.org/dev/peps/pep-0366/) (thanks John B)
``` main.py setup.py app/ -> __init__.py package_a/ -> __init__.py module_a.py package_b/ -> __init__.py module_b.py ``` 1. You run `python main.py`. 2. `main.py` does: `import app.package_a.module_a` 3. `module_a.py` does `import app.package_b.module_b` Alternatively 2 or 3 could use: `from app.package_a import module_a` That will work as long as you have `app` in your PYTHONPATH. `main.py` could be anywhere then. So you write a `setup.py` to copy (install) the whole app package and subpackages to the target system's python folders, and `main.py` to target system's script folders.
How to do relative imports in Python?
72,852
309
2008-09-16T14:24:02Z
1,083,169
24
2009-07-04T23:27:50Z
[ "python", "python-import", "python-module" ]
Imagine this directory structure: ``` app/ __init__.py sub1/ __init__.py mod1.py sub2/ __init__.py mod2.py ``` I'm coding `mod1`, and I need to import something from `mod2`. How should I do it? I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-package". I googled around but found only "`sys.path` manipulation" hacks. Isn't there a clean way? --- Edit: all my `__init__.py`'s are currently empty Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (`sub1`, `subX`, etc.). Edit3: The behaviour I'm looking for is the same as described in [PEP 366](http://www.python.org/dev/peps/pep-0366/) (thanks John B)
``` def import_path(fullpath): """ Import a file with full path specification. Allows one to import from anywhere, something __import__ does not do. """ path, filename = os.path.split(fullpath) filename, ext = os.path.splitext(filename) sys.path.append(path) module = __import__(filename) reload(module) # Might be out of date del sys.path[-1] return module ``` I'm using this snippet to import modules from paths, hope that helps
How to do relative imports in Python?
72,852
309
2008-09-16T14:24:02Z
8,195,271
26
2011-11-19T16:05:29Z
[ "python", "python-import", "python-module" ]
Imagine this directory structure: ``` app/ __init__.py sub1/ __init__.py mod1.py sub2/ __init__.py mod2.py ``` I'm coding `mod1`, and I need to import something from `mod2`. How should I do it? I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-package". I googled around but found only "`sys.path` manipulation" hacks. Isn't there a clean way? --- Edit: all my `__init__.py`'s are currently empty Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (`sub1`, `subX`, etc.). Edit3: The behaviour I'm looking for is the same as described in [PEP 366](http://www.python.org/dev/peps/pep-0366/) (thanks John B)
"Guido views running scripts within a package as an anti-pattern" (rejected [PEP-3122](http://www.python.org/dev/peps/pep-3122/)) I have spent so much time trying to find a solution, reading related posts here on Stack Overflow and saying to myself "there must be a better way!". Looks like there is not.
How to do relative imports in Python?
72,852
309
2008-09-16T14:24:02Z
15,458,607
67
2013-03-17T07:43:34Z
[ "python", "python-import", "python-module" ]
Imagine this directory structure: ``` app/ __init__.py sub1/ __init__.py mod1.py sub2/ __init__.py mod2.py ``` I'm coding `mod1`, and I need to import something from `mod2`. How should I do it? I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-package". I googled around but found only "`sys.path` manipulation" hacks. Isn't there a clean way? --- Edit: all my `__init__.py`'s are currently empty Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (`sub1`, `subX`, etc.). Edit3: The behaviour I'm looking for is the same as described in [PEP 366](http://www.python.org/dev/peps/pep-0366/) (thanks John B)
Here is the solution which works for me: I do the relative imports as `from ..sub2 import mod2` and then, if I want to run `mod1.py` then I go to the parent directory of `app` and run the module using the python -m switch as `python -m app.sub1.mod1`. The real reason why this problem occurs with relative imports, is that relative imports works by taking the `__name__` property of the module. If the module is being directly run, then `__name__` is set to `__main__` and it doesn't contain any information about package structure. And, thats why python complains about the `relative import in non-package` error. So, by using the -m switch you provide the package structure information to python, through which it can resolve the relative imports successfully. I have encountered this problem many times while doing relative imports. And, after reading all the previous answers, I was still not able to figure out how to solve it, in a clean way, without needing to put boilerplate code in all files. (Though some of the comments were really helpful, thanks to @ncoghlan and @XiongChiamiov) Hope this helps someone who is fighting with relative imports problem, because going through PEP is really not fun.
How to do relative imports in Python?
72,852
309
2008-09-16T14:24:02Z
20,449,492
8
2013-12-08T03:19:42Z
[ "python", "python-import", "python-module" ]
Imagine this directory structure: ``` app/ __init__.py sub1/ __init__.py mod1.py sub2/ __init__.py mod2.py ``` I'm coding `mod1`, and I need to import something from `mod2`. How should I do it? I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-package". I googled around but found only "`sys.path` manipulation" hacks. Isn't there a clean way? --- Edit: all my `__init__.py`'s are currently empty Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (`sub1`, `subX`, etc.). Edit3: The behaviour I'm looking for is the same as described in [PEP 366](http://www.python.org/dev/peps/pep-0366/) (thanks John B)
explanation of `nosklo's` answer with examples *note: all `__init__.py` files are empty.* ``` main.py app/ -> __init__.py package_a/ -> __init__.py fun_a.py package_b/ -> __init__.py fun_b.py ``` ### app/package\_a/fun\_a.py ``` def print_a(): print 'This is a function in dir package_a' ``` ### app/package\_b/fun\_b.py ``` from app.package_a.fun_a import print_a def print_b(): print 'This is a function in dir package_b' print 'going to call a function in dir package_a' print '-'*30 print_a() ``` ### main.py ``` from app.package_b import fun_b fun_b.print_b() ``` if you run `$ python main.py` it returns: ``` This is a function in dir package_b going to call a function in dir package_a ------------------------------ This is a function in dir package_a ``` * main.py does: `from app.package_b import fun_b` * fun\_b.py does `from app.package_a.fun_a import print_a` so file in folder `package_b` used file in folder `package_a`, which is what you want. Right??
How do I sort a list of dictionaries by values of the dictionary in Python?
72,899
822
2008-09-16T14:27:47Z
72,950
7
2008-09-16T14:31:52Z
[ "python", "list", "sorting", "dictionary" ]
I got a list of dictionaries and want that to be sorted by a value of that dictionary. This ``` [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] ``` sorted by name, should become ``` [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}] ```
You have to implement your own comparison function that will compare the dictionaries by values of name keys. See [Sorting Mini-HOW TO from PythonInfo Wiki](http://wiki.python.org/moin/HowTo/Sorting)
How do I sort a list of dictionaries by values of the dictionary in Python?
72,899
822
2008-09-16T14:27:47Z
73,019
7
2008-09-16T14:36:54Z
[ "python", "list", "sorting", "dictionary" ]
I got a list of dictionaries and want that to be sorted by a value of that dictionary. This ``` [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] ``` sorted by name, should become ``` [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}] ```
I guess you've meant: ``` [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] ``` This would be sorted like this: ``` sorted(l,cmp=lambda x,y: cmp(x['name'],y['name'])) ```
How do I sort a list of dictionaries by values of the dictionary in Python?
72,899
822
2008-09-16T14:27:47Z
73,044
12
2008-09-16T14:39:11Z
[ "python", "list", "sorting", "dictionary" ]
I got a list of dictionaries and want that to be sorted by a value of that dictionary. This ``` [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] ``` sorted by name, should become ``` [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}] ```
``` my_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] my_list.sort(lambda x,y : cmp(x['name'], y['name'])) ``` `my_list` will now be what you want. **(3 years later) Edited to add:** The new `key` argument is more efficient and neater. A better answer now looks like: ``` my_list = sorted(my_list, key=lambda k: k['name']) ``` ...the lambda is, IMO, easier to understand than `operator.itemgetter`, but YMMV.
How do I sort a list of dictionaries by values of the dictionary in Python?
72,899
822
2008-09-16T14:27:47Z
73,050
1,147
2008-09-16T14:39:44Z
[ "python", "list", "sorting", "dictionary" ]
I got a list of dictionaries and want that to be sorted by a value of that dictionary. This ``` [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] ``` sorted by name, should become ``` [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}] ```
It may look cleaner using a key instead a cmp: ``` newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) ``` or as J.F.Sebastian and others suggested, ``` from operator import itemgetter newlist = sorted(list_to_be_sorted, key=itemgetter('name')) ``` For completeness (as pointed out in comments by fitzgeraldsteele), add `reverse=True` to sort descending ``` newlist = sorted(l, key=itemgetter('name'), reverse=True) ```
How do I sort a list of dictionaries by values of the dictionary in Python?
72,899
822
2008-09-16T14:27:47Z
73,098
13
2008-09-16T14:43:51Z
[ "python", "list", "sorting", "dictionary" ]
I got a list of dictionaries and want that to be sorted by a value of that dictionary. This ``` [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] ``` sorted by name, should become ``` [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}] ```
``` import operator a_list_of_dicts.sort(key=operator.itemgetter('name')) ``` 'key' is used to sort by an arbitrary value and 'itemgetter' sets that value to each item's 'name' attribute.
How do I sort a list of dictionaries by values of the dictionary in Python?
72,899
822
2008-09-16T14:27:47Z
73,186
8
2008-09-16T14:52:14Z
[ "python", "list", "sorting", "dictionary" ]
I got a list of dictionaries and want that to be sorted by a value of that dictionary. This ``` [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] ``` sorted by name, should become ``` [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}] ```
You could use a custom comparison function, or you could pass in a function that calculates a custom sort key. That's usually more efficient as the key is only calculated once per item, while the comparison function would be called many more times. You could do it this way: ``` def mykey(adict): return adict['name'] x = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}] sorted(x, key=mykey) ``` But the standard library contains a generic routine for getting items of arbitrary objects: `itemgetter`. So try this instead: ``` from operator import itemgetter x = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}] sorted(x, key=itemgetter('name')) ```
How do I sort a list of dictionaries by values of the dictionary in Python?
72,899
822
2008-09-16T14:27:47Z
73,465
68
2008-09-16T15:18:14Z
[ "python", "list", "sorting", "dictionary" ]
I got a list of dictionaries and want that to be sorted by a value of that dictionary. This ``` [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] ``` sorted by name, should become ``` [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}] ```
``` import operator ``` To sort the list of dictionaries by key='name': ``` list_of_dicts.sort(key=operator.itemgetter('name')) ``` To sort the list of dictionaries by key='age': ``` list_of_dicts.sort(key=operator.itemgetter('age')) ```
How do I sort a list of dictionaries by values of the dictionary in Python?
72,899
822
2008-09-16T14:27:47Z
2,858,683
24
2010-05-18T15:28:11Z
[ "python", "list", "sorting", "dictionary" ]
I got a list of dictionaries and want that to be sorted by a value of that dictionary. This ``` [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] ``` sorted by name, should become ``` [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}] ```
If you want to sort the list by multiple keys you can do the following: ``` my_list = [{'name':'Homer', 'age':39}, {'name':'Milhouse', 'age':10}, {'name':'Bart', 'age':10} ] sortedlist = sorted(my_list , key=lambda elem: "%02d %s" % (elem['age'], elem['name'])) ``` It is rather hackish, since it relies on converting the values into a single string representation for comparison, but it works as expected for numbers including negative ones (although you will need to format your string appropriately with zero paddings if you are using numbers)
How do I sort a list of dictionaries by values of the dictionary in Python?
72,899
822
2008-09-16T14:27:47Z
16,772,049
8
2013-05-27T11:21:03Z
[ "python", "list", "sorting", "dictionary" ]
I got a list of dictionaries and want that to be sorted by a value of that dictionary. This ``` [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] ``` sorted by name, should become ``` [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}] ```
Using Schwartzian transform from Perl, ``` py = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] ``` do ``` sort_on = "name" decorated = [(dict_[sort_on], dict_) for dict_ in py] decorated.sort() result = [dict_ for (key, dict_) in decorated] ``` gives ``` >>> result [{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}] ``` More on [Perl Schwartzian transform](http://en.wikipedia.org/wiki/Schwartzian_transform) > In computer science, the Schwartzian transform is a Perl programming > idiom used to improve the efficiency of sorting a list of items. This > idiom is appropriate for comparison-based sorting when the ordering is > actually based on the ordering of a certain property (the key) of the > elements, where computing that property is an intensive operation that > should be performed a minimal number of times. The Schwartzian > Transform is notable in that it does not use named temporary arrays.
How to create a triple-join table with Django
72,945
9
2008-09-16T14:31:21Z
77,898
8
2008-09-16T22:22:52Z
[ "python", "django", "model-view-controller", "model" ]
Using Django's built in models, how would one create a triple-join between three models. For example: * Users, Roles, and Events are the models. * Users have many Roles, and Roles many Users. (ManyToMany) * Events have many Users, and Users many Events. (ManyToMany) * But for any given Event, any User may have only one Role. How can this be represented in the model?
**zacherates** writes: > I'd model Role as an association class between Users and Roles (...) I'd also reccomed this solution, but you can also make use of some syntactical sugar provided by Django: [ManyToMany relation with extra fields](http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships). Example: ``` class User(models.Model): name = models.CharField(max_length=128) class Event(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(User, through='Role') def __unicode__(self): return self.name class Role(models.Model): person = models.ForeignKey(User) group = models.ForeignKey(Event) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) ```
Terminating a Python script
73,663
469
2008-09-16T15:35:55Z
73,673
644
2008-09-16T15:36:36Z
[ "python", "termination" ]
I am aware of the `die()` command in PHP which stops a script early. How can I do this in Python?
``` import sys sys.exit() ``` details from the [`sys` module documentation](https://docs.python.org/2/library/constants.html#exit): > `sys.exit([arg])` > > > Exit from Python. This is implemented by raising the > > [`SystemExit`](https://docs.python.org/2/library/exceptions.html#SystemExit) exception, so cleanup actions specified by finally clauses > > of [`try`](https://docs.python.org/2/reference/compound_stmts.html#try) statements are honored, and it is possible to intercept the > > exit attempt at an outer level. > > > > The optional argument *arg* can be an integer giving the exit status > > (defaulting to zero), or another type of object. If it is an integer, > > zero is considered “successful termination” and any nonzero value is > > considered “abnormal termination” by shells and the like. Most systems > > require it to be in the range 0-127, and produce undefined results > > otherwise. Some systems have a convention for assigning specific > > meanings to specific exit codes, but these are generally > > underdeveloped; Unix programs generally use 2 for command line syntax > > errors and 1 for all other kind of errors. If another type of object > > is passed, None is equivalent to passing zero, and any other object is > > printed to [`stderr`](https://docs.python.org/2/library/sys.html#sys.stderr) and results in an exit code of 1. In particular, > > `sys.exit("some error message")` is a quick way to exit a program when > > an error occurs. > > > > Since [`exit()`](https://docs.python.org/2/library/constants.html#exit) ultimately “only” raises an exception, it will only exit > > the process when called from the main thread, and the exception is not > > intercepted. Note that this is the 'nice' way to exit. @[glyphtwistedmatrix](http://stackoverflow.com/questions/73663/terminating-a-python-script#76374) below points out that if you want a 'hard exit', you can use os.\_exit(*errorcode*), though it's likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn't let the interpreter do any cleanup before the process dies.
Terminating a Python script
73,663
469
2008-09-16T15:35:55Z
73,680
72
2008-09-16T15:37:13Z
[ "python", "termination" ]
I am aware of the `die()` command in PHP which stops a script early. How can I do this in Python?
Another way is: ``` raise SystemExit ```
Terminating a Python script
73,663
469
2008-09-16T15:35:55Z
73,695
16
2008-09-16T15:38:28Z
[ "python", "termination" ]
I am aware of the `die()` command in PHP which stops a script early. How can I do this in Python?
``` from sys import exit exit() ``` As a parameter you can pass an exit code, which will be returned to OS. Default is 0.
Terminating a Python script
73,663
469
2008-09-16T15:35:55Z
76,374
48
2008-09-16T20:08:04Z
[ "python", "termination" ]
I am aware of the `die()` command in PHP which stops a script early. How can I do this in Python?
While you should generally prefer `sys.exit` because it is more "friendly" to other code, all it actually does is raise an exception. If you are sure that you need to exit a process immediately, and you might be inside of some exception handler which would catch `SystemExit`, there is another function - `os._exit` - which terminates immediately at the C level and does not perform any of the normal tear-down of the interpreter; for example, hooks registered with the "atexit" module are not executed.
Terminating a Python script
73,663
469
2008-09-16T15:35:55Z
14,836,329
89
2013-02-12T15:50:06Z
[ "python", "termination" ]
I am aware of the `die()` command in PHP which stops a script early. How can I do this in Python?
A simple way to terminate a Python script early is to use the built-in function quit(). There is no need to import any library, and it is efficient and simple. Example: ``` #do stuff if this == that: quit() ```
Terminating a Python script
73,663
469
2008-09-16T15:35:55Z
16,150,238
30
2013-04-22T14:57:00Z
[ "python", "termination" ]
I am aware of the `die()` command in PHP which stops a script early. How can I do this in Python?
You can also use simply `exit()`. Keep in mind that `sys.exit()`, `exit()`, `quit()`, and `os._exit(0)` **kill** the Python interpreter. Therefore, if it appears in a script called from another script by `execfile()`, it stops execution of both scripts. See "[Stop execution of a script called with execfile](http://stackoverflow.com/a/1028632/1897240)" to avoid this.
Terminating a Python script
73,663
469
2008-09-16T15:35:55Z
22,504,027
8
2014-03-19T11:13:22Z
[ "python", "termination" ]
I am aware of the `die()` command in PHP which stops a script early. How can I do this in Python?
I'm a total novice but surely this is cleaner and more controlled ``` def main(): try: Answer = 1/0 print Answer except: print 'Program terminated' return print 'You wont see this' if __name__ == '__main__': main() ``` ... > Program terminated than ``` import sys def main(): try: Answer = 1/0 print Answer except: print 'Program terminated' sys.exit() print 'You wont see this' if __name__ == '__main__': main() ``` ... > > Program terminated Traceback (most recent call last): File "Z:\Directory\testdieprogram.py", line 12, in > > main() File "Z:\Directory\testdieprogram.py", line 8, in main > > sys.exit() SystemExit
Sending mail via sendmail from python
73,781
47
2008-09-16T15:46:43Z
73,844
24
2008-09-16T15:51:40Z
[ "python", "email", "sendmail" ]
If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process? Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice? I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:25; a few of these are part of embedded systems and can't be set up to accept SMTP. As part of Good Practice, I'd really like to have the library take care of header injection vulnerabilities itself -- so just dumping a string to `popen('/usr/bin/sendmail', 'w')` is a little closer to the metal than I'd like. If the answer is 'go write a library,' so be it ;-)
This is a simple python function that uses the unix sendmail to deliver a mail. ``` def sendMail(): sendmail_location = "/usr/sbin/sendmail" # sendmail location p = os.popen("%s -t" % sendmail_location, "w") p.write("From: %s\n" % "[email protected]") p.write("To: %s\n" % "[email protected]") p.write("Subject: thesubject\n") p.write("\n") # blank line separating headers from body p.write("body of the mail") status = p.close() if status != 0: print "Sendmail exit status", status ```
Sending mail via sendmail from python
73,781
47
2008-09-16T15:46:43Z
74,084
79
2008-09-16T16:12:37Z
[ "python", "email", "sendmail" ]
If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process? Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice? I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:25; a few of these are part of embedded systems and can't be set up to accept SMTP. As part of Good Practice, I'd really like to have the library take care of header injection vulnerabilities itself -- so just dumping a string to `popen('/usr/bin/sendmail', 'w')` is a little closer to the metal than I'd like. If the answer is 'go write a library,' so be it ;-)
Header injection isn't a factor in how you send the mail, it's a factor in how you construct the mail. Check the [email](https://docs.python.org/2/library/email.html) package, construct the mail with that, serialise it, and send it to `/usr/sbin/sendmail` using the [subprocess](https://docs.python.org/2/library/subprocess.html) module: ``` from email.mime.text import MIMEText from subprocess import Popen, PIPE msg = MIMEText("Here is the body of my message") msg["From"] = "[email protected]" msg["To"] = "[email protected]" msg["Subject"] = "This is the subject." p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE) p.communicate(msg.as_string()) ```
Is there a common way to check in Python if an object is any function type?
74,092
6
2008-09-16T16:13:09Z
75,507
13
2008-09-16T18:34:03Z
[ "python", "types" ]
I have a function in Python which is iterating over the attributes returned from dir(obj), and I want to check to see if any of the objects contained within is a function, method, built-in function, etc. Normally you could use callable() for this, but I don't want to include classes. The best I've come up with so far is: ``` isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType)) ``` Is there a more future-proof way to do this check? **Edit:** I misspoke before when I said: "Normally you could use callable() for this, but I don't want to disqualify classes." I actually *do* want to disqualify classes. I want to match *only* functions, not classes.
The inspect module has exactly what you want: ``` inspect.isroutine( obj ) ``` FYI, the code is: ``` def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object)) ```
Random in python 2.5 not working?
74,430
8
2008-09-16T16:49:33Z
75,427
34
2008-09-16T18:26:02Z
[ "python" ]
I am trying to use the `import random` statement in python, but it doesn't appear to have any methods in it to use. Am I missing something?
You probably have a file named random.py or random.pyc in your working directory. That's shadowing the built-in random module. You need to rename random.py to something like my\_random.py and/or remove the random.pyc file. To tell for sure what's going on, do this: ``` >>> import random >>> print random.__file__ ``` That will show you exactly which file is being imported.
How do I get the name of a python class as a string?
75,440
30
2008-09-16T18:26:47Z
75,456
28
2008-09-16T18:27:58Z
[ "python" ]
What method do I call to get the name of a class?
It's not a method, it's a field. The field is called `__name__`. `class.__name__` will give the name of the class as a string. `object.__class__.__name__` will give the name of the class of an object.
How do I get the name of a python class as a string?
75,440
30
2008-09-16T18:26:47Z
75,467
33
2008-09-16T18:28:51Z
[ "python" ]
What method do I call to get the name of a class?
``` In [1]: class test(object): ...: pass ...: In [2]: test.__name__ Out[2]: 'test' ```
Django -vs- Grails -vs-?
75,798
16
2008-09-16T19:05:48Z
77,693
9
2008-09-16T22:02:55Z
[ "python", "django", "frameworks" ]
I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools? Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However it's written in Python which means there's little real support in the way of deployment/packaging, debugging, profilers and other tools that make building and maintaining applications much easier. Ruby has similar issues and although I do like Ruby **much** better than I like Python, I get the impression that Rails is roughly in the same boat at Django when it comes to managing/supporting the app. Has anyone here tried both Django and Grails (or other web frameworks) for non-trivial projects? How did they compare?
> However it's written in Python which > means there's little real support in > the way of deployment/packaging, > debugging, profilers and other tools > that make building and maintaining > applications much easier. Python has: 1. a [great interactive debugger](http://docs.python.org/lib/module-pdb.html), which makes very good use of Python [REPL](http://en.wikipedia.org/wiki/REPL). 2. [easy\_install](http://peak.telecommunity.com/DevCenter/EasyInstall) anv [virtualenv](http://pypi.python.org/pypi/virtualenv) for dependency management, packaging and deployment. 3. [profiling features](http://docs.python.org/lib/profile.html) comparable to other languages So IMHO you shouldn't worry about this things, use Python and Django and live happily :-) Lucky for you, newest version of [Django runs on Jython](http://blog.leosoto.com/2008/08/django-on-jython-its-here.html), so you don't need to leave your whole Java ecosystem behind. Speaking of frameworks, I evaluated this year: 1. [Pylons](http://pylonshq.com/) (Python) 2. [webpy](http://webpy.org/) (Python) 3. [Symfony](http://www.symfony-project.org/) (PHP) 4. [CakePHP](http://www.cakephp.org/) (PHP) None of this frameworks comes close to the power of Django or Ruby on Rails. Based on my collegue opinion I could recommend you [kohana](http://www.kohanaphp.com/home) framework. The downside is, it's written in PHP and, as far as I know, PHP doesn't have superb tools for debugging, profiling and packaging of apps. **Edit:** Here is a very good [article about packaging and deployment of Python apps](http://bud.ca/blog/pony) (specifically Django apps). It's a hot topic in Django community now.
Django -vs- Grails -vs-?
75,798
16
2008-09-16T19:05:48Z
460,360
9
2009-01-20T07:32:41Z
[ "python", "django", "frameworks" ]
I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools? Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However it's written in Python which means there's little real support in the way of deployment/packaging, debugging, profilers and other tools that make building and maintaining applications much easier. Ruby has similar issues and although I do like Ruby **much** better than I like Python, I get the impression that Rails is roughly in the same boat at Django when it comes to managing/supporting the app. Has anyone here tried both Django and Grails (or other web frameworks) for non-trivial projects? How did they compare?
Grails. Grails just looks like Rails (Ruby),but it uses groovy which is simpler than java. It uses java technology and you can use any java lib without any trouble. I also choose Grails over simplicity and there are lots of java lib (such as jasper report, jawr etc) and I am glad that now they join with SpringSource which makes their base solid.
Django -vs- Grails -vs-?
75,798
16
2008-09-16T19:05:48Z
1,955,727
26
2009-12-23T22:42:54Z
[ "python", "django", "frameworks" ]
I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools? Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However it's written in Python which means there's little real support in the way of deployment/packaging, debugging, profilers and other tools that make building and maintaining applications much easier. Ruby has similar issues and although I do like Ruby **much** better than I like Python, I get the impression that Rails is roughly in the same boat at Django when it comes to managing/supporting the app. Has anyone here tried both Django and Grails (or other web frameworks) for non-trivial projects? How did they compare?
You asked for someone who used both Grails and Django. I've done work on both for big projects. Here's my Thoughts: **IDE's:** Django works really well in Eclipse, Grails works really well in IntelliJ Idea. **Debugging:** Practically the same (assuming you use IntelliJ for Grails, and Eclipse for Python). Step debugging, inspecting variables, etc... never need a print statement for either. Sometimes django error messages can be useless but Grails error messages are usually pretty lengthy and hard to parse through. **Time to run a unit test:** django: 2 seconds. Grails: 20 seconds (the tests themselves both run in a fraction of a second, it's the part about loading the framework to run them that takes the rest... as you can see, Grails is frustratingly slow to load). **Deployment:** Django: copy & paste one file into an apache config, and to redeploy, just change the code and reload apache. Grails: create a .war file, deploy it on tomcat, rinse and repeat to redeploy. **Programming languages:** Groovy is TOTALLY awesome. I love it, more so than Python. But I certainly have no complaints. **Plugins:** Grails: lots of broken plugins (and can use every java lib ever). Django: a few stable plugins, but enough to do most of what you need. **Database:** Django: schema migrations using South, and generally intuitive relations. Grails: no schema migrations, and by default it deletes the database on startup... WTF **Usage:** Django: startups (especially in the Gov 2.0 space), independent web dev shops. Grails: enterprise Hope that helps!
Django -vs- Grails -vs-?
75,798
16
2008-09-16T19:05:48Z
1,997,668
7
2010-01-04T05:37:55Z
[ "python", "django", "frameworks" ]
I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools? Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However it's written in Python which means there's little real support in the way of deployment/packaging, debugging, profilers and other tools that make building and maintaining applications much easier. Ruby has similar issues and although I do like Ruby **much** better than I like Python, I get the impression that Rails is roughly in the same boat at Django when it comes to managing/supporting the app. Has anyone here tried both Django and Grails (or other web frameworks) for non-trivial projects? How did they compare?
The statement that *grails deletes the database on start-up* is completely wrong. It's behavior on start-up is completely configurable and easy to configure. I generally use create-drop when running an app in dev mode. I use update when I run in test and production. I also love the bootstrap processing that lets me pre-configure test users, data, etc by environment in Grails. I'd love to see someone who has really built and deployed some commercial projects comment on the pros / cons. Be a really interesting read.
Best way to access table instances when using SQLAlchemy's declarative syntax
75,829
5
2008-09-16T19:08:29Z
156,968
7
2008-10-01T10:14:09Z
[ "python", "sql", "sqlalchemy" ]
All the docs for SQLAlchemy give `INSERT` and `UPDATE` examples using the local table instance (e.g. `tablename.update()`... ) Doing this seems difficult with the declarative syntax, I need to reference `Base.metadata.tables["tablename"]` to get the table reference. Am I supposed to do this another way? Is there a different syntax for `INSERT` and `UPDATE` recommended when using the declarative syntax? Should I just switch to the old way?
well it works for me: ``` class Users(Base): __tablename__ = 'users' __table_args__ = {'autoload':True} users = Users() print users.__table__.select() ``` ...SELECT users.......
Which is faster, python webpages or php webpages?
77,086
27
2008-09-16T21:05:26Z
77,297
27
2008-09-16T21:24:46Z
[ "php", "python", "performance", "pylons" ]
Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time. I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.
There's no point in attempting to convince your employer to port from PHP to Python, especially not for an existing system, which is what I think you implied in your question. The reason for this is that you already have a (presumably) working system, with an existing investment of time and effort (and experience). To discard this in favour of a trivial performance gain (not that I'm claiming there would be one) would be foolish, and no manager worth his salt ought to endorse it. It may also create a problem with maintainability, depending on who else has to work with the system, and their experience with Python.
Which is faster, python webpages or php webpages?
77,086
27
2008-09-16T21:05:26Z
79,744
81
2008-09-17T03:44:12Z
[ "php", "python", "performance", "pylons" ]
Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time. I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.
It sounds like you don't want to compare the two **languages**, but that you want to compare two **web systems**. This is tricky, because there are many variables involved. For example, Python web applications can take advantage of [mod\_wsgi](http://code.google.com/p/modwsgi/) to talk to web servers, which is faster than any of the typical ways that PHP talks to web servers (even mod\_php ends up being slower if you're using Apache, because Apache can only use the Prefork MPM with mod\_php rather than multi-threaded MPM like Worker). There is also the issue of code compilation. As you know, Python is compiled just-in-time to byte code (.pyc files) when a file is run each time the file changes. Therefore, after the first run of a Python file, the compilation step is skipped and the Python interpreter simply fetches the precompiled .pyc file. Because of this, one could argue that Python has a native advantage over PHP. However, optimizers and caching systems can be installed for PHP websites (my favorite is [eAccelerator](http://eaccelerator.net/)) to much the same effect. In general, enough tools exist such that one can pretty much do everything that the other can do. Of course, as others have mentioned, there's more than just speed involved in the business case to switch languages. We have an app written in oCaml at my current employer, which turned out to be a mistake because the original author left the company and nobody else wants to touch it. Similarly, the PHP-web community is much larger than the Python-web community; Website hosting services are more likely to offer PHP support than Python support; etc. But back to speed. You must recognize that the question of speed here involves many moving parts. Fortunately, many of these parts can be independently optimized, affording you various avenues to seek performance gains.
'id' is a bad variable name in Python
77,552
73
2008-09-16T21:50:58Z
77,612
87
2008-09-16T21:55:59Z
[ "python" ]
Why is it bad to name a variable `id` in Python?
`id()` is a fundamental built-in: > Help on built-in function `id` in module > `__builtin__`: > > ``` > id(...) > > id(object) -> integer > > Return the identity of an object. This is guaranteed to be unique among > simultaneously existing objects. (Hint: it's the object's memory > address.) > ``` In general, using variable names that eclipse a keyword or built-in function in any language is a bad idea, even if it is allowed.
'id' is a bad variable name in Python
77,552
73
2008-09-16T21:50:58Z
77,925
30
2008-09-16T22:27:26Z
[ "python" ]
Why is it bad to name a variable `id` in Python?
I might say something unpopular here: `id()` is a rather specialized built-in function that is rarely used in business logic. Therefore I don't see a problem in using it as a variable name in a tight and well-written function, where it's clear that id doesn't mean the built-in function.
'id' is a bad variable name in Python
77,552
73
2008-09-16T21:50:58Z
79,198
38
2008-09-17T02:13:34Z
[ "python" ]
Why is it bad to name a variable `id` in Python?
`id` is a built-in function that gives the memory address of an object. If you name one of your functions `id`, you will have to say `__builtins__.id` to get the original. Renaming `id` globally is confusing in anything but a small script. However, reusing built-in names as variables isn't all that bad as long as the use is local. Python has a *lot* of built-in functions that (1) have common names and (2) you will not use much anyway. Using these as local variables or as members of an object is OK because it's obvious from context what you're doing: Example: ``` def numbered(filename): file = open(filename) for i,input in enumerate(file): print "%s:\t%s" % (i,input) file.close() ``` Some built-ins with tempting names: * `id` * `file` * `list` * `map` * `all`, `any` * `complex` * `dir` * `input` * `slice` * `buffer`
'id' is a bad variable name in Python
77,552
73
2008-09-16T21:50:58Z
28,091,085
17
2015-01-22T14:24:12Z
[ "python" ]
Why is it bad to name a variable `id` in Python?
In **PEP 8 - Style Guide for Python Code**, the following guidance appears in the section [Descriptive: Naming Styles](https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles) : > * `single_trailing_underscore_` : used by convention to avoid conflicts > with Python keyword, e.g. > > `Tkinter.Toplevel(master, class_='ClassName')` So, to answer the question, an example that applies this guideline is: ``` id_ = 42 ``` Including the trailing underscore in the variable name makes the intent clear (to those familiar with the guidance in PEP 8).
iBATIS for Python?
77,731
4
2008-09-16T22:05:58Z
78,147
10
2008-09-16T22:53:33Z
[ "python", "orm", "ibatis" ]
At my current gig, we use iBATIS through Java to CRUD our databases. I like the abstract qualities of the tool, especially when working with legacy databases, as it doesn't impose its own syntax on you. **I'm looking for a Python analogue to this library**, since the website only has Java/.NET/Ruby versions available. I don't want to have to switch to Jython if I don't need to. Are there any other projects similar to iBATIS functionality out there for Python?
iBatis sequesters the SQL DML (or the definitions of the SQL) in an XML file. It specifically focuses on the mapping between the SQL and some object model defined elsewhere. SQL Alchemy can do this -- but it isn't really a very complete solution. Like iBatis, you can merely have SQL table definitions and a mapping between the tables and Python class definitions. What's more complete is to have a class definition that is *also* the SQL database definition. If the class definition generates the SQL Table DDL as well as the query and processing DML, that's much more complete. I flip-flop between SQLAlchemy and the Django ORM. SQLAlchemy can be used in an iBatis like manner. But I prefer to make the object design central and leave the SQL implementation be derived from the objects by the toolset. I use SQLAlchemy for large, batch, stand-alone projects. DB Loads, schema conversions, DW reporting and the like work out well. In these projects, the focus is on the relational view of the data, not the object model. The SQL that's generated may be moved into PL/SQL stored procedures, for example. I use Django for web applications, exploiting its built-in ORM capabilities. You can, with a little work, segregate the Django ORM from the rest of the Django environment. You can [provide global settings](http://docs.djangoproject.com/en/dev/topics/settings/#using-settings-without-setting-django-settings-module) to bind your app to a specific database without using a separate settings module. Django includes a number of common relationships (Foreign Key, Many-to-Many, One-to-One) for which it can manage the SQL implementation. It generates key and index definitions for the attached database. If your problem is largely object-oriented, with the database being used for persistence, then the nearly transparent ORM layer of Django has advantages. If your problem is largely relational, with the SQL processing central, then the capability of seeing the generated SQL in SQLAlchemy has advantages.
What's the best way to calculate a 3D (or n-D) centroid?
77,936
10
2008-09-16T22:28:58Z
77,978
12
2008-09-16T22:33:06Z
[ "python", "math", "3d", "geometry" ]
As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in: ``` centroid = average(x), average(y), average(z) ``` where `x`, `y` and `z` are arrays of floating-point numbers. I seem to recall that there is a way to get a more accurate centroid, but I haven't found a simple algorithm for doing so. Anyone have any ideas or suggestions? I'm using Python for this, but I can adapt examples from other languages.
Nope, that is the only formula for the centroid of a collection of points. See Wikipedia: <http://en.wikipedia.org/wiki/Centroid>
What's the best way to calculate a 3D (or n-D) centroid?
77,936
10
2008-09-16T22:28:58Z
88,394
10
2008-09-17T22:35:44Z
[ "python", "math", "3d", "geometry" ]
As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in: ``` centroid = average(x), average(y), average(z) ``` where `x`, `y` and `z` are arrays of floating-point numbers. I seem to recall that there is a way to get a more accurate centroid, but I haven't found a simple algorithm for doing so. Anyone have any ideas or suggestions? I'm using Python for this, but I can adapt examples from other languages.
You vaguely mention "a way to get a more accurate centroid". Maybe you're talking about a centroid that isn't affected by outliers. For example, the *average* household income in the USA is probably very high, because a small number of *very* rich people skew the average; they are the "outliers". For that reason, statisticians use the *median* instead. One way to obtain the median is to sort the values, then pick the value halfway down the list. Maybe you're looking for something like this, but for 2D or 3D points. The problem is, in 2D and higher, you can't sort. There's no natural order. Nevertheless, there are ways to get rid of outliers. One way is to find the [convex hull](http://en.wikipedia.org/wiki/Convex_hull) of the points. The convex hull has all the points on the "outside" of the set of points. If you do this, and throw out the points that are on the hull, you'll be throwing out the outliers, and the points that remain will give a more "representative" centroid. You can even repeat this process several times, and the result is kind like peeling an onion. In fact, it's called "convex hull peeling".
Redirect command to input of another in Python
78,431
5
2008-09-16T23:46:47Z
78,482
8
2008-09-16T23:57:32Z
[ "python", "bash", "redirect", "diff", "vimdiff" ]
I would like to replicate this in python: ``` gvimdiff <(hg cat file.txt) file.txt ``` (hg cat file.txt outputs the most recently committed version of file.txt) I know how to pipe the file to gvimdiff, but it won't accept another file: ``` $ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" ``` Getting to the python part... ``` # hgdiff.py import subprocess import sys file = sys.argv[1] subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file]) ``` When subprocess is called it merely passes `<(hg cat file)` onto `gvimdiff` as a filename. So, is there any way to redirect a command as bash does? For simplicity's sake just cat a file and redirect it to diff: ``` diff <(cat file.txt) file.txt ```
It can be done. As of Python 2.5, however, this mechanism is Linux-specific and not portable: ``` import subprocess import sys file = sys.argv[1] p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE) p2 = subprocess.Popen([ 'gvimdiff', '/proc/self/fd/%s' % p1.stdout.fileno(), file]) p2.wait() ``` That said, in the specific case of diff, you can simply take one of the files from stdin, and remove the need to use the bash-alike functionality in question: ``` file = sys.argv[1] p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE) p2 = subprocess.Popen(['diff', '-', file], stdin=p1.stdout) diff_text = p2.communicate()[0] ```
Is there a benefit to defining a class inside another class in Python?
78,799
54
2008-09-17T01:02:31Z
78,858
72
2008-09-17T01:12:59Z
[ "python", "oop" ]
What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right? I have code that looks something like this: ``` class DownloadThread: def foo(self): pass class DownloadManager(): def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadThread()) ``` But now I'm wondering if there's a situation where nesting would be better. Something like: ``` class DownloadManager(): class DownloadThread: def foo(self): pass def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadManager.DownloadThread()) ```
You might want to do this when the "inner" class is a one-off, which will never be used outside the *definition* of the outer class. For example to use a metaclass, it's sometimes handy to do ``` class Foo(object): class __metaclass__(type): .... ``` instead of defining a metaclass separately, if you're only using it once. The only other time I've used nested classes like that, I used the outer class only as a namespace to group a bunch of closely related classes together: ``` class Group(object): class cls1(object): ... class cls2(object): ... ``` Then from another module, you can import Group and refer to these as Group.cls1, Group.cls2 etc. However one might argue that you can accomplish exactly the same (perhaps in a less confusing way) by using a module.
Is there a benefit to defining a class inside another class in Python?
78,799
54
2008-09-17T01:02:31Z
78,868
14
2008-09-17T01:14:33Z
[ "python", "oop" ]
What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right? I have code that looks something like this: ``` class DownloadThread: def foo(self): pass class DownloadManager(): def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadThread()) ``` But now I'm wondering if there's a situation where nesting would be better. Something like: ``` class DownloadManager(): class DownloadThread: def foo(self): pass def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadManager.DownloadThread()) ```
I don't know Python, but your question seems very general. Ignore me if it's specific to Python. Class nesting is all about scope. If you think that one class will only make sense in the context of another one, then the former is probably a good candidate to become a nested class. It is a common pattern make helper classes as private, nested classes.
Testing GUI code: should I use a mocking library?
79,454
5
2008-09-17T02:52:58Z
80,028
7
2008-09-17T04:33:46Z
[ "python", "unit-testing", "user-interface", "tdd" ]
Recently I've been experimenting with TDD while developing a GUI application in Python. I find it very reassuring to have tests that verify the functionality of my code, but it's been tricky to follow some of the recommened practices of TDD. Namely, writing tests first has been hard. And I'm finding it difficult to make my tests readable (due to extensive use of a mocking library). I chose a mocking library called [mocker](http://labix.org/mocker). I use it a lot since much of the code I'm testing makes calls to (a) other methods in my application that depend on system state or (b) ObjC/Cocoa objects that cannot exist without an event loop, etc. Anyway, I've got a lot of tests that look like this: ``` def test_current_window_controller(): def test(config): ac = AppController() m = Mocker() ac.iter_window_controllers = iwc = m.replace(ac.iter_window_controllers) expect(iwc()).result(iter(config)) with m: result = ac.current_window_controller() assert result == (config[0] if config else None) yield test, [] yield test, [0] yield test, [1, 0] ``` Notice that this is actually three tests; all use the same parameterized test function. Here's the code that is being tested: ``` def current_window_controller(self): try: # iter_window_controllers() iterates in z-order starting # with the controller of the top-most window # assumption: the top-most window is the "current" one wc = self.iter_window_controllers().next() except StopIteration: return None return wc ``` One of the things I've noticed with using mocker is that it's easier to write the application code first and then go back and write the tests second, since most of the time I'm mocking many method calls and the syntax to write the mocked calls is much more verbose (thus harder to write) than the application code. It's easier to write the app code and then model the test code off of that. I find that with this testing method (and a bit of discipline) I can easily write code with 100% test coverage. I'm wondering if these tests are good tests? Will I regret doing it this way down the road when I finally discover the secret to writing good tests? Am I violating the core principles of TDD so much that my testing is in vain?
**If you are writing your tests after you've written your code and making them pass, you are not doing TDD** (nor are you getting any benefits of Test-First or Test-Driven development.. check out SO questions for definitive books on TDD) > One of the things I've noticed with > using mocker is that it's easier to > write the application code first and > then go back and write the tests > second, since most of the time I'm > mocking many method calls and the > syntax to write the mocked calls is > much more verbose (thus harder to > write) than the application code. It's > easier to write the app code and then > model the test code off of that. Of course, its easier because you are just testing that the sky is orange after you made it orange by painting it with a specific kind of brush. This is retrofitting tests (for self-assurance). Mocks are good but you should know how and when to use them - Like the saying goes 'When you have a hammer everything looks like a nail' It's also easy to write a whole load of unreadable and not-as-helpful-as-can-be tests. The time spent understanding what the test is about is time lost that can be used to fix broken ones. And the point is: * Read [Mocks aren't stubs - Martin Fowler](http://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting) if you haven't already. Google out some documented instances of good [ModelViewPresenter](http://martinfowler.com/eaaDev/ModelViewPresenter.html) patterned GUIs (Fake/Mock out the UIs if necessary). * Study your options and choose wisely. I'll play the guy with the halo on your left shoulder in white saying 'Don't do it.' Read this question as to [my reasons](http://stackoverflow.com/questions/59195/how-are-mocks-meant-to-be-used) - St. Justin is on your right shoulder. I believe he has also something to say:)
Unittest causing sys.exit()
79,754
11
2008-09-17T03:46:55Z
79,826
10
2008-09-17T03:58:24Z
[ "python", "unit-testing" ]
No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on. ``` IDLE 1.2.2 ==== No Subprocess ==== >>> import unittest >>> >>> class Test(unittest.TestCase): def testA(self): a = 1 self.assertEqual(a,1) >>> unittest.main() option -n not recognized Usage: idle.pyw [options] [test] [...] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output Examples: idle.pyw - run default set of tests idle.pyw MyTestSuite - run suite 'MyTestSuite' idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething idle.pyw MyTestCase - run all 'test*' test methods in MyTestCase Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> unittest.main() File "E:\Python25\lib\unittest.py", line 767, in __init__ self.parseArgs(argv) File "E:\Python25\lib\unittest.py", line 796, in parseArgs self.usageExit(msg) File "E:\Python25\lib\unittest.py", line 773, in usageExit sys.exit(2) SystemExit: 2 >>> ```
Don't try to run `unittest.main()` from IDLE. It's trying to access `sys.argv`, and it's getting the args that IDLE was started with. Either run your tests in a different way from IDLE, or call `unittest.main()` in its own Python process.
Unittest causing sys.exit()
79,754
11
2008-09-17T03:46:55Z
79,833
10
2008-09-17T03:59:27Z
[ "python", "unit-testing" ]
No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on. ``` IDLE 1.2.2 ==== No Subprocess ==== >>> import unittest >>> >>> class Test(unittest.TestCase): def testA(self): a = 1 self.assertEqual(a,1) >>> unittest.main() option -n not recognized Usage: idle.pyw [options] [test] [...] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output Examples: idle.pyw - run default set of tests idle.pyw MyTestSuite - run suite 'MyTestSuite' idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething idle.pyw MyTestCase - run all 'test*' test methods in MyTestCase Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> unittest.main() File "E:\Python25\lib\unittest.py", line 767, in __init__ self.parseArgs(argv) File "E:\Python25\lib\unittest.py", line 796, in parseArgs self.usageExit(msg) File "E:\Python25\lib\unittest.py", line 773, in usageExit sys.exit(2) SystemExit: 2 >>> ```
Your example is exiting on my install too. I can make it execute the tests and stay within Python by changing ``` unittest.main() ``` to ``` unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test)) ``` More information is available [here](http://docs.python.org/library/unittest.html#basic-example) in the Python Library Reference.
Unittest causing sys.exit()
79,754
11
2008-09-17T03:46:55Z
3,215,505
17
2010-07-09T18:30:28Z
[ "python", "unit-testing" ]
No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on. ``` IDLE 1.2.2 ==== No Subprocess ==== >>> import unittest >>> >>> class Test(unittest.TestCase): def testA(self): a = 1 self.assertEqual(a,1) >>> unittest.main() option -n not recognized Usage: idle.pyw [options] [test] [...] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output Examples: idle.pyw - run default set of tests idle.pyw MyTestSuite - run suite 'MyTestSuite' idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething idle.pyw MyTestCase - run all 'test*' test methods in MyTestCase Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> unittest.main() File "E:\Python25\lib\unittest.py", line 767, in __init__ self.parseArgs(argv) File "E:\Python25\lib\unittest.py", line 796, in parseArgs self.usageExit(msg) File "E:\Python25\lib\unittest.py", line 773, in usageExit sys.exit(2) SystemExit: 2 >>> ```
In new Python 2.7 release, [unittest.main()](http://docs.python.org/library/unittest.html#unittest.main) has a new argument. If 'exit' is set to `False`, `sys.exit()` is not called during the execution of `unittest.main()`.
How do I convert local time to UTC in Python?
79,797
147
2008-09-17T03:52:42Z
79,808
20
2008-09-17T03:54:39Z
[ "python", "datetime", "utc" ]
How do I convert a datetime *string in local time* to a *string in UTC time*? I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future. **Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with the equivalent `UTC` time: `2008-09-17 04:02:00`. Also, from <http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.
``` def local_to_utc(t): secs = time.mktime(t) return time.gmtime(secs) def utc_to_local(t): secs = calendar.timegm(t) return time.localtime(secs) ``` Source: <http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html> Example usage from [bd808](http://stackoverflow.com/users/8171/bd808): If your source is a `datetime.datetime` object `t`, call as: ``` local_to_utc(t.timetuple()) ```
How do I convert local time to UTC in Python?
79,797
147
2008-09-17T03:52:42Z
79,877
137
2008-09-17T04:07:28Z
[ "python", "datetime", "utc" ]
How do I convert a datetime *string in local time* to a *string in UTC time*? I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future. **Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with the equivalent `UTC` time: `2008-09-17 04:02:00`. Also, from <http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.
First, parse the string into a naive datetime object. This is an instance of `datetime.datetime` with no attached timezone information. See documentation for `datetime.strptime` for information on parsing the date string. Use the [`pytz`](http://pytz.sourceforge.net/) module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime. Finally, use `datetime.astimezone()` method to convert the datetime to UTC. Source code, using local timezone "America/Los\_Angeles", for the string "2001-2-3 10:11:12": ``` import pytz, datetime local = pytz.timezone ("America/Los_Angeles") naive = datetime.datetime.strptime ("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S") local_dt = local.localize(naive, is_dst=None) utc_dt = local_dt.astimezone (pytz.utc) ``` From there, you can use the `strftime()` method to format the UTC datetime as needed: ``` utc_dt.strftime ("%Y-%m-%d %H:%M:%S") ```
How do I convert local time to UTC in Python?
79,797
147
2008-09-17T03:52:42Z
79,913
51
2008-09-17T04:15:39Z
[ "python", "datetime", "utc" ]
How do I convert a datetime *string in local time* to a *string in UTC time*? I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future. **Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with the equivalent `UTC` time: `2008-09-17 04:02:00`. Also, from <http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.
Thanks @rofly, the full conversion from string to string is as follows: ``` time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")))) ``` My summary of the `time`/`calendar` functions: `time.strptime` string --> tuple (no timezone applied, so matches string) `time.mktime` local time tuple --> seconds since epoch (always local time) `time.gmtime` seconds since epoch --> tuple in UTC and `calendar.timegm` tuple in UTC --> seconds since epoch `time.localtime` seconds since epoch --> tuple in local timezone
How do I convert local time to UTC in Python?
79,797
147
2008-09-17T03:52:42Z
2,175,170
60
2010-02-01T07:00:27Z
[ "python", "datetime", "utc" ]
How do I convert a datetime *string in local time* to a *string in UTC time*? I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future. **Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with the equivalent `UTC` time: `2008-09-17 04:02:00`. Also, from <http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.
The datetime module's [utcnow()](http://docs.python.org/library/datetime.html#datetime.datetime.utcnow) function can be used to obtain the current UTC time. ``` >>> import datetime >>> utc_datetime = datetime.datetime.utcnow() >>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S") '2010-02-01 06:59:19' ``` As the link mentioned above by Tom: <http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/> says: > UTC is a timezone without daylight saving time and still a timezone > without configuration changes in the past. > > *Always measure and store time in UTC*. > > If you need to record where the time was taken, store that separately. > ***Do not*** store the local time + timezone information! **NOTE** - If any of your data is in a region that uses DST, use `pytz` and take a look at John Millikin's answer. If you want to obtain the UTC time from a given string and your lucky enough to be in a region in the world that either doesn't use DST, or you have data that is only offset from UTC without DST applied: --> using local time as the basis for the offset value: ``` >>> # Obtain the UTC Offset for the current system: >>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now() >>> local_datetime = datetime.datetime.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S") >>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA >>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S") '2008-09-17 04:04:00' ``` --> Or, from a known offset, using datetime.timedelta(): ``` >>> UTC_OFFSET = 10 >>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET) >>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S") '2008-09-17 04:04:00' ```
How do I convert local time to UTC in Python?
79,797
147
2008-09-17T03:52:42Z
8,563,126
11
2011-12-19T14:58:01Z
[ "python", "datetime", "utc" ]
How do I convert a datetime *string in local time* to a *string in UTC time*? I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future. **Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with the equivalent `UTC` time: `2008-09-17 04:02:00`. Also, from <http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.
I'm having good luck with [dateutil](http://labix.org/python-dateutil) (which is widely recommended on SO for other related questions): ``` from datetime import * from dateutil import * from dateutil.tz import * # METHOD 1: Hardcode zones: utc_zone = tz.gettz('UTC') local_zone = tz.gettz('America/Chicago') # METHOD 2: Auto-detect zones: utc_zone = tz.tzutc() local_zone = tz.tzlocal() # Convert time string to datetime local_time = datetime.strptime("2008-09-17 14:02:00", '%Y-%m-%d %H:%M:%S') # Tell the datetime object that it's in local time zone since # datetime objects are 'naive' by default local_time = local_time.replace(tzinfo=local_zone) # Convert time to UTC utc_time = local_time.astimezone(utc_zone) # Generate UTC time string utc_string = utc_time.strftime('%Y-%m-%d %H:%M:%S') ``` (Code was derived from this answer to [Convert UTC datetime string to local datetime](http://stackoverflow.com/a/4771733/165673))
How do I convert local time to UTC in Python?
79,797
147
2008-09-17T03:52:42Z
10,040,725
14
2012-04-06T07:54:41Z
[ "python", "datetime", "utc" ]
How do I convert a datetime *string in local time* to a *string in UTC time*? I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future. **Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with the equivalent `UTC` time: `2008-09-17 04:02:00`. Also, from <http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.
One more example with pytz, but includes localize(), which saved my day. ``` import pytz, datetime utc = pytz.utc fmt = '%Y-%m-%d %H:%M:%S' amsterdam = pytz.timezone('Europe/Amsterdam') dt = datetime.datetime.strptime("2012-04-06 10:00:00", fmt) am_dt = amsterdam.localize(dt) print am_dt.astimezone(utc).strftime(fmt) '2012-04-06 08:00:00' ```
How do I convert local time to UTC in Python?
79,797
147
2008-09-17T03:52:42Z
13,084,428
9
2012-10-26T09:38:42Z
[ "python", "datetime", "utc" ]
How do I convert a datetime *string in local time* to a *string in UTC time*? I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future. **Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with the equivalent `UTC` time: `2008-09-17 04:02:00`. Also, from <http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.
Here's a summary of common Python time conversions * struct\_time (UTC) → POSIX: `calendar.timegm(struct_time)` * Naïve datetime (local) → POSIX: `calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())` * Naïve datetime (UTC) → POSIX: `calendar.timegm(dt.utctimetuple())` * Aware datetime → POSIX: `calendar.timegm(dt.utctimetuple())` * POSIX → struct\_time (UTC): `time.gmtime(t)` * Naïve datetime (local) → struct\_time (UTC): `stz.localize(dt, is_dst=None).utctimetuple()` * Naïve datetime (UTC) → struct\_time (UTC): `dt.utctimetuple()` * Aware datetime → struct\_time (UTC): `dt.utctimetuple()` * POSIX → Naïve datetime (local): `datetime.fromtimestamp(t, None)` * struct\_time (UTC) → Naïve datetime (local): `datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)` * Naïve datetime (UTC) → Naïve datetime (local): `dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)` * Aware datetime → Naïve datetime (local): `dt.astimezone(tz).replace(tzinfo=None)` * POSIX → Naïve datetime (UTC): `datetime.utcfromtimestamp(t)` * struct\_time (UTC) → Naïve datetime (UTC): `datetime.datetime(struct_time[:6])` * Naïve datetime (local) → Naïve datetime (UTC): `stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)` * Aware datetime → Naïve datetime (UTC): `dt.astimezone(UTC).replace(tzinfo=None)` * POSIX → Aware datetime: `datetime.fromtimestamp(t, tz)` * struct\_time (UTC) → Aware datetime: `datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)` * Naïve datetime (local) → Aware datetime: `stz.localize(dt, is_dst=None)` * Naïve datetime (UTC) → Aware datetime: `dt.replace(tzinfo=UTC)` Source: [taaviburns.ca](http://taaviburns.ca/presentations/what_you_need_to_know_about_datetimes/)
How do you design data models for Bigtable/Datastore (GAE)?
79,850
17
2008-09-17T04:02:53Z
80,425
18
2008-09-17T06:02:38Z
[ "python", "database", "google-app-engine", "bigtable" ]
Since the Google App Engine Datastore is based on [Bigtable](http://research.google.com/archive/bigtable.html) and we know that's not a relational database, how do you design a ***database schema*/\*data model\*** for applications that use this type of database system?
Designing a bigtable schema is an open process, and basically requires you to think about: * The access patterns you will be using and how often each will be used * The relationships between your types * What indices you are going to need * The write patterns you will be using (in order to effectively spread load) GAE's datastore automatically denormalizes your data. That is, each index contains a (mostly) complete copy of the data, and thus every index adds significantly to time taken to perform a write, and the storage space used. If this were not the case, designing a Datastore schema would be a lot more work: You would have to think carefully about the primary key for each type, and consider the effect of your decision on the locality of data. For example, when rendering a blog post you would probably need to display the comments to go along with it, so each comment's key would probably begin with the associated post's key. With Datastore, this is not such a big deal: The query you use will look something like "Select \* FROM Comment WHERE post\_id = N." (If you want to page the comments, you would also have a limit clause, and a possible suffix of " AND comment\_id > last\_comment\_id".) Once you add such a query, Datastore will build the index for you, and your reads will be magically fast. Something to keep in mind is that each additional index creates some additional cost: it is best if you can use as few access patterns as possible, since it will reduce the number of indices GAE will construct, and thus the total storage required by your data. Reading over this answer, I find it a little vague. Maybe a hands-on design question would help to scope this down? :-)
Split a string by spaces -- preserving quoted substrings -- in Python
79,968
163
2008-09-17T04:25:15Z
79,985
253
2008-09-17T04:27:32Z
[ "python", "regex" ]
I have a string which is like this: ``` this is "a test" ``` I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is: ``` ['this','is','a test'] ``` PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.
You want split, from the [shlex](https://docs.python.org/2/library/shlex.html) module. ``` >>> import shlex >>> shlex.split('this is "a test"') ['this', 'is', 'a test'] ``` This should do exactly what you want.
Split a string by spaces -- preserving quoted substrings -- in Python
79,968
163
2008-09-17T04:25:15Z
79,989
45
2008-09-17T04:27:59Z
[ "python", "regex" ]
I have a string which is like this: ``` this is "a test" ``` I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is: ``` ['this','is','a test'] ``` PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.
Have a look at the `shlex` module, particularly `shlex.split`. > `>>> import shlex` > > `>>> shlex.split('This is "a test"')` > > `['This', 'is', 'a test']`
Split a string by spaces -- preserving quoted substrings -- in Python
79,968
163
2008-09-17T04:25:15Z
80,449
8
2008-09-17T06:08:38Z
[ "python", "regex" ]
I have a string which is like this: ``` this is "a test" ``` I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is: ``` ['this','is','a test'] ``` PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.
Since this question is tagged with regex, I decided to try a regex approach. I first replace all the spaces in the quotes parts with \x00, then split by spaces, then replace the \x00 back to spaces in each part. Both versions do the same thing, but splitter is a bit more readable then splitter2. ``` import re s = 'this is "a test" some text "another test"' def splitter(s): def replacer(m): return m.group(0).replace(" ", "\x00") parts = re.sub('".+?"', replacer, s).split() parts = [p.replace("\x00", " ") for p in parts] return parts def splitter2(s): return [p.replace("\x00", " ") for p in re.sub('".+?"', lambda m: m.group(0).replace(" ", "\x00"), s).split()] print splitter2(s) ```
Split a string by spaces -- preserving quoted substrings -- in Python
79,968
163
2008-09-17T04:25:15Z
524,796
26
2009-02-07T23:17:26Z
[ "python", "regex" ]
I have a string which is like this: ``` this is "a test" ``` I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is: ``` ['this','is','a test'] ``` PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.
I see regex approaches here that look complex and/or wrong. This surprises me, because regex syntax can easily describe "whitespace or thing-surrounded-by-quotes", and most regex engines (including Python's) can split on a regex. So if you're going to use regexes, why not just say exactly what you mean?: ``` test = 'this is "a test"' # or "this is 'a test'" # pieces = [p for p in re.split("( |[\\\"'].*[\\\"'])", test) if p.strip()] # From comments, use this: pieces = [p for p in re.split("( |\\\".*?\\\"|'.*?')", test) if p.strip()] ``` Explanation: ``` [\\\"'] = double-quote or single-quote .* = anything ( |X) = space or X .strip() = remove space and empty-string separators ``` shlex probably provides more features, though.
Split a string by spaces -- preserving quoted substrings -- in Python
79,968
163
2008-09-17T04:25:15Z
525,011
17
2009-02-08T02:18:46Z
[ "python", "regex" ]
I have a string which is like this: ``` this is "a test" ``` I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is: ``` ['this','is','a test'] ``` PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.
Depending on your use case, you may also want to check out the csv module: ``` import csv lines = ['this is "a string"', 'and more "stuff"'] for row in csv.reader(lines, delimiter=" "): print row ``` Output: ``` ['this', 'is', 'a string'] ['and', 'more', 'stuff'] ```
Asychronous Programming in Python Twisted
80,617
29
2008-09-17T06:51:35Z
81,456
63
2008-09-17T09:29:45Z
[ "python", "asynchronous", "twisted" ]
I'm having trouble developing a reverse proxy in Twisted. It works, but it seems overly complex and convoluted. So much of it feels like voodoo... Are there any *simple, solid* examples of asynchronous program structure on the web or in books? A sort of best practices guide? When I complete my program I'd like to be able to still see the structure in some way, not be looking at a bowl of spaghetti.
Twisted contains a [large number of examples](http://twistedmatrix.com/projects/core/documentation/howto/index.html). One in particular, the ["evolution of Finger" tutorial](http://twistedmatrix.com/projects/core/documentation/howto/tutorial/intro.html), contains a thorough explanation of how an asynchronous program grows from a very small kernel up to a complex system with lots of moving parts. Another one that might be of interest to you is the tutorial about simply [writing servers](http://twistedmatrix.com/projects/core/documentation/howto/servers.html). The key thing to keep in mind about Twisted, or even other asynchronous networking libraries (such as [asyncore](http://www.python.org/doc/current/lib/module-asyncore.html), [MINA](http://mina.apache.org/), or [ACE](http://www.cs.wustl.edu/~schmidt/ACE-overview.html)), is that your code only gets invoked when something happens. The part that I've heard most often sound like "voodoo" is the management of callbacks: for example, `Deferred`. If you're used to writing code that runs in a straight line, and only calls functions which return immediately with results, the idea of waiting for something to call you back might be confusing. But there's nothing magical, no "voodoo" about callbacks. At the lowest level, the reactor is just sitting around and waiting for one of a small number of things to happen: 1. Data arrives on a connection (it will call `dataReceived` on a Protocol) 2. Time has passed (it will call a function registered with `callLater`). 3. A connection has been accepted (it will call `buildProtocol` on a factory registered with a `listenXXX` or `connectXXX` function). 4. A connection has been dropped (it will call `connectionLost` on the appropriate Protocol) Every asynchronous program starts by hooking up a few of these events and then kicking off the reactor to wait for them to happen. Of course, events that happen lead to more events that get hooked up or disconnected, and so your program goes on its merry way. Beyond that, there's nothing special about asynchronous program structure that are interesting or special; event handlers and callbacks are just objects, and your code is run in the usual way. Here's a simple "event-driven engine" that shows you just how simple this process is. ``` # Engine import time class SimplestReactor(object): def __init__(self): self.events = [] self.stopped = False def do(self, something): self.events.append(something) def run(self): while not self.stopped: time.sleep(0.1) if self.events: thisTurn = self.events.pop(0) thisTurn() def stop(self): self.stopped = True reactor = SimplestReactor() # Application def thing1(): print 'Doing thing 1' reactor.do(thing2) reactor.do(thing3) def thing2(): print 'Doing thing 2' def thing3(): print 'Doing thing 3: and stopping' reactor.stop() reactor.do(thing1) print 'Running' reactor.run() print 'Done!' ``` At the core of libraries like Twisted, the function in the main loop is not `sleep`, but an operating system call like `select()` or `poll()`, as exposed by a module like [the Python select module](http://docs.python.org/lib/module-select.html). I say "like" `select`, because this is an API that varies a lot between platforms, and almost every GUI toolkit has its own version. Twisted currently provides an abstract interface to 14 different variations on this theme. The common thing that such an API provides is provide a way to say "Here are a list of events that I'm waiting for. Go to sleep until one of them happens, then wake up and tell me which one of them it was."
Upload files in Google App Engine
81,451
73
2008-09-17T09:28:53Z
143,798
10
2008-09-27T15:20:58Z
[ "python", "google-app-engine" ]
I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through `db.TextProperty` and `db.BlobProperty`. I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.
There is a thread in Google Groups about it: [Uploading Files](http://groups.google.com/group/google-appengine/browse_thread/thread/f9d0f22d8de8c025/bba32165e308dd13?lnk=gst&q=uploading+files#bba32165e308dd13) With a lot of useful code, that discussion helped me very much in uploading files.
Upload files in Google App Engine
81,451
73
2008-09-17T09:28:53Z
173,918
48
2008-10-06T11:15:22Z
[ "python", "google-app-engine" ]
I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through `db.TextProperty` and `db.BlobProperty`. I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.
In fact, this question is answered in the App Egnine documentation. See an example on [Uploading User Images](http://code.google.com/appengine/docs/images/usingimages.html#Uploading). HTML code, inside <form></form>: ``` <input type="file" name="img"/> ``` Python code: ``` class Guestbook(webapp.RequestHandler): def post(self): greeting = Greeting() if users.get_current_user(): greeting.author = users.get_current_user() greeting.content = self.request.get("content") avatar = self.request.get("img") greeting.avatar = db.Blob(avatar) greeting.put() self.redirect('/') ```
Upload files in Google App Engine
81,451
73
2008-09-17T09:28:53Z
4,787,543
39
2011-01-24T21:46:46Z
[ "python", "google-app-engine" ]
I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through `db.TextProperty` and `db.BlobProperty`. I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.
Here is a complete, working file. I pulled the original from the Google site and modified it to make it slightly more real world. A few things to notice: 1. This code uses the [BlobStore API](http://code.google.com/appengine/docs/python/blobstore/) 2. The purpose of this line in the ServeHandler class is to "fix" the key so that it gets rid of any name mangling that may have occurred in the browser (I didn't observe any in Chrome) ``` blob_key = str(urllib.unquote(blob_key)) ``` 3. The "save\_as" clause at the end of this is important. It will make sure that the file name does not get mangled when it is sent to your browser. Get rid of it to observe what happens. ``` self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True) ``` Good Luck! ``` import os import urllib from google.appengine.ext import blobstore from google.appengine.ext import webapp from google.appengine.ext.webapp import blobstore_handlers from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app class MainHandler(webapp.RequestHandler): def get(self): upload_url = blobstore.create_upload_url('/upload') self.response.out.write('<html><body>') self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url) self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html>""") for b in blobstore.BlobInfo.all(): self.response.out.write('<li><a href="/serve/%s' % str(b.key()) + '">' + str(b.filename) + '</a>') class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): def post(self): upload_files = self.get_uploads('file') blob_info = upload_files[0] self.redirect('/') class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, blob_key): blob_key = str(urllib.unquote(blob_key)) if not blobstore.get(blob_key): self.error(404) else: self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True) def main(): application = webapp.WSGIApplication( [('/', MainHandler), ('/upload', UploadHandler), ('/serve/([^/]+)?', ServeHandler), ], debug=True) run_wsgi_app(application) if __name__ == '__main__': main() ```
Is there any list of blog engines, written in Django?
82,653
17
2008-09-17T12:37:48Z
82,739
20
2008-09-17T12:45:14Z
[ "python", "django" ]
Is there any list of blog engines, written in Django?
EDIT: Original link went dead so here's an updated link with extracts of the list sorted with the most recently updated source at the top. [Eleven Django blog engines you should know](http://blog.montylounge.com/2010/02/10/eleven-django-blog-engines-you-should-know/) by Monty Lounge Industries > * [Biblion](http://github.com/eldarion/biblion) > * [Django-article](http://bitbucket.org/codekoala/django-articles/) > * [Flother](http://github.com/flother/flother) > * [Basic-Blog](http://github.com/nathanborror/django-basic-apps) > * [Hello-Newman](http://github.com/gregnewman/hello-newman) > * [Banjo](http://getbanjo.com/download/) > * [djangotechblog](http://code.google.com/p/djangotechblog/) > * [Django-YABA](http://github.com/f4nt/django-yaba/) > * [Shifting Bits](http://github.com/paltman/shiftingbits/) (this is now just a [biblion](http://github.com/eldarion/biblion) blog) > * [Mighty Lemon](http://github.com/mightylemon/mightylemon) > * [Coltrane](http://code.google.com/p/coltrane-blog/)
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
82,836
211
2008-09-17T12:55:48Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
``` import os.path if os.path.isfile(filename): ```
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
82,841
85
2008-09-17T12:56:22Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
``` import os os.path.exists(filename) ```
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
82,846
964
2008-09-17T12:57:08Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
You have the [`os.path.exists`](https://docs.python.org/2/library/os.path.html#os.path.exists) function: ``` import os.path os.path.exists(file_path) ``` This returns `True` for both files and directories but you can additionally use `os.path.isfile` to test if it's a file specifically.
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
82,852
2,356
2008-09-17T12:57:51Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
You can also use [`os.path.isfile`](https://docs.python.org/2/library/os.path.html#os.path.isfile) > Return `True` if path is an existing regular file. This follows symbolic links, so both [islink()](https://docs.python.org/2/library/os.path.html#os.path.islink) and [isfile()](https://docs.python.org/2/library/os.path.html#os.path.isfile) can be true for the same path. ``` import os.path os.path.isfile(fname) ``` if you need to be sure it's a file. Starting with Python 3.4, the [`pathlib` module](https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file) offers an object-oriented approach: ``` from pathlib import Path my_file = Path("/path/to/file") if my_file.is_file(): # file exists ```
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
83,012
18
2008-09-17T13:13:31Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
Additionally, `os.access()`: ``` if os.access("myfile", os.R_OK): with open("myfile") as fp: return fp.read() ``` Being `R_OK`, `W_OK`, and `X_OK` the flags to test for permissions ([doc](https://docs.python.org/3/library/os.html#os.access)).
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
84,173
640
2008-09-17T15:01:14Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
Unlike [`isfile()`](http://docs.python.org/3.3/library/os.path.html?highlight=os.path#os.path.isfile), [`exists()`](http://docs.python.org/3.3/library/os.path.html?highlight=os.path#os.path.exists) will yield *True* for directories. So depending on if you want only plain files or also directories, you'll use `isfile()` or `exists()`. Here is a simple REPL output. ``` >>> print os.path.isfile("/etc/password.txt") True >>> print os.path.isfile("/etc") False >>> print os.path.isfile("/does/not/exist") False >>> print os.path.exists("/etc/password.txt") True >>> print os.path.exists("/etc") True >>> print os.path.exists("/does/not/exist") False ```
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
1,671,095
87
2009-11-04T00:48:06Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
Prefer the try statement. It's considered better style and avoids race conditions. Don't take my word for it. There's plenty of support for this theory. Here's a couple: * Style: Section "Handling unusual conditions" of <http://allendowney.com/sd/notes/notes11.txt> * [Avoiding Race Conditions](https://developer.apple.com/library/mac/#documentation/security/conceptual/SecureCodingGuide/Articles/RaceConditions.html#//apple_ref/doc/uid/TP40002585-SW8)
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
4,247,590
16
2010-11-22T16:19:19Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
Just to add to the confusion, it seems that the try: open() approach suggested above doesn't work in Python, as file access isn't exclusive, not even when writing to files, c.f. [What is the best way to open a file for exclusive access in Python?](http://stackoverflow.com/questions/186202/what-is-the-best-way-to-open-a-file-for-exclusive-access-in-python).
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
4,799,818
33
2011-01-25T23:00:01Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
You could try this: (safer) ``` try: # http://effbot.org/zone/python-with-statement.htm # with is more safe to open file with open('whatever.txt') as fh: # do something with fh except IOError as e: print("({})".format(e)) ``` the ouput would be: > ([Errno 2] No such file or directory: > 'whatever.txt') then, depending on the result, your program can just keep running from there or you can code to stop it if you want.
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
8,876,254
156
2012-01-16T05:57:12Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
Use [`os.path.isfile()`](https://docs.python.org/3.3/library/os.path.html?highlight=os.path#os.path.isfile) with [`os.access()`](https://docs.python.org/3.3/library/os.html?highlight=os.access#os.access): ``` import os import os.path PATH='./file.txt' if os.path.isfile(PATH) and os.access(PATH, os.R_OK): print "File exists and is readable" else: print "Either file is missing or is not readable" ```
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
17,344,732
78
2013-06-27T13:38:04Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
This is the simplest way to check if a file exists. Just **because** the file existed when you checked doesn't **guarantee** that it will be there when you need to open it. ``` import os fname = "foo.txt" if os.path.isfile(fname): print "file does exist at this time" else: print "no such file" ```
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
18,994,918
44
2013-09-25T01:52:46Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
It doesn't seem like there's a meaningful functional difference between try/except and `isfile()`, so you should use which one makes sense. If you want to read a file, if it exists, do ``` try: f = open(filepath) except IOError: print 'Oh dear.' ``` But if you just wanted to rename a file if it exists, and therefore don't need to open it, do ``` if os.path.isfile(filepath): os.rename(filepath, filepath + '.old') ``` If you want to write to a file, if it doesn't exist, do ``` # python 2 if not os.path.isfile(filepath): f = open(filepath, 'w') # python 3, x opens for exclusive creation, failing if the file already exists try: f = open(filepath, 'wx') except IOError: print 'file already exists' ``` If you need file locking, that's a different matter.
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
21,641,213
65
2014-02-08T02:38:42Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
**Python 3.4** has an object-oriented path module: [**pathlib**](http://docs.python.org/3.4/library/pathlib.html). Using this new module, you can check whether a file exists like this: ``` import pathlib p = pathlib.Path('path/to/file') if p.is_file(): # or p.is_dir() to see if it is a directory # do stuff ``` You can (and usually should) still use a `try/except` block when opening files: ``` try: with p.open() as f: # do awesome stuff except OSError: print('Well darn.') ``` The pathlib module has lots of cool stuff in it: convenient globbing, checking file's owner, easier path joining, etc. It's worth checking out. If you're on an older Python (version 2.6 or later), you can still install pathlib with pip: ``` # installs pathlib on older Python versions pip install pathlib ```
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
21,688,350
9
2014-02-10T21:30:20Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
You can write Brian's suggestion without the `try:`. ``` from contextlib import suppress with suppress(IOError), open('filename'): process() ``` `supress` is part of Python 3.4. In older releases you can quickly write your own supress: ``` from contextlib import contextmanager @contextmanager def suppress(*exceptions): try: yield except exceptions: pass ```
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
23,826,292
7
2014-05-23T10:01:20Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
You can use following open method to check if file exists + readable ``` open(inputFile, 'r') ```
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
26,433,646
7
2014-10-17T21:25:30Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
To check if a file exists, ``` from sys import argv from os.path import exists script, filename = argv target = open(filename) print "file exists: %r" % exists(filename) ```
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
27,581,592
7
2014-12-20T15:21:40Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
You can use the "OS" library of python. ``` >>> import os >>> os.path.exists("C:\\Users\\####\\Desktop\\test.txt") True >>> os.path.exists("C:\\Users\\####\\Desktop\\test.tx") False ```
How do I check whether a file exists using Python?
82,831
2,729
2008-09-17T12:55:00Z
27,661,444
25
2014-12-26T20:05:32Z
[ "python", "file", "filesystems" ]
How do I check whether a file exists, without using the [`try`](https://docs.python.org/3.6/reference/compound_stmts.html#try) statement?
Although I always recommend using `try` and `except` statements, here's a few possibilities for you (My personal favourite is using `os.access`: 1. Try opening the file: Opening the file will always verify the existence of the file. You can make a function just like so: ``` def File_Existence(filepath): f = open(filepath) return True ``` If it's False, it will stop execution with an unhanded IOError or OSError in later versions of python. To catch the exception, you have to use a try except clause. Of course, you can always use a `try` `except` statement like so (Thanks to [hsandt](http://stackoverflow.com/users/3256073/hsandt) for making me think): ``` def File_Existence(filepath): try: f = open(filepath) except IOError, OSError: # Note OSError is for later versions of python return False return True ``` 2. Use `os.path.exists(path)`: This will check the existence of what you specify. However, it checks for files *and* directories so beware about how you use it. ``` import os.path >>> os.path.exists("this/is/a/directory") True >>> os.path.exists("this/is/a/file.txt") True >>> os.path.exists("not/a/directory") False ``` 3. Use `os.access(path, mode)`: This will check whether you have access to the file. It will check for permissions. Based on the os.py documentation, typing in `os.F_OK`, will check the existence of the path. However, using this will create a security hole, as someone can attack your file using the time between checking the permissions and opening the file. You should instead go directly to opening the file instead of checking its permissions. ([EAFP](https://docs.python.org/2/glossary.html#term-eafp) vs [LBYP](https://docs.python.org/2/glossary.html#term-lbyl)). If you're not going to open the file afterwards, and only checking its existence, then you can use this. Anyways, here: ``` >>> import os >>> os.access("/is/a/file.txt", os.F_OK) True ``` I should also mention that there are two ways that you will not be able to verify the existence of a file. Either the issue will be `permission denied` or `no such file or directory`. If you catch an `IOError`, set the `IOError as e` (Like my first option), and then type in `print(e.args)` so that you can hopefully determine your issue. Hope it helps! :)