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 |
|---|---|---|---|---|---|---|---|---|---|
How do I get the path and name of the file that is currently executing? | 50,499 | 262 | 2008-09-08T19:41:10Z | 50,521 | 7 | 2008-09-08T19:56:19Z | [
"python",
"scripting",
"file"
] | I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using [execfile](http://docs.python.org/library/functions.html#execfile):
* `script_1.py` calls `script_2.py`.
* In turn, `script_2.py` calls `script_3.py`.
How can I get the file name and path of **`script_3.py`**, *from code within `script_3.py`*, without having to pass that information as arguments from `script_2.py`?
(Executing `os.getcwd()` returns the original starting script's filepath not the current file's.) | The `__file__` attribute works for both the file containing the main execution code as well as imported modules.
See <https://web.archive.org/web/20090918095828/http://pyref.infogami.com/__file__> |
How do I get the path and name of the file that is currently executing? | 50,499 | 262 | 2008-09-08T19:41:10Z | 50,905 | 168 | 2008-09-08T23:02:42Z | [
"python",
"scripting",
"file"
] | I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using [execfile](http://docs.python.org/library/functions.html#execfile):
* `script_1.py` calls `script_2.py`.
* In turn, `script_2.py` calls `script_3.py`.
How can I get the file name and path of **`script_3.py`**, *from code within `script_3.py`*, without having to pass that information as arguments from `script_2.py`?
(Executing `os.getcwd()` returns the original starting script's filepath not the current file's.) | p1.py:
```
execfile("p2.py")
```
p2.py:
```
import inspect, os
print inspect.getfile(inspect.currentframe()) # script filename (usually with path)
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # script directory
``` |
How do I get the path and name of the file that is currently executing? | 50,499 | 262 | 2008-09-08T19:41:10Z | 1,955,163 | 260 | 2009-12-23T20:33:47Z | [
"python",
"scripting",
"file"
] | I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using [execfile](http://docs.python.org/library/functions.html#execfile):
* `script_1.py` calls `script_2.py`.
* In turn, `script_2.py` calls `script_3.py`.
How can I get the file name and path of **`script_3.py`**, *from code within `script_3.py`*, without having to pass that information as arguments from `script_2.py`?
(Executing `os.getcwd()` returns the original starting script's filepath not the current file's.) | ```
__file__
```
as others have said. You may want to use:
```
os.path.realpath(__file__)
``` |
How do I get the path and name of the file that is currently executing? | 50,499 | 262 | 2008-09-08T19:41:10Z | 2,345,265 | 30 | 2010-02-26T22:25:29Z | [
"python",
"scripting",
"file"
] | I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using [execfile](http://docs.python.org/library/functions.html#execfile):
* `script_1.py` calls `script_2.py`.
* In turn, `script_2.py` calls `script_3.py`.
How can I get the file name and path of **`script_3.py`**, *from code within `script_3.py`*, without having to pass that information as arguments from `script_2.py`?
(Executing `os.getcwd()` returns the original starting script's filepath not the current file's.) | The suggestions marked as best are all true if your script consists of only one file.
If you want to find out the name of the executable (i.e. the root file passed to the python interpreter for the current program) from a file that may be imported as a module, you need to do this (let's assume this is in a file named *foo.py*):
`import inspect`
`print inspect.stack()[-1][1]`
Because the last thing (`[-1]`) on the stack is the first thing that went into it (stacks are LIFO/FILO data structures).
Then in file *bar.py* if you `import foo` it'll print *bar.py*, rather than *foo.py*, which would be the value of all of these:
* `__file__`
* `inspect.getfile(inspect.currentframe())`
* `inspect.stack()[0][1]` |
How do I get the path and name of the file that is currently executing? | 50,499 | 262 | 2008-09-08T19:41:10Z | 6,628,348 | 38 | 2011-07-08T17:50:28Z | [
"python",
"scripting",
"file"
] | I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using [execfile](http://docs.python.org/library/functions.html#execfile):
* `script_1.py` calls `script_2.py`.
* In turn, `script_2.py` calls `script_3.py`.
How can I get the file name and path of **`script_3.py`**, *from code within `script_3.py`*, without having to pass that information as arguments from `script_2.py`?
(Executing `os.getcwd()` returns the original starting script's filepath not the current file's.) | I think this is cleaner:
```
import inspect
print inspect.stack()[0][1]
```
and gets the same information as:
```
print inspect.getfile(inspect.currentframe())
```
Where [0] is the current frame in the stack (top of stack) and [1] is for the file name, increase to go backwards in the stack i.e.
```
print inspect.stack()[1][1]
```
would be the file name of the script that called the current frame. Also, using [-1] will get you to the bottom of the stack, the original calling script. |
How do I get the path and name of the file that is currently executing? | 50,499 | 262 | 2008-09-08T19:41:10Z | 18,168,345 | 13 | 2013-08-11T03:05:05Z | [
"python",
"scripting",
"file"
] | I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using [execfile](http://docs.python.org/library/functions.html#execfile):
* `script_1.py` calls `script_2.py`.
* In turn, `script_2.py` calls `script_3.py`.
How can I get the file name and path of **`script_3.py`**, *from code within `script_3.py`*, without having to pass that information as arguments from `script_2.py`?
(Executing `os.getcwd()` returns the original starting script's filepath not the current file's.) | ```
import os
print os.path.basename(__file__)
```
this will give us the filename only. i.e. if abspath of file is c:\abcd\abc.py then 2nd line will print abc.py |
How do I get the path and name of the file that is currently executing? | 50,499 | 262 | 2008-09-08T19:41:10Z | 28,356,929 | 23 | 2015-02-06T01:05:18Z | [
"python",
"scripting",
"file"
] | I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using [execfile](http://docs.python.org/library/functions.html#execfile):
* `script_1.py` calls `script_2.py`.
* In turn, `script_2.py` calls `script_3.py`.
How can I get the file name and path of **`script_3.py`**, *from code within `script_3.py`*, without having to pass that information as arguments from `script_2.py`?
(Executing `os.getcwd()` returns the original starting script's filepath not the current file's.) | ```
import os
os.path.dirname(__file__) # relative directory path
os.path.abspath(__file__) # absolute file path
os.path.basename(__file__) # the file name only
``` |
How do I get the path and name of the file that is currently executing? | 50,499 | 262 | 2008-09-08T19:41:10Z | 31,867,043 | 22 | 2015-08-06T22:50:01Z | [
"python",
"scripting",
"file"
] | I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using [execfile](http://docs.python.org/library/functions.html#execfile):
* `script_1.py` calls `script_2.py`.
* In turn, `script_2.py` calls `script_3.py`.
How can I get the file name and path of **`script_3.py`**, *from code within `script_3.py`*, without having to pass that information as arguments from `script_2.py`?
(Executing `os.getcwd()` returns the original starting script's filepath not the current file's.) | Here is an experiment based on the answers in this thread - with Python 2.7.10 on Windows.
**The stack-based ones are the only ones that seem to give reliable results. The last two have the shortest syntax**, ie -
```
print os.path.abspath(inspect.stack()[0][1]) # C:\testpath\lib\script3.py
print os.path.dirname(os.path.abspath(inspect.stack()[0][1])) # C:\testpath\lib
```
Here's to these being added to **sys** as functions! Credit to @Usagi and @pablog
Based on the following three files, and running script1.py from its folder with `python script1.py` (also tried execfiles with absolute paths and calling from a separate folder).
C:\testpath\script1.py: `execfile('script2.py')`
C:\testpath\script2.py: `execfile('lib/script3.py')`
C:\testpath\lib\script3.py:
```
import sys
import os
import inspect
print "Python " + sys.version
print
print __file__ # script1.py
print sys.argv[0] # script1.py
print inspect.stack()[0][1] # lib/script3.py
print sys.path[0] # C:\testpath
print
print os.path.realpath(__file__) # C:\testpath\script1.py
print os.path.abspath(__file__) # C:\testpath\script1.py
print os.path.basename(__file__) # script1.py
print os.path.basename(os.path.realpath(sys.argv[0])) # script1.py
print
print sys.path[0] # C:\testpath
print os.path.abspath(os.path.split(sys.argv[0])[0]) # C:\testpath
print os.path.dirname(os.path.abspath(__file__)) # C:\testpath
print os.path.dirname(os.path.realpath(sys.argv[0])) # C:\testpath
print os.path.dirname(__file__) # (empty string)
print
print inspect.getfile(inspect.currentframe()) # lib/script3.py
print os.path.abspath(inspect.getfile(inspect.currentframe())) # C:\testpath\lib\script3.py
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # C:\testpath\lib
print
print os.path.abspath(inspect.stack()[0][1]) # C:\testpath\lib\script3.py
print os.path.dirname(os.path.abspath(inspect.stack()[0][1])) # C:\testpath\lib
print
``` |
Django Sessions | 50,568 | 34 | 2008-09-08T20:16:16Z | 50,668 | 25 | 2008-09-08T20:58:29Z | [
"python",
"django",
"session",
"caching",
"mongodb"
] | I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them? | The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it.
The memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost.
If you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases. |
Django Sessions | 50,568 | 34 | 2008-09-08T20:16:16Z | 51,511 | 19 | 2008-09-09T10:11:33Z | [
"python",
"django",
"session",
"caching",
"mongodb"
] | I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them? | I'm no Django expert, so this answer is about session stores generally. Downvote if I'm wrong.
## Performance and Scalability
Choice of session store has an effect on performance and scalability. This should only be a big problem if you have a very popular application.
Both database and filesystem session stores are (usually) backed by disks so you can have a lot of sessions cheaply (because disks are cheap), but requests will often have to wait for the data to be read (because disks are slow). Memcached sessions use RAM, so will cost more to support the same number of concurrent sessions (because RAM is expensive), but may be faster (because RAM is fast).
Filesystem sessions are tied to the box where your application is running, so you can't load balance between multiple application servers if your site gets huge. Database and memcached sessions let you have multiple application servers talking to a shared session store.
## Simplicity
Choice of session store will also impact how easy it is to deploy your site. Changing away from the default will cost some complexity. Memcached and RDBMSs both have their own complexities, but your application is probably going to be using an RDBMS anyway.
Unless you have a very popular application, simplicity should be the larger concern.
## Bonus
Another approach is to store [session data in cookies](https://docs.djangoproject.com/en/1.8/topics/http/sessions/#using-cookie-based-sessions) (all of it, not just an ID). This has the advantage that the session store automatically scales with the number of users, but it has disadvantages too. You (or your framework) need to be careful to stop users forging session data. You also need to keep each session small because the whole thing will be sent with every request. |
Django Sessions | 50,568 | 34 | 2008-09-08T20:16:16Z | 1,939,548 | 9 | 2009-12-21T11:21:56Z | [
"python",
"django",
"session",
"caching",
"mongodb"
] | I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them? | As of Django 1.1 you can use the cached\_db session back end.
This stores the session in the cache (only use with memcached), and writes it back to the DB. If it has fallen out of the cache, it will be read from the DB.
Although this is slower than just using memcached for storing the session, it adds persistence to the session.
For more information, see: [Django Docs: Using Cached Sessions](http://docs.djangoproject.com/en/dev/topics/http/sessions/#using-cached-sessions) |
How do you create a weak reference to an object in Python? | 50,923 | 4 | 2008-09-08T23:10:53Z | 50,929 | 10 | 2008-09-08T23:13:16Z | [
"python",
"weak-references"
] | How do you create a weak reference to an object in Python? | ```
>>> import weakref
>>> class Object:
... pass
...
>>> o = Object()
>>> r = weakref.ref(o)
>>> # if the reference is still active, r() will be o, otherwise None
>>> do_something_with_o(r())
```
See the [wearkref module docs](http://docs.python.org/lib/module-weakref.html) for more details.
You can also use `weakref.proxy` to create an object that proxies o. Will throw `ReferenceError` if used when the referent is no longer referenced. |
What is the simplest way to find the difference between 2 times in python? | 51,010 | 9 | 2008-09-09T00:28:58Z | 51,042 | 16 | 2008-09-09T00:53:24Z | [
"python",
"datetime",
"time"
] | I have 2 time values which have the type `datetime.time`. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type `datetime.datetime` but not for `datetime.time`. So what is the best way to do this? | Also a little silly, but you could try picking an arbitrary day and embedding each time in it, using `datetime.datetime.combine`, then subtracting:
```
>>> import datetime
>>> t1 = datetime.time(2,3,4)
>>> t2 = datetime.time(18,20,59)
>>> dummydate = datetime.date(2000,1,1)
>>> datetime.datetime.combine(dummydate,t2) - datetime.datetime.combine(dummydate,t1)
datetime.timedelta(0, 58675)
``` |
How to write a download progress indicator in Python? | 51,212 | 41 | 2008-09-09T04:09:15Z | 51,218 | 13 | 2008-09-09T04:21:09Z | [
"python",
"http"
] | I am writing a little application to download files over http (as, for example, described [here](http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776)).
I also want to include a little download progress indicator showing the percentage of the download progress.
Here is what I came up with:
```
sys.stdout.write(rem_file + "...")
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % percent)
sys.stdout.write("\b\b\b")
sys.stdout.flush()
```
Output: MyFileName... 9%
Any other ideas or recommendations to do this?
One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?
**EDIT:**
Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:
```
global rem_file # global variable to be used in dlProgress
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
sys.stdout.flush()
```
Output: MyFileName...9%
And the cursor shows up at the END of the line. Much better. | You might also try:
```
sys.stdout.write("\r%2d%%" % percent)
sys.stdout.flush()
```
Using a single carriage return at the beginning of your string rather than several backspaces. Your cursor will still blink, but it'll blink after the percent sign rather than under the first digit, and with one control character instead of three you may get less flicker. |
How to write a download progress indicator in Python? | 51,212 | 41 | 2008-09-09T04:09:15Z | 51,239 | 16 | 2008-09-09T04:48:28Z | [
"python",
"http"
] | I am writing a little application to download files over http (as, for example, described [here](http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776)).
I also want to include a little download progress indicator showing the percentage of the download progress.
Here is what I came up with:
```
sys.stdout.write(rem_file + "...")
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % percent)
sys.stdout.write("\b\b\b")
sys.stdout.flush()
```
Output: MyFileName... 9%
Any other ideas or recommendations to do this?
One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?
**EDIT:**
Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:
```
global rem_file # global variable to be used in dlProgress
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
sys.stdout.flush()
```
Output: MyFileName...9%
And the cursor shows up at the END of the line. Much better. | There's a text progress bar library for python at <http://pypi.python.org/pypi/progressbar/2.2> that you might find useful:
> This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway.
>
> The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line.
>
> The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when available. |
How can I retrieve the page title of a webpage using Python? | 51,233 | 44 | 2008-09-09T04:38:55Z | 51,240 | 44 | 2008-09-09T04:49:38Z | [
"python",
"html"
] | How can I retrieve the page title of a webpage (title html tag) using Python? | I'll always use [lxml](http://lxml.de/) for such tasks. You could use [beautifulsoup](http://www.crummy.com/software/BeautifulSoup/) as well.
```
import lxml.html
t = lxml.html.parse(url)
print t.find(".//title").text
``` |
How can I retrieve the page title of a webpage using Python? | 51,233 | 44 | 2008-09-09T04:38:55Z | 51,263 | 10 | 2008-09-09T05:45:39Z | [
"python",
"html"
] | How can I retrieve the page title of a webpage (title html tag) using Python? | The mechanize Browser object has a title() method. So the code from [this post](http://stackoverflow.com/questions/51233/how-can-i-retrieve-the-page-title-of-a-webpage-using-python#51242) can be rewritten as:
```
from mechanize import Browser
br = Browser()
br.open("http://www.google.com/")
print br.title()
``` |
How can I retrieve the page title of a webpage using Python? | 51,233 | 44 | 2008-09-09T04:38:55Z | 51,550 | 54 | 2008-09-09T10:32:54Z | [
"python",
"html"
] | How can I retrieve the page title of a webpage (title html tag) using Python? | Here's a simplified version of [@Vinko Vrsalovic's answer](http://stackoverflow.com/a/51242/4279):
```
import urllib2
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen("https://www.google.com"))
print soup.title.string
```
NOTE:
* *soup.title* finds the first *title* element **anywhere** in the html document
* *title.string* assumes it has only **one** child node, and that child node is a **string**
For [beautifulsoup 4.x](http://www.crummy.com/software/BeautifulSoup/bs4/doc/), use different import:
```
from bs4 import BeautifulSoup
``` |
Passing on named variable arguments in python | 51,412 | 11 | 2008-09-09T08:46:51Z | 51,415 | 32 | 2008-09-09T08:50:34Z | [
"python",
"varargs"
] | Say I have the following methods:
```
def methodA(arg, **kwargs):
pass
def methodB(arg, *args, **kwargs):
pass
```
In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define `methodA` as follows, the second argument will be passed on as positional rather than named variable arguments.
```
def methodA(arg, **kwargs):
methodB("argvalue", kwargs)
```
How do I make sure that the \*\*kwargs in methodA gets passed as \*\*kwargs to methodB? | Put the asterisks before the kwargs variable. This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments.
```
methodB("argvalue", **kwargs)
``` |
Improving Python readability? | 51,502 | 2 | 2008-09-09T10:05:36Z | 51,505 | 8 | 2008-09-09T10:08:28Z | [
"python",
"readability"
] | I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.
However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.
For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):
```
if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
```
The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:
```
if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
```
And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me. | You could try increasing the indent size, but in general I would just say, relax, it will come with time. I don't think trying to make Python look like C is a very good idea. |
Improving Python readability? | 51,502 | 2 | 2008-09-09T10:05:36Z | 51,551 | 15 | 2008-09-09T10:33:05Z | [
"python",
"readability"
] | I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.
However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.
For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):
```
if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
```
The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:
```
if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
```
And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me. | I like to put blank lines around blocks to make control flow more obvious. For example:
```
if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
``` |
Improving Python readability? | 51,502 | 2 | 2008-09-09T10:05:36Z | 51,570 | 7 | 2008-09-09T10:43:27Z | [
"python",
"readability"
] | I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.
However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.
For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):
```
if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
```
The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:
```
if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
```
And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me. | Rather than focusing on making your existing structures more readable, you should focus on making more logical structures. Make smaller blocks, try not to nest blocks excessively, make smaller functions, and try to think through your code flow more.
If you come to a point where you can't quickly determine the structure of your code, you should probably consider refactoring and adding some comments. Code flow should always be immediately apparent -- the more you have to think about it, the less maintainable your code becomes. |
Improving Python readability? | 51,502 | 2 | 2008-09-09T10:05:36Z | 52,090 | 23 | 2008-09-09T14:58:52Z | [
"python",
"readability"
] | I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.
However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.
For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):
```
if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
```
The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:
```
if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
```
And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me. | Part of learning a new programming language is learning to read code in that language. A crutch like this may make it easier to read your own code, but it's going to impede the process of learning how to read anyone else's Python code. I really think you'd be better off getting rid of the end of block comments and getting used to normal Python. |
How to get an absolute file path in Python | 51,520 | 308 | 2008-09-09T10:19:32Z | 51,523 | 424 | 2008-09-09T10:21:03Z | [
"python",
"path",
"relative-path",
"absolute-path"
] | Given a path such as `"mydir/myfile.txt"`, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:
```
"C:/example/cwd/mydir/myfile.txt"
``` | ```
>>> import os
>>> os.path.abspath("mydir/myfile.txt")
``` |
How to get an absolute file path in Python | 51,520 | 308 | 2008-09-09T10:19:32Z | 51,539 | 32 | 2008-09-09T10:28:26Z | [
"python",
"path",
"relative-path",
"absolute-path"
] | Given a path such as `"mydir/myfile.txt"`, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:
```
"C:/example/cwd/mydir/myfile.txt"
``` | ```
>>> import os
>>> os.path.abspath('mydir/myfile.txt')
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>
``` |
How to get an absolute file path in Python | 51,520 | 308 | 2008-09-09T10:19:32Z | 58,417 | 13 | 2008-09-12T06:53:25Z | [
"python",
"path",
"relative-path",
"absolute-path"
] | Given a path such as `"mydir/myfile.txt"`, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:
```
"C:/example/cwd/mydir/myfile.txt"
``` | Better still, install the [`path.py`](http://pypi.python.org/pypi/path.py/2.2) module, it wraps all the `os.path` functions and other related functions into methods on an object that can be used wherever strings are used:
```
>>> from path import path
>>> path('mydir/myfile.txt').abspath()
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>
``` |
How to get an absolute file path in Python | 51,520 | 308 | 2008-09-09T10:19:32Z | 15,325,066 | 7 | 2013-03-10T17:11:57Z | [
"python",
"path",
"relative-path",
"absolute-path"
] | Given a path such as `"mydir/myfile.txt"`, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:
```
"C:/example/cwd/mydir/myfile.txt"
``` | Today you can also use the `unipath` package which was based on `path.py`: <http://sluggo.scrapping.cc/python/unipath/>
```
>>> from unipath import Path
>>> absolute_path = Path('mydir/myfile.txt').absolute()
Path('C:\\example\\cwd\\mydir\\myfile.txt')
>>> str(absolute_path)
C:\\example\\cwd\\mydir\\myfile.txt
>>>
```
I would recommend using this package as it offers [a clean interface to common os.path utilities](http://sluggo.scrapping.cc/python/unipath/Unipath-current/README.html). |
How to get an absolute file path in Python | 51,520 | 308 | 2008-09-09T10:19:32Z | 26,539,947 | 29 | 2014-10-24T01:05:02Z | [
"python",
"path",
"relative-path",
"absolute-path"
] | Given a path such as `"mydir/myfile.txt"`, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:
```
"C:/example/cwd/mydir/myfile.txt"
``` | You could use the new Python 3.4 library `pathlib`. (You can also get it for Python 2.6 or 2.7 using `pip install pathlib`.) The authors [wrote](http://www.python.org/dev/peps/pep-0428/#abstract): "The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them."
To get an absolute path in Windows:
```
>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
WindowsPath('C:/Python27/pythonw.exe')
>>> str(p)
'C:\\Python27\\pythonw.exe'
```
Or on UNIX:
```
>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
PosixPath('/opt/python3/bin/python3.4')
>>> str(p)
'/opt/python3/bin/python3.4'
```
Docs are here: <https://docs.python.org/3/library/pathlib.html> |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) | 51,553 | 11 | 2008-09-09T10:33:39Z | 51,745 | 13 | 2008-09-09T12:31:26Z | [
"python",
"sql",
"optimization",
"aggregate",
"olap"
] | I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):
```
SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
```
Is this normal behaviour when using a SQL database?
The schema (the table holds responses to a survey):
```
CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
```
I wrote some tests in Java and Python for context and they crush SQL (except for pure python):
```
java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
```
Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)
Tunings i've tried without success include (blindly following some web advice):
```
increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
```
So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous.
Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.
---
No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.
The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)
I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.
The Postgres query doesn't change timing on subsequent runs.
I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!) | I would say your test scheme is not really useful. To fulfill the db query, the db server goes through several steps:
1. parse the SQL
2. work up a query plan, i. e. decide on which indices to use (if any), optimize etc.
3. if an index is used, search it for the pointers to the actual data, then go to the appropriate location in the data or
4. if no index is used, scan *the whole table* to determine which rows are needed
5. load the data from disk into a temporary location (hopefully, but not necessarily, memory)
6. perform the count() and avg() calculations
So, creating an array in Python and getting the average basically skips all these steps save the last one. As disk I/O is among the most expensive operations a program has to perform, this is a major flaw in the test (see also the answers to [this question](http://stackoverflow.com/questions/26021/how-is-data-compression-more-effective-than-indexing-for-search-performance) I asked here before). Even if you read the data from disk in your other test, the process is completely different and it's hard to tell how relevant the results are.
To obtain more information about where Postgres spends its time, I would suggest the following tests:
* Compare the execution time of your query to a SELECT without the aggregating functions (i. e. cut step 5)
* If you find that the aggregation leads to a significant slowdown, try if Python does it faster, obtaining the raw data through the plain SELECT from the comparison.
To speed up your query, reduce disk access first. I doubt very much that it's the aggregation that takes the time.
There's several ways to do that:
* Cache data (in memory!) for subsequent access, either via the db engine's own capabilities or with tools like memcached
* Reduce the size of your stored data
* Optimize the use of indices. Sometimes this can mean to skip index use altogether (after all, it's disk access, too). For MySQL, I seem to remember that it's recommended to skip indices if you assume that the query fetches more than 10% of all the data in the table.
* If your query makes good use of indices, I know that for MySQL databases it helps to put indices and data on separate physical disks. However, I don't know whether that's applicable for Postgres.
* There also might be more sophisticated problems such as swapping rows to disk if for some reason the result set can't be completely processed in memory. But I would leave that kind of research until I run into serious performance problems that I can't find another way to fix, as it requires knowledge about a lot of little under-the-hood details in your process.
**Update:**
*I just realized that you seem to have no use for indices for the above query and most likely aren't using any, too, so my advice on indices probably wasn't helpful. Sorry. Still, I'd say that the aggregation is not the problem but disk access is. I'll leave the index stuff in, anyway, it might still have some use.* |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) | 51,553 | 11 | 2008-09-09T10:33:39Z | 52,006 | 8 | 2008-09-09T14:26:28Z | [
"python",
"sql",
"optimization",
"aggregate",
"olap"
] | I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):
```
SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
```
Is this normal behaviour when using a SQL database?
The schema (the table holds responses to a survey):
```
CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
```
I wrote some tests in Java and Python for context and they crush SQL (except for pure python):
```
java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
```
Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)
Tunings i've tried without success include (blindly following some web advice):
```
increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
```
So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous.
Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.
---
No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.
The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)
I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.
The Postgres query doesn't change timing on subsequent runs.
I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!) | Postgres is doing a lot more than it looks like (maintaining data consistency for a start!)
If the values don't have to be 100% spot on, or if the table is updated rarely, but you are running this calculation often, you might want to look into Materialized Views to speed it up.
(Note, I have not used materialized views in Postgres, they look at little hacky, but might suite your situation).
[Materialized Views](http://jonathangardner.net/tech/w/PostgreSQL/Materialized_Views)
Also consider the overhead of actually connecting to the server and the round trip required to send the request to the server and back.
I'd consider 200ms for something like this to be pretty good, A quick test on my oracle server, the same table structure with about 500k rows and no indexes, takes about 1 - 1.5 seconds, which is almost all just oracle sucking the data off disk.
The real question is, is 200ms fast enough?
-------------- More --------------------
I was interested in solving this using materialized views, since I've never really played with them. This is in oracle.
First I created a MV which refreshes every minute.
```
create materialized view mv_so_x
build immediate
refresh complete
START WITH SYSDATE NEXT SYSDATE + 1/24/60
as select count(*),avg(a),avg(b),avg(c),avg(d) from so_x;
```
While its refreshing, there is no rows returned
```
SQL> select * from mv_so_x;
no rows selected
Elapsed: 00:00:00.00
```
Once it refreshes, its MUCH faster than doing the raw query
```
SQL> select count(*),avg(a),avg(b),avg(c),avg(d) from so_x;
COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)
---------- ---------- ---------- ---------- ----------
1899459 7495.38839 22.2905454 5.00276131 2.13432836
Elapsed: 00:00:05.74
SQL> select * from mv_so_x;
COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)
---------- ---------- ---------- ---------- ----------
1899459 7495.38839 22.2905454 5.00276131 2.13432836
Elapsed: 00:00:00.00
SQL>
```
If we insert into the base table, the result is not immediately viewable view the MV.
```
SQL> insert into so_x values (1,2,3,4,5);
1 row created.
Elapsed: 00:00:00.00
SQL> commit;
Commit complete.
Elapsed: 00:00:00.00
SQL> select * from mv_so_x;
COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)
---------- ---------- ---------- ---------- ----------
1899459 7495.38839 22.2905454 5.00276131 2.13432836
Elapsed: 00:00:00.00
SQL>
```
But wait a minute or so, and the MV will update behind the scenes, and the result is returned fast as you could want.
```
SQL> /
COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)
---------- ---------- ---------- ---------- ----------
1899460 7495.35823 22.2905352 5.00276078 2.17647059
Elapsed: 00:00:00.00
SQL>
```
This isn't ideal. for a start, its not realtime, inserts/updates will not be immediately visible. Also, you've got a query running to update the MV whether you need it or not (this can be tune to whatever time frame, or on demand). But, this does show how much faster an MV can make it seem to the end user, if you can live with values which aren't quite upto the second accurate. |
Cross-platform space remaining on volume using python | 51,658 | 56 | 2008-09-09T11:36:39Z | 2,372,171 | 58 | 2010-03-03T14:45:23Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] | I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way? | ```
import ctypes
import os
import platform
import sys
def get_free_space_mb(dirname):
"""Return folder/drive free space (in megabytes)."""
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
return free_bytes.value / 1024 / 1024
else:
st = os.statvfs(dirname)
return st.f_bavail * st.f_frsize / 1024 / 1024
```
Note that you *must* pass a directory name for `GetDiskFreeSpaceEx()` to work
(`statvfs()` works on both files and directories). You can get a directory name
from a file with `os.path.dirname()`.
Also see the documentation for [`os.statvfs()`](https://docs.python.org/3/library/os.html#os.fstatvfs) and [`GetDiskFreeSpaceEx`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx). |
Cross-platform space remaining on volume using python | 51,658 | 56 | 2008-09-09T11:36:39Z | 19,332,602 | 13 | 2013-10-12T09:20:42Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] | I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way? | You could use the [wmi](https://pypi.python.org/pypi/WMI/) module for windows and os.statvfs for unix
for window
```
import wmi
c = wmi.WMI ()
for d in c.Win32_LogicalDisk():
print( d.Caption, d.FreeSpace, d.Size, d.DriveType)
```
for unix or linux
```
from os import statvfs
statvfs(path)
``` |
Cross-platform space remaining on volume using python | 51,658 | 56 | 2008-09-09T11:36:39Z | 29,944,093 | 7 | 2015-04-29T12:43:17Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] | I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way? | Install [psutil](http://pythonhosted.org/psutil/) using `pip install psutil`. Then you can get the amount of free space in bytes using:
```
import psutil
print(psutil.disk_usage(".").free)
``` |
Large Python Includes | 53,027 | 3 | 2008-09-09T22:15:09Z | 53,037 | 8 | 2008-09-09T22:21:04Z | [
"python"
] | I have a file that I want to include in Python but the included file is fairly long and it'd be much neater to be able to split them into several files but then I have to use several include statements.
Is there some way to group together several files and include them all at once? | 1. Put files in one folder.
2. Add \_\_init\_\_.py file to the folder. Do necessary imports in \_\_init\_\_.py
3. Replace multiple imports by one:
import folder\_name
See [Python Package Management](http://docs.python.org/tut/node8.html#SECTION008400000000000000000) |
How can I do a line break (line continuation) in Python? | 53,162 | 535 | 2008-09-09T23:45:30Z | 53,173 | 12 | 2008-09-09T23:48:30Z | [
"python",
"syntax",
"line-breaks",
"long-lines"
] | I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?
For example, adding a bunch of strings,
```
e = 'a' + 'b' + 'c' + 'd'
```
and have it like this:
```
e = 'a' + 'b' +
'c' + 'd'
``` | Put a `\` at the end of your line or enclose the statement in parens `( .. )`. From [IBM](http://www.ibm.com/developerworks/opensource/library/os-python5/):
```
b = ((i1 < 20) and
(i2 < 30) and
(i3 < 40))
```
or
```
b = (i1 < 20) and \
(i2 < 30) and \
(i3 < 40)
``` |
How can I do a line break (line continuation) in Python? | 53,162 | 535 | 2008-09-09T23:45:30Z | 53,180 | 615 | 2008-09-09T23:52:05Z | [
"python",
"syntax",
"line-breaks",
"long-lines"
] | I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?
For example, adding a bunch of strings,
```
e = 'a' + 'b' + 'c' + 'd'
```
and have it like this:
```
e = 'a' + 'b' +
'c' + 'd'
``` | What is the line? You can just have arguments on the next line without any problems:
```
a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5,
blahblah6, blahblah7)
```
Otherwise you can do something like this:
```
if a == True and \
b == False
```
Check the [style guide](http://www.python.org/dev/peps/pep-0008/) for more information.
From your example line:
```
a = '1' + '2' + '3' + \
'4' + '5'
```
Or:
```
a = ('1' + '2' + '3' +
'4' + '5')
```
Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go. |
How can I do a line break (line continuation) in Python? | 53,162 | 535 | 2008-09-09T23:45:30Z | 53,182 | 9 | 2008-09-09T23:53:17Z | [
"python",
"syntax",
"line-breaks",
"long-lines"
] | I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?
For example, adding a bunch of strings,
```
e = 'a' + 'b' + 'c' + 'd'
```
and have it like this:
```
e = 'a' + 'b' +
'c' + 'd'
``` | > From the horse's mouth: [Explicit line
> joining](http://docs.python.org/ref/explicit-joining.html)
>
> Two or more physical lines may be
> joined into logical lines using
> backslash characters (`\`), as follows:
> when a physical line ends in a
> backslash that is not part of a string
> literal or comment, it is joined with
> the following forming a single logical
> line, deleting the backslash and the
> following end-of-line character. For
> example:
>
> ```
> if 1900 < year < 2100 and 1 <= month <= 12 \
> and 1 <= day <= 31 and 0 <= hour < 24 \
> and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
> return 1
> ```
>
> A line ending in a backslash cannot
> carry a comment. A backslash does not
> continue a comment. A backslash does
> not continue a token except for string
> literals (i.e., tokens other than
> string literals cannot be split across
> physical lines using a backslash). A
> backslash is illegal elsewhere on a
> line outside a string literal. |
How can I do a line break (line continuation) in Python? | 53,162 | 535 | 2008-09-09T23:45:30Z | 53,200 | 119 | 2008-09-10T00:06:39Z | [
"python",
"syntax",
"line-breaks",
"long-lines"
] | I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?
For example, adding a bunch of strings,
```
e = 'a' + 'b' + 'c' + 'd'
```
and have it like this:
```
e = 'a' + 'b' +
'c' + 'd'
``` | From [Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/):
> **The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces.** Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
>
> Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:
>
> ```
> with open('/path/to/some/file/you/want/to/read') as file_1, \
> open('/path/to/some/file/being/written', 'w') as file_2:
> file_2.write(file_1.read())
> ```
>
> Another such case is with assert statements.
>
> Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is **after** the operator, not before it. Some examples:
>
> ```
> class Rectangle(Blob):
>
> def __init__(self, width, height,
> color='black', emphasis=None, highlight=0):
> if (width == 0 and height == 0 and
> color == 'red' and emphasis == 'strong' or
> highlight > 100):
> raise ValueError("sorry, you lose")
> if width == 0 and height == 0 and (color == 'red' or
> emphasis is None):
> raise ValueError("I don't think so -- values are %s, %s" %
> (width, height))
> Blob.__init__(self, width, height,
> color, emphasis, highlight)
> ```
EDIT: PEP8 now recommends the *opposite convention* (for breaking at binary operations) used by Mathematicians and their publishers to improve readability.
Donald Knuth's style of breaking **before** a binary operator aligns operators vertically, thus reducing the eye's workload when determining which items are added and subtracted.
From [PEP8: Should a line break before or after a binary operator?](http://legacy.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator):
> Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations"[3].
>
> Following the tradition from mathematics usually results in more readable code:
>
> ```
> # Yes: easy to match operators with operands
> income = (gross_wages
> + taxable_interest
> + (dividends - qualified_dividends)
> - ira_deduction
> - student_loan_interest)
> ```
>
> In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.
[3]: Donald Knuth's The TeXBook, pages 195 and 196 |
How can I do a line break (line continuation) in Python? | 53,162 | 535 | 2008-09-09T23:45:30Z | 61,933 | 46 | 2008-09-15T06:28:30Z | [
"python",
"syntax",
"line-breaks",
"long-lines"
] | I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?
For example, adding a bunch of strings,
```
e = 'a' + 'b' + 'c' + 'd'
```
and have it like this:
```
e = 'a' + 'b' +
'c' + 'd'
``` | The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.
See Python Idioms and Anti-Idioms (for [Python 2](https://docs.python.org/2/howto/doanddont.html#using-backslash-to-continue-statements) or [Python 3](https://docs.python.org/3.1/howto/doanddont.html#using-backslash-to-continue-statements)) for more. |
How can I do a line break (line continuation) in Python? | 53,162 | 535 | 2008-09-09T23:45:30Z | 110,882 | 16 | 2008-09-21T12:20:08Z | [
"python",
"syntax",
"line-breaks",
"long-lines"
] | I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?
For example, adding a bunch of strings,
```
e = 'a' + 'b' + 'c' + 'd'
```
and have it like this:
```
e = 'a' + 'b' +
'c' + 'd'
``` | You can break lines in between parenthesises and braces. Additionally, you can append the backslash character `\` to a line to explicitly break it:
```
x = (tuples_first_value,
second_value)
y = 1 + \
2
``` |
How do you check whether a python method is bound or not? | 53,225 | 22 | 2008-09-10T00:31:11Z | 53,322 | 27 | 2008-09-10T02:19:09Z | [
"python",
"python-datamodel"
] | Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to? | ```
def isbound(method):
return method.im_self is not None
def instance(bounded_method):
return bounded_method.im_self
```
[User-defined methods:](http://docs.python.org/ref/types.html)
> When a user-defined method object is
> created by retrieving a user-defined
> function object from a class, its
> `im_self` attribute is `None` and the
> method object is said to be unbound.
> When one is created by retrieving a
> user-defined function object from a
> class via one of its instances, its
> `im_self` attribute is the instance, and
> the method object is said to be bound.
> In either case, the new method's
> `im_class` attribute is the class from
> which the retrieval takes place, and
> its `im_func` attribute is the original
> function object.
In Python [2.6 and 3.0](http://docs.python.org/dev/whatsnew/2.6.html):
> Instance method objects have new
> attributes for the object and function
> comprising the method; the new synonym
> for `im_self` is `__self__`, and `im_func`
> is also available as `__func__`. The old
> names are still supported in Python
> 2.6, but are gone in 3.0. |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 53,522 | 2,388 | 2008-09-10T06:28:05Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | ```
if not a:
print("List is empty")
```
Using the implicit booleanness of the empty list `a` is quite pythonic. |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 53,523 | 35 | 2008-09-10T06:28:39Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | I have seen the below as preferred, as it will catch the null list as well:
```
if not a:
print "The list is empty or null"
``` |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 53,525 | 65 | 2008-09-10T06:31:22Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | An empty list is itself considered false in true value testing (see [python documentation](https://docs.python.org/2/library/stdtypes.html#truth-value-testing)):
```
a = []
if a:
print "not empty"
```
@Daren Thomas
> EDIT: Another point against testing
> the empty list as False: What about
> polymorphism? You shouldn't depend on
> a list being a list. It should just
> quack like a duck - how are you going
> to get your duckCollection to quack
> ''False'' when it has no elements?
Your duckCollection should implement `__nonzero__` or `__len__` so the if a: will work without problems. |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 53,752 | 565 | 2008-09-10T10:33:38Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | The pythonic way to do it is from the [PEP 8 style guide](https://www.python.org/dev/peps/pep-0008):
> For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
>
> ```
> Yes: if not seq:
> if seq:
>
> No: if len(seq):
> if not len(seq):
> ``` |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 61,918 | 28 | 2008-09-15T05:50:48Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | [`len()` is an O(1) operation](http://books.google.com/books?id=vpTAq4dnmuAC&pg=RA1-PA479&lpg=RA1-PA479&dq=Python+len+big+O&source=web&ots=AOM6A1K9Fy&sig=iQo8mV6Xf9KdzuNSa-Jkr8wDEuw&hl=en&sa=X&oi=book_result&resnum=4&ct=result) for Python lists, strings, dicts, and sets. Python internally keeps track of the number of elements in these containers.
JavaScript [has a similar notion of truthy/falsy](http://www.isolani.co.uk/blog/javascript/TruthyFalsyAndTypeCasting). |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 7,302,987 | 267 | 2011-09-05T00:30:30Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | I prefer it explicitly:
```
if len(li) == 0:
print 'the list is empty'
```
This way it's 100% clear that `li` is a sequence (list) and we want to test its size. My problem with `if not li: ...` is that it gives the false impression that `li` is a boolean variable. |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 9,381,545 | 95 | 2012-02-21T16:48:02Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | # Other methods don't work for numpy arrays
Other people seem to be generalizing your question beyond just `list`s, so I thought I'd add a caveat for a different type of sequence that a lot of people might use. You need to be careful with numpy arrays, because other methods that work fine for `list`s fail for numpy arrays. I explain why below, but in short, the [preferred method](http://www.scipy.org/scipylib/faq.html#what-is-the-preferred-way-to-check-for-an-empty-zero-element-array) is to use `size`.
### The "pythonic" way doesn't work I
The "pythonic" way fails with numpy arrays because numpy tries to cast the array to an array of `bool`s, and `if x` tries to evaluate all of those `bool`s at once for some kind of aggregate truth value. But this doesn't make any sense, so you get a `ValueError`:
```
>>> x = numpy.array([0,1])
>>> if x: print("x")
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
```
### The "pythonic" way doesn't work II
But at least the case above tells you that it failed. If you happen to have a numpy array with exactly one element, the `if` statement will "work", in the sense that you don't get an error. However, if that one element happens to be `0` (or `0.0`, or `false`, ...), the `if` statement will incorrectly result in `false`:
```
>>> x = numpy.array([0,])
>>> if x: print("x")
... else: print("No x")
No x
```
But clearly `x` exists and is not empty! This result is not what you wanted.
### Using `len` can give unexpected results
For example,
```
len( numpy.zeros((1,0)) )
```
returns 1, even though the array has zero elements.
### The numpythonic way
As explained in the [scipy FAQ](http://www.scipy.org/scipylib/faq.html#what-is-the-preferred-way-to-check-for-an-empty-zero-element-array), the correct method in all cases where you know you have a numpy array is to use `if x.size`:
```
>>> x = numpy.array([0,1])
>>> if x.size: print("x")
x
>>> x = numpy.array([0,])
>>> if x.size: print("x")
... else: print("No x")
x
>>> x = numpy.zeros((1,0))
>>> if x.size: print("x")
... else: print("No x")
No x
```
If you're not sure whether it might be a `list`, a numpy array, or something else, you should combine this approach with [the answer @dubiousjim gives](http://stackoverflow.com/a/10835703/1194883) to make sure the right test is used for each type. Not very "pythonic", but it turns out that python itself isn't pythonic in this sense either... |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 10,835,703 | 15 | 2012-05-31T14:35:05Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | I had written:
```
if isinstance(a, (list, some, other, types, i, accept)) and not a:
do_stuff
```
which was voted -1. I'm not sure if that's because readers objected to the strategy or thought the answer wasn't helpful as presented. I'll pretend it was the latter, since---whatever counts as "pythonic"---this is the correct strategy. Unless you've already ruled out, or are prepared to handle cases where `a` is, for example, `False`, you need a test more restrictive than just `if not a:`. You could use something like this:
```
if isinstance(a, numpy.ndarray) and not a.size:
do_stuff
elif isinstance(a, collections.Sized) and not a:
do_stuff
```
the first test is in response to @Mike's answer, above. The third line could also be replaced with:
```
elif isinstance(a, (list, tuple)) and not a:
```
if you only want to accept instances of particular types (and their subtypes), or with:
```
elif isinstance(a, (list, tuple)) and not len(a):
```
You can get away without the explicit type check, but only if the surrounding context already assures you that `a` is a value of the types you're prepared to handle, or if you're sure that types you're not prepared to handle are going to raise errors (e.g., a `TypeError` if you call `len` on a value for which it's undefined) that you're prepared to handle. In general, the "pythonic" conventions seem to go this last way. Squeeze it like a duck and let it raise a DuckError if it doesn't know how to quack. You still have to *think* about what type assumptions you're making, though, and whether the cases you're not prepared to handle properly really are going to error out in the right places. The Numpy arrays are a good example where just blindly relying on `len` or the boolean typecast may not do precisely what you're expecting. |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 10,863,668 | 16 | 2012-06-02T15:40:24Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | Python is very uniform about the treatment of emptiness. Given the following:
```
a = []
.
.
.
if a:
print("List is not empty.")
else:
print("List is empty.")
```
You simply check list a with an "if" statement to see if it is empty. From what I have read and been taught, this is the "Pythonic" way to see if a list or tuple is empty. |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 26,579,625 | 7 | 2014-10-27T00:35:45Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | some methods what i use:
```
if not a:
print "list is empty"
if not bool(a):
print "list is empty"
if len(a) == 0:
print "list is empty"
``` |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 27,262,598 | 39 | 2014-12-03T02:21:29Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | [Patrick's (accepted) answer](http://stackoverflow.com/a/53522/908494) is right: `if not a:` is the right way to do it. [Harley Holcombe's answer](http://stackoverflow.com/a/53752/908494) is right that this is in the PEP 8 style guide. But what none of the answers explain is why it's a good idea to follow the idiomâeven if you personally find it's not explicit enough or confusing to Ruby users or whatever.
Python code, and the Python community, has very strong idioms. Following those idioms makes your code easier to read for anyone experienced in Python. And when you violate those idioms, that's a strong signal.
It's true that `if not a:` doesn't distinguish empty lists from `None`, or numeric 0, or empty tuples, or empty user-created collection types, or empty user-created not-quite-collection types, or single-element NumPy array acting as scalars with falsey values, etc. And sometimes it's important to be explicit about that. And in that case, you know *what* you want to be explicit about, so you can test for exactly that. For example, `if not a and a is not None:` means "anything falsey except None", while `if len(a) != 0:` means "only empty sequencesâand anything besides a sequence is an error here", and so on. Besides testing for exactly what you want to test, this also signals to the reader that this test is important.
But when you don't have anything to be explicit about, anything other than `if not a:` is misleading the reader. You're signaling something as important when it isn't. (You may also be making the code less flexible, or slower, or whatever, but that's all less important.) And if you *habitually* mislead the reader like this, then when you *do* need to make a distinction, it's going to pass unnoticed because you've been "crying wolf" all over your code. |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 32,978,062 | 16 | 2015-10-06T19:25:34Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | No one seems to have addressed questioning your *need* to test the list in the first place. Because you provided no additional context, I can imagine that you may not need to do this check in the first place, but are unfamiliar with list processing in Python.
I would argue that the *most pythonic* way is to not check at all, but rather to just process the list. That way it will do the right thing whether empty or full.
```
a = []
for item in a:
<do something with item>
<rest of code>
```
This has the benefit of handling any contents of **a**, while not requiring a specific check for emptiness. If **a** is empty, the dependent block will not execute and the interpreter will fall through to the next line.
If you do actually need to check the array for emptiness, the other answers are sufficient. |
Best way to check if a list is empty | 53,513 | 1,615 | 2008-09-10T06:20:11Z | 34,558,732 | 10 | 2016-01-01T18:18:58Z | [
"python",
"list"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | From [documentation](https://docs.python.org/3.5/library/stdtypes.html#truth-value-testing) on truth value testing:
All values other than what is listed here are considered `True`
* `None`
* `False`
* zero of any numeric type, for example, `0`, `0.0`, `0j`.
* any empty sequence, for example, `''`, `()`, `[]`.
* any empty mapping, for example, `{}`.
* instances of user-defined classes, if the class defines a `__bool__()` or `__len__()` method, when that method returns the integer zero or bool value `False`.
As can be seen, empty list `[]` is *falsy*, so doing what would be done to a boolean value sounds most efficient:
```
if not a:
print('"a" is empty!')
``` |
What are some strategies to write python code that works in CPython, Jython and IronPython | 53,543 | 15 | 2008-09-10T07:04:43Z | 53,549 | 14 | 2008-09-10T07:07:59Z | [
"python",
"ironpython",
"jython",
"cpython"
] | Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation? | If you *do* find you need to write unique code for an environment, use pythons
```
import mymodule_jython as mymodule
import mymodule_cpython as mymodule
```
have this stuff in a simple module (''module\_importer''?) and write your code like this:
```
from module_importer import mymodule
```
This way, all you need to do is alter `module_importer.py` per platform. |
What are some strategies to write python code that works in CPython, Jython and IronPython | 53,543 | 15 | 2008-09-10T07:04:43Z | 55,312 | 10 | 2008-09-10T21:00:04Z | [
"python",
"ironpython",
"jython",
"cpython"
] | Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation? | @[Daren Thomas](#53549): I agree, but you should use the [platform module](http://docs.python.org/dev/library/platform.html#platform.python_implementation) to determine which interpreter you're running. |
Any good AJAX framework for Google App Engine apps? | 53,997 | 12 | 2008-09-10T13:12:07Z | 54,008 | 12 | 2008-09-10T13:14:54Z | [
"python",
"ajax",
"google-app-engine"
] | I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?
I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine? | As Google Web Toolkit is a [subset of Java](http://code.google.com/support/bin/answer.py?answer=54830&topic=10208) it works best when you Java at the backend too. Since Google App Engine is currently [Python only](http://code.google.com/appengine/kb/general.html#language) I think you'd have to do a lot of messing about to get your server and client to talk nicely to each other.
jQuery seems to be the most popular JavaScript library option in the [AJAX Tag at DjangoSnippets.com](http://www.djangosnippets.org/tags/ajax/?page=1).
**Edit:** The above is only true of Google App Engine applications written in Python. As Google App Engine now supports Java, GWT could now be a good choice for writing an AJAX front end. [Google even have a tutorial showing you how to do it.](http://code.google.com/webtoolkit/doc/latest/tutorial/appengine.html) |
Any good AJAX framework for Google App Engine apps? | 53,997 | 12 | 2008-09-10T13:12:07Z | 800,037 | 7 | 2009-04-28T22:08:08Z | [
"python",
"ajax",
"google-app-engine"
] | I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?
I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine? | A nice way is to use an AJAX library is to take advantage of [Google's AJAX Libraries API service](http://code.google.com/apis/ajaxlibs/). This is a bit faster and cleaner than downloading the JS and putting it in your `/static/` folder and doesn't eat into your disk quota.
In your javascript you would just put, for example:
```
google.load("jquery", "1.3.2");
```
and/or
```
google.load(google.load("dojo", "1.3.0");
```
Somewhere in your header you would put something like:
```
<script src="http://www.google.com/jsapi?key=your-key-here"></script>
```
And that's all you need to use Google's API libraries. |
What is the difference between old style and new style classes in Python? | 54,867 | 604 | 2008-09-10T18:01:27Z | 54,873 | 340 | 2008-09-10T18:02:43Z | [
"python",
"class",
"oop",
"types",
"new-style-class"
] | What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days? | From <http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes> :
> Up to Python 2.1, old-style classes were the only flavour available to the user. The concept of (old-style) class is unrelated to the concept of type: if `x` is an instance of an old-style class, then `x.__class__` designates the class of `x`, but `type(x)` is always `<type 'instance'>`. This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.
>
> **New-style classes were introduced in Python 2.2 to unify the concepts of class and type**. A new-style class is simply a user-defined type, no more, no less. If x is an instance of a new-style class, then `type(x)` is typically the same as `x.__class__` (although this is not guaranteed â a new-style class instance is permitted to override the value returned for `x.__class__`).
>
> **The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model**. It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of "descriptors", which enable computed properties.
>
> **For compatibility reasons, classes are still old-style by default**. New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the "top-level type" object if no other parent is needed. The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns. Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are "fixes" that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.
>
> **Python 3 only has new-style classes**. No matter if you subclass from `object` or not, classes are new-style in Python 3. It is however recommended that you still subclass from `object`. |
What is the difference between old style and new style classes in Python? | 54,867 | 604 | 2008-09-10T18:01:27Z | 1,203,997 | 220 | 2009-07-30T01:21:59Z | [
"python",
"class",
"oop",
"types",
"new-style-class"
] | What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days? | **Declaration-wise:**
New-style classes inherit from object, or from another new-style class.
```
class NewStyleClass(object):
pass
class AnotherNewStyleClass(NewStyleClass):
pass
```
Old-style classes don't.
```
class OldStyleClass():
pass
``` |
What is the difference between old style and new style classes in Python? | 54,867 | 604 | 2008-09-10T18:01:27Z | 3,228,045 | 29 | 2010-07-12T11:26:52Z | [
"python",
"class",
"oop",
"types",
"new-style-class"
] | What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days? | Old style classes are still marginally faster for attribute lookup. This is not usually important, but may be useful in performance-sensitive Python 2.x code:
```
In [3]: class A:
...: def __init__(self):
...: self.a = 'hi there'
...:
In [4]: class B(object):
...: def __init__(self):
...: self.a = 'hi there'
...:
In [6]: aobj = A()
In [7]: bobj = B()
In [8]: %timeit aobj.a
10000000 loops, best of 3: 78.7 ns per loop
In [10]: %timeit bobj.a
10000000 loops, best of 3: 86.9 ns per loop
``` |
What is the difference between old style and new style classes in Python? | 54,867 | 604 | 2008-09-10T18:01:27Z | 16,193,572 | 22 | 2013-04-24T13:41:26Z | [
"python",
"class",
"oop",
"types",
"new-style-class"
] | What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days? | Guido has written [The Inside Story on New-Style Classes](http://python-history.blogspot.com/2010/06/inside-story-on-new-style-classes.html), a really great article about new-style and old-style class in Python.
Python 3 has only new-style class, even if you write an 'old-style class', it is implicitly derived from `object`.
New-style classes have some advanced features lacking in old-style classes, such as `super` and the new [C3 mro](http://en.wikipedia.org/wiki/C3_linearization), some magical methods, etc. |
What is the difference between old style and new style classes in Python? | 54,867 | 604 | 2008-09-10T18:01:27Z | 19,273,761 | 8 | 2013-10-09T13:40:29Z | [
"python",
"class",
"oop",
"types",
"new-style-class"
] | What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days? | Here's a very practical, True/False difference. The only difference between the two versions of the following code is that in the second version Person inherits from object. Other than that the two versions are identical, but with different results :
1) old-style classes
```
class Person():
_names_cache = {}
def __init__(self,name):
self.name = name
def __new__(cls,name):
return cls._names_cache.setdefault(name,object.__new__(cls,name))
ahmed1 = Person("Ahmed")
ahmed2 = Person("Ahmed")
print ahmed1 is ahmed2
print ahmed1
print ahmed2
>>> False
<__main__.Person instance at 0xb74acf8c>
<__main__.Person instance at 0xb74ac6cc>
>>>
```
2) new-style classes
```
class Person(object):
_names_cache = {}
def __init__(self,name):
self.name = name
def __new__(cls,name):
return cls._names_cache.setdefault(name,object.__new__(cls,name))
ahmed1 = Person("Ahmed")
ahmed2 = Person("Ahmed")
print ahmed2 is ahmed1
print ahmed1
print ahmed2
>>> True
<__main__.Person object at 0xb74ac66c>
<__main__.Person object at 0xb74ac66c>
>>>
``` |
What is the difference between old style and new style classes in Python? | 54,867 | 604 | 2008-09-10T18:01:27Z | 19,950,198 | 126 | 2013-11-13T09:36:59Z | [
"python",
"class",
"oop",
"types",
"new-style-class"
] | What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days? | **Important behavior changes between old and new style classes**
* [super](http://stackoverflow.com/questions/576169/understanding-python-super-and-init-methods) added
* MRO changed (explained below)
* [descriptors](http://docs.python.org/2/howto/descriptor.html) added
* new style class objects cannot be raised unless derived from `Exception` (example below)
* [`__slots__`](http://docs.python.org/2/reference/datamodel.html#slots) added
## MRO (Method Resolution Order) changed
It was mentioned in other answers, but here goes a concrete example of the difference between classic MRO and C3 MRO (used in new style classes).
The question is the order in which attributes (which include methods and member variables) are searched for in multiple inheritance.
**Classic classes** do a depth first search from left to right. Stop on first match. They do not have the `__mro__` attribute.
```
class C: i = 0
class C1(C): pass
class C2(C): i = 2
class C12(C1, C2): pass
class C21(C2, C1): pass
assert C12().i == 0
assert C21().i == 2
try:
C12.__mro__
except AttributeError:
pass
else:
assert False
```
**New-style classes** MRO is more complicated to synthesize in a single English sentence. It is explained in detail [here](http://www.python.org/download/releases/2.3/mro/). One of its properties is that a Base class is only searched for once all its Derived classes have been. They have the `__mro__` attribute which shows the search order.
```
class C(object): i = 0
class C1(C): pass
class C2(C): i = 2
class C12(C1, C2): pass
class C21(C2, C1): pass
assert C12().i == 2
assert C21().i == 2
assert C12.__mro__ == (C12, C1, C2, C, object)
assert C21.__mro__ == (C21, C2, C1, C, object)
```
## New style class objects cannot be raised unless derived from `Exception`
Around Python 2.5 many classes could be raised, around Python 2.6 this was removed. On Python 2.7.3:
```
# OK, old:
class Old: pass
try:
raise Old()
except Old:
pass
else:
assert False
# TypeError, new not derived from `Exception`.
class New(object): pass
try:
raise New()
except TypeError:
pass
else:
assert False
# OK, derived from `Exception`.
class New(Exception): pass
try:
raise New()
except New:
pass
else:
assert False
# `'str'` is a new style object, so you can't raise it:
try:
raise 'str'
except TypeError:
pass
else:
assert False
``` |
In Python, how can you easily retrieve sorted items from a dictionary? | 55,180 | 11 | 2008-09-10T20:05:25Z | 55,193 | 16 | 2008-09-10T20:10:05Z | [
"python",
"sorting",
"dictionary",
"list"
] | Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added.
What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?
For example, you had this:
```
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
```
I want to print the associated values in the following sequence sorted by key:
```
this is a
this is b
this is c
``` | Do you mean that you need the values sorted by the value of the key?
In that case, this should do it:
```
for key in sorted(d):
print d[key]
```
**EDIT:** changed to use sorted(d) instead of sorted(d.keys()), thanks [Eli](http://stackoverflow.com/users/1694/eli-courtwright)! |
In Python, how can you easily retrieve sorted items from a dictionary? | 55,180 | 11 | 2008-09-10T20:05:25Z | 55,194 | 16 | 2008-09-10T20:10:51Z | [
"python",
"sorting",
"dictionary",
"list"
] | Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added.
What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?
For example, you had this:
```
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
```
I want to print the associated values in the following sequence sorted by key:
```
this is a
this is b
this is c
``` | Or shorter,
```
for key, value in sorted(d.items()):
print value
``` |
Python regular expression for HTML parsing (BeautifulSoup) | 55,391 | 9 | 2008-09-10T21:49:53Z | 55,404 | 8 | 2008-09-10T21:59:47Z | [
"python",
"regex",
"screen-scraping"
] | I want to grab the value of a hidden input field in HTML.
```
<input type="hidden" name="fooId" value="12-3456789-1111111111" />
```
I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format
```
<input type="hidden" name="fooId" value="**[id is here]**" />
```
Can someone provide an example in Python to parse the HTML for the value? | ```
import re
reg = re.compile('<input type="hidden" name="([^"]*)" value="<id>" />')
value = reg.search(inputHTML).group(1)
print 'Value is', value
``` |
Python regular expression for HTML parsing (BeautifulSoup) | 55,391 | 9 | 2008-09-10T21:49:53Z | 55,424 | 27 | 2008-09-10T22:16:24Z | [
"python",
"regex",
"screen-scraping"
] | I want to grab the value of a hidden input field in HTML.
```
<input type="hidden" name="fooId" value="12-3456789-1111111111" />
```
I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format
```
<input type="hidden" name="fooId" value="**[id is here]**" />
```
Can someone provide an example in Python to parse the HTML for the value? | For this particular case, BeautifulSoup is harder to write than a regex, but it is much more robust... I'm just contributing with the BeautifulSoup example, given that you already know which regexp to use :-)
```
from BeautifulSoup import BeautifulSoup
#Or retrieve it from the web, etc.
html_data = open('/yourwebsite/page.html','r').read()
#Create the soup object from the HTML data
soup = BeautifulSoup(html_data)
fooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag
value = fooId.attrs[2][1] #The value of the third attribute of the desired tag
#or index it directly via fooId['value']
``` |
Python regular expression for HTML parsing (BeautifulSoup) | 55,391 | 9 | 2008-09-10T21:49:53Z | 64,983 | 18 | 2008-09-15T17:35:44Z | [
"python",
"regex",
"screen-scraping"
] | I want to grab the value of a hidden input field in HTML.
```
<input type="hidden" name="fooId" value="12-3456789-1111111111" />
```
I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format
```
<input type="hidden" name="fooId" value="**[id is here]**" />
```
Can someone provide an example in Python to parse the HTML for the value? | I agree with Vinko [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) is the way to go. However I suggest using `fooId['value']` to [get the attribute](http://www.crummy.com/software/BeautifulSoup/documentation.html#The%20attributes%20of%20Tags) rather than relying on value being the third attribute.
```
from BeautifulSoup import BeautifulSoup
#Or retrieve it from the web, etc.
html_data = open('/yourwebsite/page.html','r').read()
#Create the soup object from the HTML data
soup = BeautifulSoup(html_data)
fooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag
value = fooId['value'] #The value attribute
``` |
XML writing tools for Python | 56,229 | 34 | 2008-09-11T10:35:37Z | 56,269 | 28 | 2008-09-11T11:04:15Z | [
"python",
"xml",
"xhtml"
] | I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?
This is similar to what I'm actually doing:
```
import xml.etree.ElementTree as ET
root = ET.Element('html')
head = ET.SubElement(root,'head')
script = ET.SubElement(head,'script')
script.set('type','text/javascript')
script.text = "var a = 'I love á letters'"
body = ET.SubElement(root,'body')
h1 = ET.SubElement(body,'h1')
h1.text = "And I like the fact that 3 > 1"
tree = ET.ElementTree(root)
tree.write('foo.xhtml')
# more foo.xhtml
<html><head><script type="text/javascript">var a = 'I love &aacute;
letters'</script></head><body><h1>And I like the fact that 3 > 1</h1>
</body></html>
``` | Another way is using the [E Factory](http://codespeak.net/lxml/tutorial.html#the-e-factory) builder from lxml (available in [Elementtree](http://effbot.org/zone/element-builder.htm) too)
```
>>> from lxml import etree
>>> from lxml.builder import E
>>> def CLASS(*args): # class is a reserved word in Python
... return {"class":' '.join(args)}
>>> html = page = (
... E.html( # create an Element called "html"
... E.head(
... E.title("This is a sample document")
... ),
... E.body(
... E.h1("Hello!", CLASS("title")),
... E.p("This is a paragraph with ", E.b("bold"), " text in it!"),
... E.p("This is another paragraph, with a", "\n ",
... E.a("link", href="http://www.python.org"), "."),
... E.p("Here are some reserved characters: <spam&egg>."),
... etree.XML("<p>And finally an embedded XHTML fragment.</p>"),
... )
... )
... )
>>> print(etree.tostring(page, pretty_print=True))
<html>
<head>
<title>This is a sample document</title>
</head>
<body>
<h1 class="title">Hello!</h1>
<p>This is a paragraph with <b>bold</b> text in it!</p>
<p>This is another paragraph, with a
<a href="http://www.python.org">link</a>.</p>
<p>Here are some reservered characters: <spam&egg>.</p>
<p>And finally an embedded XHTML fragment.</p>
</body>
</html>
``` |
XML writing tools for Python | 56,229 | 34 | 2008-09-11T10:35:37Z | 56,470 | 10 | 2008-09-11T12:53:06Z | [
"python",
"xml",
"xhtml"
] | I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?
This is similar to what I'm actually doing:
```
import xml.etree.ElementTree as ET
root = ET.Element('html')
head = ET.SubElement(root,'head')
script = ET.SubElement(head,'script')
script.set('type','text/javascript')
script.text = "var a = 'I love á letters'"
body = ET.SubElement(root,'body')
h1 = ET.SubElement(body,'h1')
h1.text = "And I like the fact that 3 > 1"
tree = ET.ElementTree(root)
tree.write('foo.xhtml')
# more foo.xhtml
<html><head><script type="text/javascript">var a = 'I love &aacute;
letters'</script></head><body><h1>And I like the fact that 3 > 1</h1>
</body></html>
``` | I assume that you're actually creating an XML DOM tree, because you want to validate that what goes into this file is valid XML, since otherwise you'd just write a static string to a file. If validating your output is indeed your goal, then I'd suggest
```
from xml.dom.minidom import parseString
doc = parseString("""<html>
<head>
<script type="text/javascript">
var a = 'I love &aacute; letters'
</script>
</head>
<body>
<h1>And I like the fact that 3 > 1</h1>
</body>
</html>""")
with open("foo.xhtml", "w") as f:
f.write( doc.toxml() )
```
This lets you just write the XML you want to output, validate that it's correct (since parseString will raise an exception if it's invalid) and have your code look much nicer.
Presumably you're not just writing the same static XML every time and want some substitution. In this case I'd have lines like
```
var a = '%(message)s'
```
and then use the % operator to do the substitution, like
```
</html>""" % {"message": "I love &aacute; letters"})
``` |
XML writing tools for Python | 56,229 | 34 | 2008-09-11T10:35:37Z | 3,098,902 | 24 | 2010-06-23T04:16:17Z | [
"python",
"xml",
"xhtml"
] | I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?
This is similar to what I'm actually doing:
```
import xml.etree.ElementTree as ET
root = ET.Element('html')
head = ET.SubElement(root,'head')
script = ET.SubElement(head,'script')
script.set('type','text/javascript')
script.text = "var a = 'I love á letters'"
body = ET.SubElement(root,'body')
h1 = ET.SubElement(body,'h1')
h1.text = "And I like the fact that 3 > 1"
tree = ET.ElementTree(root)
tree.write('foo.xhtml')
# more foo.xhtml
<html><head><script type="text/javascript">var a = 'I love &aacute;
letters'</script></head><body><h1>And I like the fact that 3 > 1</h1>
</body></html>
``` | There's always [SimpleXMLWriter](http://effbot.org/zone/xml-writer.htm), part of the ElementTree toolkit. The interface is dead simple.
Here's an example:
```
from elementtree.SimpleXMLWriter import XMLWriter
import sys
w = XMLWriter(sys.stdout)
html = w.start("html")
w.start("head")
w.element("title", "my document")
w.element("meta", name="generator", value="my application 1.0")
w.end()
w.start("body")
w.element("h1", "this is a heading")
w.element("p", "this is a paragraph")
w.start("p")
w.data("this is ")
w.element("b", "bold")
w.data(" and ")
w.element("i", "italic")
w.data(".")
w.end("p")
w.close(html)
``` |
XML writing tools for Python | 56,229 | 34 | 2008-09-11T10:35:37Z | 7,060,046 | 7 | 2011-08-14T22:09:27Z | [
"python",
"xml",
"xhtml"
] | I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?
This is similar to what I'm actually doing:
```
import xml.etree.ElementTree as ET
root = ET.Element('html')
head = ET.SubElement(root,'head')
script = ET.SubElement(head,'script')
script.set('type','text/javascript')
script.text = "var a = 'I love á letters'"
body = ET.SubElement(root,'body')
h1 = ET.SubElement(body,'h1')
h1.text = "And I like the fact that 3 > 1"
tree = ET.ElementTree(root)
tree.write('foo.xhtml')
# more foo.xhtml
<html><head><script type="text/javascript">var a = 'I love &aacute;
letters'</script></head><body><h1>And I like the fact that 3 > 1</h1>
</body></html>
``` | <https://github.com/galvez/xmlwitch>:
```
import xmlwitch
xml = xmlwitch.Builder(version='1.0', encoding='utf-8')
with xml.feed(xmlns='http://www.w3.org/2005/Atom'):
xml.title('Example Feed')
xml.updated('2003-12-13T18:30:02Z')
with xml.author:
xml.name('John Doe')
xml.id('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6')
with xml.entry:
xml.title('Atom-Powered Robots Run Amok')
xml.id('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a')
xml.updated('2003-12-13T18:30:02Z')
xml.summary('Some text.')
print(xml)
``` |
Anyone used Dabo for a medium-big project? | 56,417 | 18 | 2008-09-11T12:29:09Z | 106,464 | 24 | 2008-09-19T23:55:08Z | [
"python",
"erp",
"dabo"
] | We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client. We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects?
Thanks for your time! | I'm one of the authors of the Dabo framework. One of our users pointed out to me the extremely negative answer you received, and so I thought I had better chime in and clear up some of the incorrect assumptions in the first reply.
Dabo is indeed well-known in the Python community. I have presented it at 3 of the last 4 US PyCons, and we have several hundred users who subscribe to our email lists. Our website (<http://dabodev.com>) has not had any service interruptions; I don't know why the first responder claimed to have trouble. Support is through our email lists, and we pride ourselves on helping people quickly and efficiently. Many of the newbie questions help us to identify places where our docs are lacking, so we strongly encourage newcomers to ask questions!
Dabo has been around for 4 years. The fact that it is still a few days away from a 0.9 release is more of a reflection of the rather conservative version numbering of my partner, Paul McNett, than any instabilities in the framework. I know of Dabo apps that have been in production since 2006; I have used it for my own projects since 2004. Whatever importance you attach to release numbers, we are at revision 4522, with consistent work being done to add more and more stuff to the framework; refactor and streamline some of the older code, and yes, clean up some bugs.
Please sign up for our free email support list:
<http://leafe.com/mailman/listinfo/dabo-users>
...and ask any questions you may have about Dabo there. Not many people have discovered Stack Overflow yet, so I wouldn't expect very informed answers here yet. There are several regular contributors there who use Dabo on a daily basis, and are usually more than happy to offer their opinions and their help. |
round() in Python doesn't seem to be rounding properly | 56,820 | 71 | 2008-09-11T15:08:09Z | 56,833 | 66 | 2008-09-11T15:11:41Z | [
"python",
"floating-point"
] | The documentation for the [round()](http://docs.python.org/lib/built-in-funcs.html) function states that you pass it a number, and the positions past the decimal to round. Thus it *should* do this:
```
n = 5.59
round(n, 1) # 5.6
```
But, in actuality, good old floating point weirdness creeps in and you get:
```
5.5999999999999996
```
For the purposes of UI, I need to display `5.6`. I poked around the Internet and found some [documentation](http://mail.python.org/pipermail/python-list/2005-September/340383.html) that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. [See here also](http://www.python.org/doc/2.5.1/tut/node16.html).
Short of creating my own round library, is there any way around this? | can't help the way it's stored, but at least formatting works correctly:
```
'%.1f' % round(n, 1) # gives you '5.6'
``` |
round() in Python doesn't seem to be rounding properly | 56,820 | 71 | 2008-09-11T15:08:09Z | 56,844 | 9 | 2008-09-11T15:13:28Z | [
"python",
"floating-point"
] | The documentation for the [round()](http://docs.python.org/lib/built-in-funcs.html) function states that you pass it a number, and the positions past the decimal to round. Thus it *should* do this:
```
n = 5.59
round(n, 1) # 5.6
```
But, in actuality, good old floating point weirdness creeps in and you get:
```
5.5999999999999996
```
For the purposes of UI, I need to display `5.6`. I poked around the Internet and found some [documentation](http://mail.python.org/pipermail/python-list/2005-September/340383.html) that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. [See here also](http://www.python.org/doc/2.5.1/tut/node16.html).
Short of creating my own round library, is there any way around this? | You get '5.6' if you do `str(round(n, 1))` instead of just `round(n, 1)`. |
round() in Python doesn't seem to be rounding properly | 56,820 | 71 | 2008-09-11T15:08:09Z | 56,850 | 81 | 2008-09-11T15:14:22Z | [
"python",
"floating-point"
] | The documentation for the [round()](http://docs.python.org/lib/built-in-funcs.html) function states that you pass it a number, and the positions past the decimal to round. Thus it *should* do this:
```
n = 5.59
round(n, 1) # 5.6
```
But, in actuality, good old floating point weirdness creeps in and you get:
```
5.5999999999999996
```
For the purposes of UI, I need to display `5.6`. I poked around the Internet and found some [documentation](http://mail.python.org/pipermail/python-list/2005-September/340383.html) that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. [See here also](http://www.python.org/doc/2.5.1/tut/node16.html).
Short of creating my own round library, is there any way around this? | Formatting works correctly even without having to round:
```
"%.1f" % n
``` |
round() in Python doesn't seem to be rounding properly | 56,820 | 71 | 2008-09-11T15:08:09Z | 57,704 | 15 | 2008-09-11T21:27:35Z | [
"python",
"floating-point"
] | The documentation for the [round()](http://docs.python.org/lib/built-in-funcs.html) function states that you pass it a number, and the positions past the decimal to round. Thus it *should* do this:
```
n = 5.59
round(n, 1) # 5.6
```
But, in actuality, good old floating point weirdness creeps in and you get:
```
5.5999999999999996
```
For the purposes of UI, I need to display `5.6`. I poked around the Internet and found some [documentation](http://mail.python.org/pipermail/python-list/2005-September/340383.html) that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. [See here also](http://www.python.org/doc/2.5.1/tut/node16.html).
Short of creating my own round library, is there any way around this? | `round(5.59, 1)` is working fine. The problem is that 5.6 cannot be represented exactly in binary floating point.
```
>>> 5.6
5.5999999999999996
>>>
```
As Vinko says, you can use string formatting to do rounding for display.
Python has a [module for decimal arithmetic](http://docs.python.org/lib/module-decimal.html) if you need that. |
round() in Python doesn't seem to be rounding properly | 56,820 | 71 | 2008-09-11T15:08:09Z | 15,398,691 | 11 | 2013-03-13T23:48:33Z | [
"python",
"floating-point"
] | The documentation for the [round()](http://docs.python.org/lib/built-in-funcs.html) function states that you pass it a number, and the positions past the decimal to round. Thus it *should* do this:
```
n = 5.59
round(n, 1) # 5.6
```
But, in actuality, good old floating point weirdness creeps in and you get:
```
5.5999999999999996
```
For the purposes of UI, I need to display `5.6`. I poked around the Internet and found some [documentation](http://mail.python.org/pipermail/python-list/2005-September/340383.html) that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. [See here also](http://www.python.org/doc/2.5.1/tut/node16.html).
Short of creating my own round library, is there any way around this? | If you use the Decimal module you can approximate without the use of the 'round' function. Here is what I've been using for rounding especially when writing monetary applications:
```
Decimal(str(16.2)).quantize(Decimal('.01'), rounding=ROUND_UP)
```
This will return a Decimal Number which is 16.20. |
Convert XML/HTML Entities into Unicode String in Python | 57,708 | 60 | 2008-09-11T21:28:46Z | 57,745 | 7 | 2008-09-11T21:52:28Z | [
"python",
"html",
"entities"
] | I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?
For example:
I get back:
```
ǎ
```
which represents an "Ç" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value `u'\u01ce'` | You could find an answer here -- [Getting international characters from a web page?](http://stackoverflow.com/questions/53224/getting-international-characters-from-a-web-page#53246)
**EDIT**: It seems like `BeautifulSoup` doesn't convert entities written in hexadecimal form. It can be fixed:
```
import copy, re
from BeautifulSoup import BeautifulSoup
hexentityMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE)
# replace hexadecimal character reference by decimal one
hexentityMassage += [(re.compile('&#x([^;]+);'),
lambda m: '&#%d;' % int(m.group(1), 16))]
def convert(html):
return BeautifulSoup(html,
convertEntities=BeautifulSoup.HTML_ENTITIES,
markupMassage=hexentityMassage).contents[0].string
html = '<html>ǎǎ</html>'
print repr(convert(html))
# u'\u01ce\u01ce'
```
**EDIT**:
[`unescape()`](http://effbot.org/zone/re-sub.htm#unescape-html) function mentioned by [@dF](http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python/58125#58125) which uses `htmlentitydefs` standard module and `unichr()` might be more appropriate in this case. |
Convert XML/HTML Entities into Unicode String in Python | 57,708 | 60 | 2008-09-11T21:28:46Z | 57,877 | 18 | 2008-09-11T23:09:08Z | [
"python",
"html",
"entities"
] | I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?
For example:
I get back:
```
ǎ
```
which represents an "Ç" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value `u'\u01ce'` | Use the builtin `unichr` -- BeautifulSoup isn't necessary:
```
>>> entity = 'ǎ'
>>> unichr(int(entity[3:],16))
u'\u01ce'
``` |
Convert XML/HTML Entities into Unicode String in Python | 57,708 | 60 | 2008-09-11T21:28:46Z | 58,125 | 55 | 2008-09-12T01:40:41Z | [
"python",
"html",
"entities"
] | I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?
For example:
I get back:
```
ǎ
```
which represents an "Ç" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value `u'\u01ce'` | Python has the [htmlentitydefs](https://docs.python.org/2/library/htmllib.html#module-htmlentitydefs) module, but this doesn't include a function to unescape HTML entities.
Python developer Fredrik Lundh (author of elementtree, among other things) has such a function [on his website](http://effbot.org/zone/re-sub.htm#unescape-html), which works with decimal, hex and named entities:
```
import re, htmlentitydefs
##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.
def unescape(text):
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
``` |
Convert XML/HTML Entities into Unicode String in Python | 57,708 | 60 | 2008-09-11T21:28:46Z | 9,216,990 | 14 | 2012-02-09T18:55:48Z | [
"python",
"html",
"entities"
] | I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?
For example:
I get back:
```
ǎ
```
which represents an "Ç" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value `u'\u01ce'` | An alternative, if you have lxml:
```
>>> import lxml.html
>>> lxml.html.fromstring('ǎ').text
u'\u01ce'
``` |
Convert XML/HTML Entities into Unicode String in Python | 57,708 | 60 | 2008-09-11T21:28:46Z | 12,614,706 | 45 | 2012-09-27T05:34:44Z | [
"python",
"html",
"entities"
] | I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?
For example:
I get back:
```
ǎ
```
which represents an "Ç" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value `u'\u01ce'` | The standard libâs very own HTMLParser has an undocumented function unescape() which does exactly what you think it does:
```
import HTMLParser
h = HTMLParser.HTMLParser()
h.unescape('© 2010') # u'\xa9 2010'
h.unescape('© 2010') # u'\xa9 2010'
``` |
Does re.compile() or any given Python library call throw an exception? | 58,119 | 11 | 2008-09-12T01:35:33Z | 58,129 | 9 | 2008-09-12T01:42:38Z | [
"python",
"regex",
"exception"
] | I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are? | Well, `re.compile` certainly may:
```
>>> import re
>>> re.compile('he(lo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python25\lib\re.py", line 180, in compile
return _compile(pattern, flags)
File "C:\Python25\lib\re.py", line 233, in _compile
raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis
```
[The documentation](http://docs.python.org/lib/node46.html#l2h-408) does support this, in a roundabout way - check the bottom of the "Module Contents" page for (brief) description of the `error` exception.
Unfortunately, I don't have any answer to the general question. I suppose the documentation for the various modules varies in quality and thoroughness. If there were particular modules you were interested in, you might be able to [decompile](http://www.depython.net/) them (if written in Python) or even [look at the source](http://www.python.org/download/), if they're in the standard library. |
How do I get the external IP of a socket in Python? | 58,294 | 8 | 2008-09-12T04:21:51Z | 58,296 | 7 | 2008-09-12T04:23:53Z | [
"python",
"sockets"
] | When I call `socket.getsockname()` on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this? | This isn't possible without cooperation from an external server, because there could be any number of NATs between you and the other computer. If it's a custom protocol, you could ask the other system to report what address it's connected to. |
Can I document Python code with doxygen (and does it make sense)? | 58,622 | 49 | 2008-09-12T10:26:40Z | 58,701 | 30 | 2008-09-12T11:11:03Z | [
"python",
"documentation",
"doxygen",
"docstring",
"python-sphinx"
] | I like doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /\* .. \*/ comments and also has its own self-documentation facility which seems to be the pythonic way to document.
Can I just use doxygen? Anything particular to be aware of?
I have done some coding in Python but so far only on small projects where I was to lazy to document at all (yeah, I know ... but let's just pretend that's OK for now). | This is [documented on the doxygen website](http://www.stack.nl/~dimitri/doxygen/docblocks.html#pythonblocks), but to summarize here:
You can use doxygen to document your Python code. You can either use the Python documentation string syntax:
```
"""@package docstring
Documentation for this module.
More details.
"""
def func():
"""Documentation for a function.
More details.
"""
pass
```
In which case the comments will be extracted by doxygen, but you won't be able to use any of the [special doxygen commands](http://www.stack.nl/~dimitri/doxygen/commands.html#cmd_intro).
**Or** you can (similar to C-style languages under doxygen) double up the comment marker (`#`) on the first line before the member:
```
## @package pyexample
# Documentation for this module.
#
# More details.
## Documentation for a function.
#
# More details.
def func():
pass
```
In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting `OPTMIZE_OUTPUT_JAVA` to `YES`.
Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands? |
Can I document Python code with doxygen (and does it make sense)? | 58,622 | 49 | 2008-09-12T10:26:40Z | 59,018 | 11 | 2008-09-12T13:48:59Z | [
"python",
"documentation",
"doxygen",
"docstring",
"python-sphinx"
] | I like doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /\* .. \*/ comments and also has its own self-documentation facility which seems to be the pythonic way to document.
Can I just use doxygen? Anything particular to be aware of?
I have done some coding in Python but so far only on small projects where I was to lazy to document at all (yeah, I know ... but let's just pretend that's OK for now). | An other very good documentation tool is [sphinx](http://sphinx.pocoo.org/). It will be used for the upcoming python 2.6 [documentation](http://docs.python.org/dev/) and is used by [django](http://docs.djangoproject.com/en/dev/) and a lot of other python projects.
From the sphinx website:
* **Output formats**: HTML (including Windows HTML Help) and LaTeX, for printable PDF versions
* **Extensive cross-references**: semantic markup and automatic links for functions, classes, glossary terms and similar pieces of information
* **Hierarchical structure**: easy definition of a document tree, with automatic links to siblings, parents and children
* **Automatic indices**: general index as well as a module index
* **Code handling**: automatic highlighting using the Pygments highlighter
* **Extensions**: automatic testing of code snippets, inclusion of docstrings from Python modules, and more |
Can I document Python code with doxygen (and does it make sense)? | 58,622 | 49 | 2008-09-12T10:26:40Z | 59,955 | 18 | 2008-09-12T21:04:48Z | [
"python",
"documentation",
"doxygen",
"docstring",
"python-sphinx"
] | I like doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /\* .. \*/ comments and also has its own self-documentation facility which seems to be the pythonic way to document.
Can I just use doxygen? Anything particular to be aware of?
I have done some coding in Python but so far only on small projects where I was to lazy to document at all (yeah, I know ... but let's just pretend that's OK for now). | Sphinx is mainly a tool for formatting docs written independently from the source code, as I understand it.
For generating API docs from Python docstrings, the leading tools are [pdoc](https://github.com/BurntSushi/pdoc) and [pydoctor](https://launchpad.net/pydoctor). Here's pydoctor's generated API docs for [Twisted](http://twistedmatrix.com/documents/current/api) and [Bazaar](http://starship.python.net/crew/mwh/bzrlibapi/).
Of course, if you just want to have a look at the docstrings while you're working on stuff, there's the "[pydoc](https://docs.python.org/2/library/pydoc.html)" command line tool and as well as the `help()` function available in the interactive interpreter. |
Can I document Python code with doxygen (and does it make sense)? | 58,622 | 49 | 2008-09-12T10:26:40Z | 497,322 | 48 | 2009-01-30T21:30:02Z | [
"python",
"documentation",
"doxygen",
"docstring",
"python-sphinx"
] | I like doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /\* .. \*/ comments and also has its own self-documentation facility which seems to be the pythonic way to document.
Can I just use doxygen? Anything particular to be aware of?
I have done some coding in Python but so far only on small projects where I was to lazy to document at all (yeah, I know ... but let's just pretend that's OK for now). | The [doxypy](https://pypi.python.org/pypi/doxypy/) input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well. |
How would you design a very "Pythonic" UI framework? | 58,711 | 11 | 2008-09-12T11:18:04Z | 58,917 | 7 | 2008-09-12T13:13:57Z | [
"python",
"user-interface",
"frameworks"
] | I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:
```
Shoes.app do
t = para "Not clicked!"
button "The Label" do
alert "You clicked the button!" # when clicked, make an alert
t.replace "Clicked!" # ..and replace the label's text
end
end
```
This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C\* library (In the case of GTK, Tk, wx, QT etc etc)
Shoes takes things from web devlopment (like `#f0c2f0` style colour notation, CSS layout techniques, like `:margin => 10`), and from ruby (extensively using blocks in sensible ways)
Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:
```
def Shoeless(Shoes.app):
self.t = para("Not clicked!")
def on_click_func(self):
alert("You clicked the button!")
self.t.replace("clicked!")
b = button("The label", click=self.on_click_func)
```
No where near as clean, and wouldn't be *nearly* as flexible, and I'm not even sure if it would be implementable.
Using decorators seems like an interesting way to map blocks of code to a specific action:
```
class BaseControl:
def __init__(self):
self.func = None
def clicked(self, func):
self.func = func
def __call__(self):
if self.func is not None:
self.func()
class Button(BaseControl):
pass
class Label(BaseControl):
pass
# The actual applications code (that the end-user would write)
class MyApp:
ok = Button()
la = Label()
@ok.clicked
def clickeryHappened():
print "OK Clicked!"
if __name__ == '__main__':
a = MyApp()
a.ok() # trigger the clicked action
```
Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.
The scope of various stuff (say, the `la` label in the above example) could be rather complicated, but it seems doable in a fairly neat manner.. | You could actually pull this off, but it would require using metaclasses, which are *deep* magic (there be dragons). If you want an intro to metaclasses, there's a series of [articles from IBM](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) which manage to introduce the ideas without melting your brain.
The source code from an ORM like SQLObject might help, too, since it uses this same kind of declarative syntax. |
How to retrieve an element from a set without removing it? | 59,825 | 154 | 2008-09-12T19:58:33Z | 59,841 | 197 | 2008-09-12T20:08:10Z | [
"python",
"set"
] | Suppose the following:
```
>>>s = set([1, 2, 3])
```
How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.
Quick and dirty:
```
>>>elem = s.pop()
>>>s.add(elem)
```
But do you know of a better way? Ideally in constant time. | Two options that don't require copying the whole set:
```
for e in s:
break
# e is now an element from s
```
Or...
```
e = next(iter(s))
```
But in general, sets don't support indexing or slicing. |
How to retrieve an element from a set without removing it? | 59,825 | 154 | 2008-09-12T19:58:33Z | 60,027 | 15 | 2008-09-12T21:43:27Z | [
"python",
"set"
] | Suppose the following:
```
>>>s = set([1, 2, 3])
```
How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.
Quick and dirty:
```
>>>elem = s.pop()
>>>s.add(elem)
```
But do you know of a better way? Ideally in constant time. | Since you want a random element, this will also work:
```
>>> import random
>>> s = set([1,2,3])
>>> random.sample(s, 1)
[2]
```
The documentation doesn't seem to mention performance of `random.sample`. From a really quick empirical test with a huge list and a huge set, it seems to be constant time for a list but not for the set. Also, iteration over a set isn't random; the order is undefined but predictable:
```
>>> list(set(range(10))) == range(10)
True
```
If randomness is important and you need a bunch of elements in constant time (large sets), I'd use `random.sample` and convert to a list first:
```
>>> lst = list(s) # once, O(len(s))?
...
>>> e = random.sample(lst, 1)[0] # constant time
``` |
How to retrieve an element from a set without removing it? | 59,825 | 154 | 2008-09-12T19:58:33Z | 60,233 | 37 | 2008-09-13T01:07:38Z | [
"python",
"set"
] | Suppose the following:
```
>>>s = set([1, 2, 3])
```
How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.
Quick and dirty:
```
>>>elem = s.pop()
>>>s.add(elem)
```
But do you know of a better way? Ideally in constant time. | Least code would be:
```
>>> s = set([1, 2, 3])
>>> list(s)[0]
1
```
Obviously this would create a new list which contains each member of the set, so not great if your set is very large. |
How to retrieve an element from a set without removing it? | 59,825 | 154 | 2008-09-12T19:58:33Z | 1,612,654 | 28 | 2009-10-23T10:47:49Z | [
"python",
"set"
] | Suppose the following:
```
>>>s = set([1, 2, 3])
```
How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.
Quick and dirty:
```
>>>elem = s.pop()
>>>s.add(elem)
```
But do you know of a better way? Ideally in constant time. | To provide some timing figures behind the different approaches, consider the following code.
*The get() is my custom addition to Python's setobject.c, being just a pop() without removing the element.*
```
from timeit import *
stats = ["for i in xrange(1000): iter(s).next() ",
"for i in xrange(1000): \n\tfor x in s: \n\t\tbreak",
"for i in xrange(1000): s.add(s.pop()) ",
"for i in xrange(1000): s.get() "]
for stat in stats:
t = Timer(stat, setup="s=set(range(100))")
try:
print "Time for %s:\t %f"%(stat, t.timeit(number=1000))
except:
t.print_exc()
```
The output is:
```
$ ./test_get.py
Time for for i in xrange(1000): iter(s).next() : 0.433080
Time for for i in xrange(1000):
for x in s:
break: 0.148695
Time for for i in xrange(1000): s.add(s.pop()) : 0.317418
Time for for i in xrange(1000): s.get() : 0.146673
```
This means that the ***for/break*** solution is the fastest (sometimes faster than the custom get() solution). |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 60,211 | 616 | 2008-09-13T00:38:24Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | You could use a dictionary:
```
def f(x):
return {
'a': 1,
'b': 2,
}[x]
``` |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 60,215 | 156 | 2008-09-13T00:41:46Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | I've always liked doing it this way
```
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)
```
[From here](http://blog.simonwillison.net/post/57956755106/switch) |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 60,236 | 127 | 2008-09-13T01:10:58Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | In addition to the dictionary methods (which I really like, BTW), you can also use if-elif-else to obtain the switch/case/default functionality:
```
if x == 'a':
# Do the thing
elif x == 'b':
# Do the other thing
if x in 'bc':
# Fall-through by not using elif, but now the default case includes case 'a'!
elif x in 'xyz':
# Do yet another thing
else:
# Do the default
```
This of course is not identical to switch/case - you cannot have fall-through as easily as leaving off the break; statement, but you can have a more complicated test. Its formatting is nicer than a series of nested ifs, even though functionally that's what it is closer to. |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 60,243 | 32 | 2008-09-13T01:26:26Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | There's a pattern that I learned from Twisted Python code.
```
class SMTP:
def lookupMethod(self, command):
return getattr(self, 'do_' + command.upper(), None)
def do_HELO(self, rest):
return 'Howdy ' + rest
def do_QUIT(self, rest):
return 'Bye'
SMTP().lookupMethod('HELO')('foo.bar.com') # => 'Howdy foo.bar.com'
SMTP().lookupMethod('QUIT')('') # => 'Bye'
```
You can use it any time you need to dispatch on a token and execute extended piece of code. In a state machine you would have `state_` methods, and dispatch on `self.state`. This switch can be cleanly extended by inheriting from base class and defining your own `do_` methods. Often times you won't even have `do_` methods in the base class.
*Edit: how exactly is that used*
In case of SMTP you will receive `HELO` from the wire. The relevant code (from `twisted/mail/smtp.py`, modified for our case) looks like this
```
class SMTP:
# ...
def do_UNKNOWN(self, rest):
raise NotImplementedError, 'received unknown command'
def state_COMMAND(self, line):
line = line.strip()
parts = line.split(None, 1)
if parts:
method = self.lookupMethod(parts[0]) or self.do_UNKNOWN
if len(parts) == 2:
return method(parts[1])
else:
return method('')
else:
raise SyntaxError, 'bad syntax'
SMTP().state_COMMAND(' HELO foo.bar.com ') # => Howdy foo.bar.com
```
You'll receive `' HELO foo.bar.com '` (or you might get `'QUIT'` or `'RCPT TO: foo'`). This is tokenized into `parts` as `['HELO', 'foo.bar.com']`. The actual method lookup name is taken from `parts[0]`.
(The original method is also called `state_COMMAND`, because it uses the same pattern to implement a state machine, i.e. `getattr(self, 'state_' + self.mode)`) |
Replacements for switch statement in Python? | 60,208 | 788 | 2008-09-13T00:36:30Z | 102,990 | 9 | 2008-09-19T15:37:15Z | [
"python",
"switch-statement"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | expanding on the "dict as switch" idea. if you want to use a default value for your switch:
```
def f(x):
try:
return {
'a': 1,
'b': 2,
}[x]
except KeyError:
return 'default'
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.