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 |
|---|---|---|---|---|---|---|---|---|---|
Finding what methods an object has | 34,439 | 159 | 2008-08-29T15:05:17Z | 34,481 | 11 | 2008-08-29T15:47:04Z | [
"python",
"introspection"
] | Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?
Or,
if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called? | On top of the more direct answers, I'd be remiss if I didn't mention [iPython](http://ipython.scipy.org/).
Hit 'tab' to see the available methods, with autocompletion.
And once you've found a method, try:
```
help(object.method)
```
to see the pydocs, method signature, etc.
Ahh... [REPL](http://en.wikipedia.org/wiki/REPL). |
Finding what methods an object has | 34,439 | 159 | 2008-08-29T15:05:17Z | 20,100,900 | 21 | 2013-11-20T16:06:27Z | [
"python",
"introspection"
] | Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?
Or,
if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called? | The simplest method is to use dir(objectname). It will display all the methods available for that object. Cool trick. |
Validate (X)HTML in Python | 35,538 | 21 | 2008-08-30T01:15:32Z | 35,543 | 7 | 2008-08-30T01:20:52Z | [
"python",
"html",
"validation",
"xhtml"
] | What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app. | XHTML is easy, use [lxml](http://lxml.de/validation.html).
HTML is harder, since there's traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself through a validator, yikes). The easiest solution would be to execute external applications such as [nsgmls](http://www.jclark.com/sp/) or [OpenJade](http://openjade.sourceforge.net/), and then parse their output. |
Validate (X)HTML in Python | 35,538 | 21 | 2008-08-30T01:15:32Z | 646,877 | 11 | 2009-03-14T22:42:12Z | [
"python",
"html",
"validation",
"xhtml"
] | What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app. | Starting with html5, you can try to use [html5lib](http://code.google.com/p/html5lib/).
You can also decide to install the HTML validator locally and create a client to request the validation.
Here I had made a program to validate a list of urls in a txt file. I was just checking the HEAD to get the validation status, but if you do a GET you would get the full results. Look at the API of the validator, there are plenty of options for it.
```
import httplib2
import time
h = httplib2.Http(".cache")
f = open("urllistfile.txt", "r")
urllist = f.readlines()
f.close()
for url in urllist:
# wait 10 seconds before the next request - be nice with the validator
time.sleep(10)
resp= {}
url = url.strip()
urlrequest = "http://qa-dev.w3.org/wmvs/HEAD/check?doctype=HTML5&uri="+url
try:
resp, content = h.request(urlrequest, "HEAD")
if resp['x-w3c-validator-status'] == "Abort":
print url, "FAIL"
else:
print url, resp['x-w3c-validator-status'], resp['x-w3c-validator-errors'], resp['x-w3c-validator-warnings']
except:
pass
``` |
Validate (X)HTML in Python | 35,538 | 21 | 2008-08-30T01:15:32Z | 1,279,293 | 18 | 2009-08-14T18:04:38Z | [
"python",
"html",
"validation",
"xhtml"
] | What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app. | <http://countergram.com/software/pytidylib> is a nice python binding for HTML Tidy. Their example:
```
from tidylib import tidy_document
document, errors = tidy_document('''<p>fõo <img src="bar.jpg">''',
options={'numeric-entities':1})
print document
print errors
``` |
Validate (X)HTML in Python | 35,538 | 21 | 2008-08-30T01:15:32Z | 10,519,634 | 14 | 2012-05-09T15:53:46Z | [
"python",
"html",
"validation",
"xhtml"
] | What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app. | I think the most elegant way it to invoke the W3C Validation Service at
```
http://validator.w3.org/
```
programmatically. Few people know that you do not have to screen-scrape the results in order to get the results, because the service returns non-standard HTTP header paramaters
```
X-W3C-Validator-Recursion: 1
X-W3C-Validator-Status: Invalid (or Valid)
X-W3C-Validator-Errors: 6
X-W3C-Validator-Warnings: 0
```
for indicating the validity and the number of errors and warnings.
For instance, the command line
```
curl -I "http://validator.w3.org/check?uri=http%3A%2F%2Fwww.stalsoft.com"
```
returns
```
HTTP/1.1 200 OK
Date: Wed, 09 May 2012 15:23:58 GMT
Server: Apache/2.2.9 (Debian) mod_python/3.3.1 Python/2.5.2
Content-Language: en
X-W3C-Validator-Recursion: 1
X-W3C-Validator-Status: Invalid
X-W3C-Validator-Errors: 6
X-W3C-Validator-Warnings: 0
Content-Type: text/html; charset=UTF-8
Vary: Accept-Encoding
Connection: close
```
Thus, you can elegantly invoke the W3C Validation Service and extract the results from the HTTP header:
```
# Programmatic XHTML Validations in Python
# Martin Hepp and Alex Stolz
# [email protected] / [email protected]
import urllib
import urllib2
URL = "http://validator.w3.org/check?uri=%s"
SITE_URL = "http://www.heppnetz.de"
# pattern for HEAD request taken from
# http://stackoverflow.com/questions/4421170/python-head-request-with-urllib2
request = urllib2.Request(URL % urllib.quote(SITE_URL))
request.get_method = lambda : 'HEAD'
response = urllib2.urlopen(request)
valid = response.info().getheader('X-W3C-Validator-Status')
if valid == "Valid":
valid = True
else:
valid = False
errors = int(response.info().getheader('X-W3C-Validator-Errors'))
warnings = int(response.info().getheader('X-W3C-Validator-Warnings'))
print "Valid markup: %s (Errors: %i, Warnings: %i) " % (valid, errors, warnings)
``` |
Why does Python's iter() on a mapping return iterkeys() instead of iteritems()? | 35,569 | 6 | 2008-08-30T01:51:05Z | 35,582 | 8 | 2008-08-30T02:01:57Z | [
"python",
"mapping",
"iteration"
] | It seems like if you want to get the keys of a mapping, you ask for them; otherwise, give me the *whole* mapping (constituted by a set of key-value pairs). Is there a historical reason for this? | Check out [this thread](http://mail.python.org/pipermail/python-3000/2007-September/010209.html) for a discussion on the reasons behind this behavior (including that Guido likes it, and it's [not likely to change](http://mail.python.org/pipermail/python-3000/2007-September/010222.html)). |
Ruby "is" equivalent | 35,634 | 6 | 2008-08-30T03:04:54Z | 35,635 | 12 | 2008-08-30T03:06:02Z | [
"python",
"ruby"
] | Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i.e. have the same memory location). | Use `a.equal? b`
<http://www.ruby-doc.org/core/classes/Object.html>
> Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). |
Is Python good for big software projects (not web based)? | 35,753 | 25 | 2008-08-30T07:08:22Z | 35,757 | 16 | 2008-08-30T07:19:40Z | [
"python",
"ide"
] | Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity).
Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?
What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion. | In my opinion python is more than ready for developing complex applications. I see pythons strength more on the server side than writing graphical clients. But have a look at <http://www.resolversystems.com/>. They develop a whole spreadsheet in python using the .net ironpython port.
If you are familiar with eclipse have a look at [pydev](http://pydev.sourceforge.net/) which provides auto-completion and debugging support for python with all the other eclipse goodies like svn support. The guy developing it has just been bought by [aptana](http://aptana.com/blog/pcolton/pydev_news), so this will be solid choice for the future.
@Marcin
> Cons: as a dynamic language, has way
> worse IDE support (proper syntax
> completion requires static typing,
> whether explicit in Java or inferred
> in SML),
You are right, that static analysis may not provide full syntax completion for dynamic languages, but I thing pydev gets the job done very well. Further more I have a different development style when programming python. I have always an ipython session open and with one F5 I do not only get the perfect completion from ipython, but object introspection and manipulation as well.
> But if you want to write second Google
> or Yahoo, you will be much better with
> C# or Java.
[Google just rewrote jaiku](http://www.jaiku.com/blog/2008/08/18/from-the-dev-corner-an-under-the-hood-preview-of-our-new-engine/) to work on top of App Engine, all in python. And as far as I know they use a lot of python inside google too. |
Is Python good for big software projects (not web based)? | 35,753 | 25 | 2008-08-30T07:08:22Z | 35,759 | 11 | 2008-08-30T07:22:03Z | [
"python",
"ide"
] | Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity).
Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?
What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion. | I really like python, it's usually my language of choice these days for small (non-gui) stuff that I do on my own.
However, for some larger Python projects I've tackled, I'm finding that it's not quite the same as programming in say, C++. I was working on a language parser, and needed to represent an AST in Python. This is certainly within the scope of what Python can do, but I had a bit of trouble with some refactoring. I was changing the representation of my AST and changing methods and classes around a lot, and I found I missed the strong typing that would be available to me in a C++ solution. Python's duck typing was almost *too* flexible and I found myself adding a lot of `assert` code to try to check my types as the program ran. And then I couldn't really be sure that everything was properly typed unless I had 100% code coverage testing (which I didn't at the time).
Actually, that's another thing that I miss sometimes. It's possible to write syntactically correct code in Python that simply won't run. The compiler is incapable of telling you about it until it actually executes the code, so in infrequently-used code paths such as error handlers you can easily have unseen bugs lurking around. Even code that's as simple as printing an error message with a % format string can fail at runtime because of mismatched types.
I haven't used Python for any GUI stuff so I can't comment on that aspect. |
Is Python good for big software projects (not web based)? | 35,753 | 25 | 2008-08-30T07:08:22Z | 35,776 | 8 | 2008-08-30T08:21:18Z | [
"python",
"ide"
] | Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity).
Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?
What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion. | Python is considered (among Python programmers :) to be a great language for rapid prototyping. There's not a lot of extraneous syntax getting in the way of your thought processes, so most of the work you do tends to go into the code. (There's far less idioms required to be involved in writing good Python code than in writing good C++.)
Given this, most Python (CPython) programmers ascribe to the "premature optimization is the root of all evil" philosophy. By writing high-level (and significantly slower) Python code, one can optimize the bottlenecks out using C/C++ bindings when your application is nearing completion. At this point it becomes more clear what your processor-intensive algorithms are through proper profiling. This way, you write most of the code in a very readable and maintainable manner while allowing for speedups down the road. You'll see several Python library modules written in C for this very reason.
Most graphics libraries in Python (i.e. wxPython) are just Python wrappers around C++ libraries anyway, so you're pretty much writing to a C++ backend.
To address your IDE question, [SPE](http://pythonide.blogspot.com/) (Stani's Python Editor) is a good IDE that I've used and [Eclipse](http://www.eclipse.org/) with [PyDev](http://pydev.sourceforge.net/) gets the job done as well. Both are OSS, so they're free to try!
[Edit] @Marcin: Have you had experience writing > 30k LOC in Python? It's also funny that you should mention Google's scalability concerns, since they're Python's biggest supporters! Also a small organization called NASA also uses Python frequently ;) see ["One coder and 17,000 Lines of Code Later"](http://www.python.org/about/success/usa/). |
Is Python good for big software projects (not web based)? | 35,753 | 25 | 2008-08-30T07:08:22Z | 35,777 | 19 | 2008-08-30T08:21:24Z | [
"python",
"ide"
] | Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity).
Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?
What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion. | You'll find mostly two answers to that – the religous one (Yes! Of course! It's the best language ever!) and the other religious one (you gotta be kidding me! Python? No... it's not mature enough). I will maybe skip the last religion (Python?! Use Ruby!). The truth, as always, is far from obvious.
**Pros**: it's easy, readable, batteries included, has lots of good libraries for pretty much everything. It's expressive and dynamic typing makes it more concise in many cases.
**Cons**: as a dynamic language, has way worse IDE support (proper syntax completion **requires** static typing, whether explicit in Java or inferred in SML), its object system is far from perfect (interfaces, anyone?) and it is easy to end up with messy code that has methods returning either int or boolean or object or some sort under unknown circumstances.
My take – I love Python for scripting, automation, tiny webapps and other simple well defined tasks. In my opinion it is by far **the best** dynamic language on the planet. That said, I would **never** use it **any** dynamically typed language to develop an application of substantial size.
Say – it would be fine to use it for Stack Overflow, which has three developers and I guess no more than 30k lines of code. For bigger things – first your development would be super fast, and then once team and codebase grow things are slowing down more than they would with Java or C#. You need to offset lack of compilation time checks by writing more unittests, refactorings get harder cause you never know what your refacoring broke until you run all tests or even the whole big app, etc.
Now – decide on how big your team is going to be and how big the app is supposed to be once it is done. If you have 5 or less people and the target size is roughly Stack Overflow, go ahead, write in Python. You will finish in no time and be happy with good codebase. But if you want to write second Google or Yahoo, you will be much better with C# or Java.
Side-note on C/C++ you have mentioned: if you are not writing performance critical software (say massive parallel raytracer that will run for three months rendering a film) or a very mission critical system (say Mars lander that will fly three years straight and has only one chance to land right or you lose $400mln) do not use it. For web apps, most desktop apps, most apps in general it is not a good choice. You will die debugging pointers and memory allocation in complex business logic. |
Is Python good for big software projects (not web based)? | 35,753 | 25 | 2008-08-30T07:08:22Z | 259,591 | 28 | 2008-11-03T19:05:14Z | [
"python",
"ide"
] | Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity).
Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?
What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion. | We've used IronPython to build our flagship spreadsheet application (40kloc production code - and it's Python, which IMO means loc per feature is low) at [Resolver Systems](http://www.resolversystems.com/), so I'd definitely say it's ready for production use of complex apps.
There are two ways in which this might not be a useful answer to you :-)
1. We're using IronPython, not the more usual CPython. This gives us the huge advantage of being able to use .NET class libraries. I may be setting myself up for flaming here, but I would say that I've never really seen a CPython application that looked "professional" - so having access to the WinForms widget set was a huge win for us. IronPython also gives us the advantage of being able to easily drop into C# if we need a performance boost. (Though to be honest we have *never* needed to do that. All of our performance problems to date have been because we chose dumb algorithms rather than because the language was slow.) Using C# from IP is much easier than writing a C Extension for CPython.
2. We're an Extreme Programming shop, so we write tests before we write code. I would not write production code in a dynamic language without writing the tests first; the lack of a compile step needs to be covered by something, and as other people have pointed out, refactoring without it can be tough. (Greg Hewgill's answer suggests he's had the same problem. On the other hand, I don't think I would write - or especially refactor - production code in *any* language these days without writing the tests first - but YMMV.)
Re: the IDE - we've been pretty much fine with each person using their favourite text editor; if you prefer something a bit more heavyweight then [WingIDE](http://www.wingware.com/products) is pretty well-regarded. |
Why is my instance variable not in __dict__? | 35,805 | 27 | 2008-08-30T09:12:41Z | 35,823 | 38 | 2008-08-30T09:33:00Z | [
"python"
] | If I create a class `A` as follows:
```
class A:
def __init__(self):
self.name = 'A'
```
Inspecting the `__dict__` member looks like `{'name': 'A'}`
If however I create a class `B`:
```
class B:
name = 'B'
```
`__dict__` is empty.
What is the difference between the two, and why doesn't `name` show up in `B`'s `__dict__`? | `B.name` is a class attribute, not an instance attribute. It shows up in `B.__dict__`, but not in `b = B(); b.__dict__`.
The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, `b.name` will give you the value of `B.name`. |
Why is my instance variable not in __dict__? | 35,805 | 27 | 2008-08-30T09:12:41Z | 39,755 | 11 | 2008-09-02T15:12:12Z | [
"python"
] | If I create a class `A` as follows:
```
class A:
def __init__(self):
self.name = 'A'
```
Inspecting the `__dict__` member looks like `{'name': 'A'}`
If however I create a class `B`:
```
class B:
name = 'B'
```
`__dict__` is empty.
What is the difference between the two, and why doesn't `name` show up in `B`'s `__dict__`? | ```
class A:
def _ _init_ _(self):
self.name = 'A'
a = A()
```
Creates an attribute on the object instance a of type A and it can therefore be found in: `a.__dict__`
```
class B:
name = 'B'
b = B()
```
Creates an attribute on the class B and the attribute can be found in `B.__dict__` alternatively if you have an instance b of type B you can see the class level attributes in `b.__class__.__dict__` |
How to escape os.system() calls in Python? | 35,817 | 72 | 2008-08-30T09:27:24Z | 35,857 | 44 | 2008-08-30T10:13:11Z | [
"python",
"shell",
"escaping"
] | When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.
I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:
```
def sh_escape(s):
return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")
os.system("cat %s | grep something | sort > %s"
% (sh_escape(in_filename),
sh_escape(out_filename)))
```
*Edit:* I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.
Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me). | This is what I use:
```
def shellquote(s):
return "'" + s.replace("'", "'\\''") + "'"
```
The shell will always accept a quoted filename and remove the surrounding quotes before passing it to the program in question. Notably, this avoids problems with filenames that contain spaces or any other kind of nasty shell metacharacter.
**Update**: If you are using Python 3.3 or later, use [shlex.quote](http://docs.python.org/dev/library/shlex.html#shlex.quote) instead of rolling your own. |
How to escape os.system() calls in Python? | 35,817 | 72 | 2008-08-30T09:27:24Z | 35,858 | 49 | 2008-08-30T10:15:02Z | [
"python",
"shell",
"escaping"
] | When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.
I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:
```
def sh_escape(s):
return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")
os.system("cat %s | grep something | sort > %s"
% (sh_escape(in_filename),
sh_escape(out_filename)))
```
*Edit:* I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.
Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me). | Perhaps you have a specific reason for using `os.system()`. But if not you should probably be using the [`subprocess` module](http://docs.python.org/lib/module-subprocess.html). You can specify the pipes directly and avoid using the shell.
The following is from [PEP324](http://www.python.org/dev/peps/pep-0324/):
> ```
> Replacing shell pipe line
> -------------------------
>
> output=`dmesg | grep hda`
> ==>
> p1 = Popen(["dmesg"], stdout=PIPE)
> p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
> output = p2.communicate()[0]
> ``` |
How to escape os.system() calls in Python? | 35,817 | 72 | 2008-08-30T09:27:24Z | 847,800 | 101 | 2009-05-11T12:06:40Z | [
"python",
"shell",
"escaping"
] | When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.
I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:
```
def sh_escape(s):
return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")
os.system("cat %s | grep something | sort > %s"
% (sh_escape(in_filename),
sh_escape(out_filename)))
```
*Edit:* I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.
Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me). | [`shlex.quote()`](https://docs.python.org/3/library/shlex.html#shlex.quote) does what you want since python 3.
(Use [`pipes.quote`](https://docs.python.org/2/library/pipes.html#pipes.quote) to support both python 2 and python 3) |
How to escape os.system() calls in Python? | 35,817 | 72 | 2008-08-30T09:27:24Z | 10,750,633 | 7 | 2012-05-25T07:54:41Z | [
"python",
"shell",
"escaping"
] | When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.
I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:
```
def sh_escape(s):
return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")
os.system("cat %s | grep something | sort > %s"
% (sh_escape(in_filename),
sh_escape(out_filename)))
```
*Edit:* I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.
Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me). | Maybe `subprocess.list2cmdline` is a better shot? |
Django templates and variable attributes | 35,948 | 30 | 2008-08-30T13:20:02Z | 35,978 | 9 | 2008-08-30T14:16:54Z | [
"python",
"django",
"google-app-engine"
] | I'm using Google App Engine and Django templates.
I have a table that I want to display the objects look something like:
```
Object Result:
Items = [item1,item2]
Users = [{name='username',item1=3,item2=4},..]
```
The Django template is:
```
<table>
<tr align="center">
<th>user</th>
{% for item in result.items %}
<th>{{item}}</th>
{% endfor %}
</tr>
{% for user in result.users %}
<tr align="center">
<td>{{user.name}}</td>
{% for item in result.items %}
<td>{{ user.item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
```
Now the [Django documention](http://www.djangoproject.com/documentation/0.96/templates/#variables) states that when it sees a **.** in variables
It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen... | I'm assuming that the part the doesn't work is `{{ user.item }}`.
Django will be trying a dictionary lookup, but using the string `"item"` and not the value of the `item` loop variable. Django did the same thing when it resolved `{{ user.name }}` to the `name` attribute of the `user` object, rather than looking for a variable called `name`.
I think you will need to do some preprocessing of the data in your view before you render it in your template. |
Django templates and variable attributes | 35,948 | 30 | 2008-08-30T13:20:02Z | 50,425 | 30 | 2008-09-08T19:01:24Z | [
"python",
"django",
"google-app-engine"
] | I'm using Google App Engine and Django templates.
I have a table that I want to display the objects look something like:
```
Object Result:
Items = [item1,item2]
Users = [{name='username',item1=3,item2=4},..]
```
The Django template is:
```
<table>
<tr align="center">
<th>user</th>
{% for item in result.items %}
<th>{{item}}</th>
{% endfor %}
</tr>
{% for user in result.users %}
<tr align="center">
<td>{{user.name}}</td>
{% for item in result.items %}
<td>{{ user.item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
```
Now the [Django documention](http://www.djangoproject.com/documentation/0.96/templates/#variables) states that when it sees a **.** in variables
It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen... | I found a "nicer"/"better" solution for getting variables inside
Its not the nicest way, but it works.
You install a custom filter into django which gets the key of your dict as a parameter
To make it work in google app-engine you need to add a file to your main directory,
I called mine \*django\_hack.py\* which contains this little piece of code
```
from google.appengine.ext import webapp
register = webapp.template.create_template_register()
def hash(h,key):
if key in h:
return h[key]
else:
return None
register.filter(hash)
```
Now that we have this file, all we need to do is tell the app-engine to use it...
we do that by adding this little line to your main file
```
webapp.template.register_template_library('django_hack')
```
and in your template view add this template instead of the usual code
```
{{ user|hash:item }}
```
And its should work perfectly =) |
Django templates and variable attributes | 35,948 | 30 | 2008-08-30T13:20:02Z | 3,466,349 | 7 | 2010-08-12T09:36:35Z | [
"python",
"django",
"google-app-engine"
] | I'm using Google App Engine and Django templates.
I have a table that I want to display the objects look something like:
```
Object Result:
Items = [item1,item2]
Users = [{name='username',item1=3,item2=4},..]
```
The Django template is:
```
<table>
<tr align="center">
<th>user</th>
{% for item in result.items %}
<th>{{item}}</th>
{% endfor %}
</tr>
{% for user in result.users %}
<tr align="center">
<td>{{user.name}}</td>
{% for item in result.items %}
<td>{{ user.item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
```
Now the [Django documention](http://www.djangoproject.com/documentation/0.96/templates/#variables) states that when it sees a **.** in variables
It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen... | Or you can use the default django system which is used to resolve attributes in tempaltes like this :
```
from django.template import Variable, VariableDoesNotExist
@register.filter
def hash(object, attr):
pseudo_context = { 'object' : object }
try:
value = Variable('object.%s' % attr).resolve(pseudo_context)
except VariableDoesNotExist:
value = None
return value
```
That just works
in your template :
```
{{ user|hash:item }}
``` |
C-like structures in Python | 35,988 | 210 | 2008-08-30T14:33:25Z | 35,990 | 47 | 2008-08-30T14:35:29Z | [
"python",
"struct"
] | Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
```
class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
``` | How about a dictionary?
Something like this:
```
myStruct = {'field1': 'some val', 'field2': 'some val'}
```
Then you can use this to manipulate values:
```
print myStruct['field1']
myStruct['field2'] = 'some other values'
```
And the values don't have to be strings. They can be pretty much any other object. |
C-like structures in Python | 35,988 | 210 | 2008-08-30T14:33:25Z | 35,993 | 70 | 2008-08-30T14:38:38Z | [
"python",
"struct"
] | Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
```
class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
``` | You can use a tuple for a lot of things where you would use a struct in C (something like x,y coordinates or RGB colors for example).
For everything else you can use dictionary, or a utility class like [this one](http://code.activestate.com/recipes/52308/):
```
>>> class Bunch:
... def __init__(self, **kwds):
... self.__dict__.update(kwds)
...
>>> mystruct = Bunch(field1=value1, field2=value2)
```
I think the "definitive" discussion is [here](http://books.google.com/books?id=Q0s6Vgb98CQC&lpg=PT212&dq=Python%20Cookbook%20%22Collecting%20a%20Bunch%20of%20Named%20Items%22&hl=en&pg=PT213#v=onepage&q&f=false), in the published version of the Python Cookbook. |
C-like structures in Python | 35,988 | 210 | 2008-08-30T14:33:25Z | 36,033 | 202 | 2008-08-30T15:18:59Z | [
"python",
"struct"
] | Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
```
class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
``` | Use a [named tuple](https://docs.python.org/2/library/collections.html#collections.namedtuple), which was added to the [collections module](http://docs.python.org/library/collections.html) in the standard library in Python 2.6. It's also possible to use Raymond Hettinger's [named tuple](http://code.activestate.com/recipes/500261/) recipe if you need to support Python 2.4.
It's nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as:
```
from collections import namedtuple
MyStruct = namedtuple("MyStruct", "field1 field2 field3")
```
The newly created type can be used like this:
```
m = MyStruct("foo", "bar", "baz")
```
Or you can use named arguments:
```
m = MyStruct(field1 = "foo", field2 = "bar", field3 = "baz")
``` |
C-like structures in Python | 35,988 | 210 | 2008-08-30T14:33:25Z | 36,034 | 17 | 2008-08-30T15:20:15Z | [
"python",
"struct"
] | Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
```
class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
``` | > dF: that's pretty cool... I didn't
> know that I could access the fields in
> a class using dict.
>
> Mark: the situations that I wish I had
> this are precisely when I want a tuple
> but nothing as "heavy" as a
> dictionary.
You can access the fields of a class using a dictionary because the fields of a class, its methods and all its properties are stored internally using dicts (at least in CPython).
...Which leads us to your second comment. Believing that Python dicts are "heavy" is an extremely non-pythonistic concept. And reading such comments kills my Python Zen. That's not good.
You see, when you declare a class you are actually creating a pretty complex wrapper around a dictionary - so, if anything, you are adding more overhead than by using a simple dictionary. An overhead which, by the way, is meaningless in any case. If you are working on performance critical applications, use C or something. |
C-like structures in Python | 35,988 | 210 | 2008-08-30T14:33:25Z | 36,061 | 13 | 2008-08-30T15:53:10Z | [
"python",
"struct"
] | Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
```
class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
``` | You can also pass the init parameters to the instance variables by position
```
# Abstract struct class
class Struct:
def __init__ (self, *argv, **argd):
if len(argd):
# Update by dictionary
self.__dict__.update (argd)
else:
# Update by position
attrs = filter (lambda x: x[0:2] != "__", dir(self))
for n in range(len(argv)):
setattr(self, attrs[n], argv[n])
# Specific class
class Point3dStruct (Struct):
x = 0
y = 0
z = 0
pt1 = Point3dStruct()
pt1.x = 10
print pt1.x
print "-"*10
pt2 = Point3dStruct(5, 6)
print pt2.x, pt2.y
print "-"*10
pt3 = Point3dStruct (x=1, y=2, z=3)
print pt3.x, pt3.y, pt3.z
print "-"*10
``` |
C-like structures in Python | 35,988 | 210 | 2008-08-30T14:33:25Z | 3,761,729 | 56 | 2010-09-21T15:15:33Z | [
"python",
"struct"
] | Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
```
class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
``` | Perhaps you are looking for Structs without constructors:
```
class Sample:
name = ''
average = 0.0
values = None # list cannot be initialized here!
s1 = Sample()
s1.name = "sample 1"
s1.values = []
s1.values.append(1)
s1.values.append(2)
s1.values.append(3)
s2 = Sample()
s2.name = "sample 2"
s2.values = []
s2.values.append(4)
for v in s1.values: # prints 1,2,3 --> OK.
print v
print "***"
for v in s2.values: # prints 4 --> OK.
print v
``` |
How do I sort a list of strings in Python? | 36,139 | 211 | 2008-08-30T17:03:09Z | 36,143 | 23 | 2008-08-30T17:04:40Z | [
"python",
"string",
"sorting"
] | What is the best way of creating an alphabetically sorted list in Python? | ```
list.sort()
```
It really is that simple :) |
How do I sort a list of strings in Python? | 36,139 | 211 | 2008-08-30T17:03:09Z | 36,156 | 270 | 2008-08-30T17:10:12Z | [
"python",
"string",
"sorting"
] | What is the best way of creating an alphabetically sorted list in Python? | Basic answer:
```
mylist = ["b", "C", "A"]
mylist.sort()
```
This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the [`sorted()`](http://docs.python.org/library/functions.html#sorted) function:
```
for x in sorted(mylist):
print x
```
However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter `key` to specify custom sorting order (the alternative, using `cmp`, is a deprecated solution, as it has to be evaluated multiple times - `key` is only computed once per element).
So, to sort according to the current locale, taking language-specific rules into account ([`cmp_to_key`](http://docs.python.org/library/functools.html#functools.cmp_to_key) is a helper function from functools):
```
sorted(mylist, key=cmp_to_key(locale.strcoll))
```
And finally, if you need, you can specify a [custom locale](http://docs.python.org/library/locale.html) for sorting:
```
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'),
key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']
```
Last note: you will see examples of case-insensitive sorting which use the `lower()` method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:
```
# this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)
``` |
How do I sort a list of strings in Python? | 36,139 | 211 | 2008-08-30T17:03:09Z | 36,395 | 29 | 2008-08-30T22:14:36Z | [
"python",
"string",
"sorting"
] | What is the best way of creating an alphabetically sorted list in Python? | It is also worth noting the `sorted()` function:
```
for x in sorted(list):
print x
```
This returns a new, sorted version of a list without changing the original list. |
How do I sort a list of strings in Python? | 36,139 | 211 | 2008-08-30T17:03:09Z | 1,640,634 | 13 | 2009-10-28T22:45:59Z | [
"python",
"string",
"sorting"
] | What is the best way of creating an alphabetically sorted list in Python? | The proper way to sort strings is:
```
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']
# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']
```
The previous example of `mylist.sort(key=lambda x: x.lower())` will work fine for ASCII-only contexts. |
"The system cannot find the file specified" when invoking subprocess.Popen in python | 36,324 | 4 | 2008-08-30T20:24:38Z | 36,327 | 12 | 2008-08-30T20:34:35Z | [
"python",
"svn-merge"
] | I'm trying to use svnmerge.py to merge some files. Under the hood it uses python, and when I use it I get an error - "The system cannot find the file specified". Colleagues at work are running the same version of svnmerge.py, and of python (2.5.2, specifically r252:60911) without an issue.
I found [this link](http://www.nabble.com/problem-under-some-windows-desktop-td15868057.html), which describes my problem. Trying what was outlined there, I confirmed Python could find svn (it's in my path):
```
P:\>python
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> i,k = os.popen4("svn --version")
>>> i.close()
>>> k.readline()
'svn, version 1.4.2 (r22196)\n'
```
Looking at the svnmerge.py code, though, I noticed for python versions 2.4 and higher it was following a different execution path. Rather than invoking
os.popen4() it uses subprocess.Popen(). Trying that reproduces the error:
```
C:\>python
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> p = subprocess.Popen("svn --version", stdout=subprocess.PIPE,
>>> close_fds=False, stderr=subprocess.PIPE)
Traceback (most recent call last):
File "", line 1, in
File "C:\Python25\lib\subprocess.py", line 594, in __init__
errread, errwrite)
File "C:\Python25\lib\subprocess.py", line 816, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
>>>
```
For now, I've commented out the 2.4-and-higher specific code, but I'd like to find a proper solution.
If it's not obvious, I'm a complete python newbie, but google hasn't helped. Any pointers? | It's a bug, see the [documentation of `subprocess.Popen`](http://docs.python.org/lib/node528.html). There either needs to be a `"shell=True`" option, or the first argument needs to be a sequence `['svn', '--version']`. As it is now, `Popen` is looking for an executable named, literally, "svn --version" which it doesn't find.
I don't know why it would work for your colleagues though, if they are running the same OS and version of Python... FWIW it gives me the same error message on a mac, and either of the two ways I gave fixes it. |
Setup django with WSGI and apache | 36,806 | 5 | 2008-08-31T12:03:20Z | 1,038,110 | 7 | 2009-06-24T12:39:13Z | [
"python",
"django",
"apache",
"mod-wsgi"
] | I have been sold on mod\_wsgi and apache rather than mod\_python.
I have all the parts installed (django, apache, mod\_wsgi) but have run into a problem deploying.
I am on osx 10.5 with apache 2.2 and django 1.0b2, mod\_wsgi-2.3
My application is called tred.
Here are the relevant files:
httpd-vhosts (included in httpd-conf)
```
NameVirtualHost tred:80
ServerName tred
Alias /admin_media /usr/lib/python2.5/site-packages/django/contrib/admin/media
Order allow,deny
Allow from all
Alias /media /Users/dmg/Sites/tred/media
Order allow,deny
Allow from all
Alias / /Users/dmg/Sites/tred/
Order allow,deny
Allow from all
WSGIScriptAlias / /Users/dmg/Sites/tred/mod_wsgi-handler.wsgi
WSGIDaemonProcess tred user=dmg group=staff processes=1 threads=10
WSGIProcessGroup tred
```
mod\_wsgi-handle.wsgi
```
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'tred.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
```
When I go to <http://tred> I get a directory listing rather than the rendered website. I think I have followed the tutorials correctly but it is obviously not right. What can I do to make this work? | Note that Alias and WSGIScriptAlias directives do not have the same precedence. Thus, they will not be processed in file order as written. Instead, all Alias directives get precedence over WSGIScriptAlias directives. Thus, it wouldn't have mattered if the Alias for '/' appeared after WSGIScriptAlias, it would still have taken precedence. |
How do I add data to an existing model in Django? | 36,812 | 2 | 2008-08-31T12:11:10Z | 36,935 | 7 | 2008-08-31T15:59:11Z | [
"python",
"django"
] | Currently, I am writing up a bit of a product-based CMS as my first project.
Here is my question. How can I add additional data (products) to my Product model?
I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in mind that I don't really know all that much Python, and i am very new to Django
How can I do this all without using this existing django admin interface. | You will want to wire your URL to the Django [create\_object generic view](https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object), and pass it either "model" (the model you want to create) or "form\_class" (a customized [ModelForm](https://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#topics-forms-modelforms) class). There are a number of [other arguments](https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object) you can also pass to override default behaviors.
Sample URLconf for the simplest case:
```
from django.conf.urls.defaults import *
from django.views.generic.create_update import create_object
from my_products_app.models import Product
urlpatterns = patterns('',
url(r'^admin/products/add/$', create_object, {'model': Product}))
```
Your template will get the context variable "form", which you just need to wrap in a <form> tag and add a submit button. The simplest working template (by default should go in "my\_products\_app/product\_form.html"):
```
<form action="." method="POST">
{{ form }}
<input type="submit" name="submit" value="add">
</form>
```
Note that your Product model must have a get\_absolute\_url method, or else you must pass in the post\_save\_redirect parameter to the view. Otherwise it won't know where to redirect to after save. |
What does ** (double star) and * (star) do for Python parameters? | 36,901 | 833 | 2008-08-31T15:04:35Z | 36,902 | 9 | 2008-08-31T15:07:48Z | [
"python",
"syntax",
"parameter-passing",
"identifier",
"kwargs"
] | In the following method definitions, what does the `*` and `**` do for `param2`?
```
def foo(param1, *param2):
def bar(param1, **param2):
``` | From the Python documentation:
> If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax "\*identifier" is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).
>
> If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax "\*\*identifier" is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments. |
What does ** (double star) and * (star) do for Python parameters? | 36,901 | 833 | 2008-08-31T15:04:35Z | 36,908 | 877 | 2008-08-31T15:17:31Z | [
"python",
"syntax",
"parameter-passing",
"identifier",
"kwargs"
] | In the following method definitions, what does the `*` and `**` do for `param2`?
```
def foo(param1, *param2):
def bar(param1, **param2):
``` | The `*args` and `**kwargs` is a common idiom to allow arbitrary number of arguments to functions as described in the section [more on defining functions](http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions) in the Python documentation.
The `*args` will give you all function parameters [as a tuple](https://docs.python.org/dev/tutorial/controlflow.html#arbitrary-argument-lists):
```
In [1]: def foo(*args):
...: for a in args:
...: print a
...:
...:
In [2]: foo(1)
1
In [4]: foo(1,2,3)
1
2
3
```
The `**kwargs` will give you all
**keyword arguments** except for those corresponding to a formal parameter as a dictionary.
```
In [5]: def bar(**kwargs):
...: for a in kwargs:
...: print a, kwargs[a]
...:
...:
In [6]: bar(name='one', age=27)
age 27
name one
```
Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
```
def foo(kind, *args, **kwargs):
pass
```
Another usage of the `*l` idiom is to **unpack argument lists** when calling a function.
```
In [9]: def foo(bar, lee):
...: print bar, lee
...:
...:
In [10]: l = [1,2]
In [11]: foo(*l)
1 2
```
In Python 3 it is possible to use `*l` on the left side of an assignment ([Extended Iterable Unpacking](http://www.python.org/dev/peps/pep-3132/)):
```
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
```
Also Python 3 adds new semantic (refer [PEP 3102](https://www.python.org/dev/peps/pep-3102/)):
```
def func(arg1, arg2, arg3='default', *, kwarg1='abc', kwarg2='xyz'):
pass
```
Such function accepts only 2 positional arguments, and everything after `*` can only be passed as keyword argument, not positional one.
In Python 2 similar was true for all parameters after `*args`. |
What does ** (double star) and * (star) do for Python parameters? | 36,901 | 833 | 2008-08-31T15:04:35Z | 36,911 | 89 | 2008-08-31T15:20:21Z | [
"python",
"syntax",
"parameter-passing",
"identifier",
"kwargs"
] | In the following method definitions, what does the `*` and `**` do for `param2`?
```
def foo(param1, *param2):
def bar(param1, **param2):
``` | The single \* means that there can be any number of extra positional arguments. `foo()` can be invoked like `foo(1,2,3,4,5)`. In the body of foo() param2 is a sequence containing 2-5.
The double \*\* means there can be any number of extra named parameters. `bar()` can be invoked like `bar(1, a=2, b=3)`. In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }
With the following code:
```
def foo(param1, *param2):
print param1
print param2
def bar(param1, **param2):
print param1
print param2
foo(1,2,3,4,5)
bar(1,a=2,b=3)
```
the output is
```
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
``` |
What does ** (double star) and * (star) do for Python parameters? | 36,901 | 833 | 2008-08-31T15:04:35Z | 36,926 | 244 | 2008-08-31T15:47:25Z | [
"python",
"syntax",
"parameter-passing",
"identifier",
"kwargs"
] | In the following method definitions, what does the `*` and `**` do for `param2`?
```
def foo(param1, *param2):
def bar(param1, **param2):
``` | It's also worth noting that you can use \* and \*\* when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:
```
def foo(x,y,z):
print "x=" + str(x)
print "y=" + str(y)
print "z=" + str(z)
```
You can do things like:
```
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
``` |
What does ** (double star) and * (star) do for Python parameters? | 36,901 | 833 | 2008-08-31T15:04:35Z | 12,362,812 | 15 | 2012-09-11T04:33:44Z | [
"python",
"syntax",
"parameter-passing",
"identifier",
"kwargs"
] | In the following method definitions, what does the `*` and `**` do for `param2`?
```
def foo(param1, *param2):
def bar(param1, **param2):
``` | `*` and `**` have special usage in the function argument list. `*`
implies that the argument is a list and `**` implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments |
What does ** (double star) and * (star) do for Python parameters? | 36,901 | 833 | 2008-08-31T15:04:35Z | 26,365,795 | 47 | 2014-10-14T16:34:01Z | [
"python",
"syntax",
"parameter-passing",
"identifier",
"kwargs"
] | In the following method definitions, what does the `*` and `**` do for `param2`?
```
def foo(param1, *param2):
def bar(param1, **param2):
``` | **`*args` and `**kwargs` notation**
`*args` (typically said "star-args") and `**kwargs` (stars can be implied by saying "kwargs", but be explicit with "double-star kwargs") are common idioms of Python for using the `*` and `**` notation. These specific variable names aren't required (e.g. you could use `*foos` and `**bars`), but a departure from convention is likely to enrage your fellow Python coders.
We typically use these when we don't know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).
**Example 1**
The following function describes how they can be used, and demonstrates behavior. Note the named `b` argument will be consumed by the second positional argument before :
```
def foo(a, b=10, *args, **kwargs):
'''
this function takes required argument a, not required keyword argument b
and any number of unknown positional arguments and keyword arguments after
'''
print('a is a required argument, and its value is {0}'.format(a))
print('b not required, its default value is 10, actual value: {0}'.format(b))
# we can inspect the unknown arguments we were passed:
# - args:
print('args is of type {0} and length {1}'.format(type(args), len(args)))
for arg in args:
print('unknown arg: {0}'.format(arg))
# - kwargs:
print('kwargs is of type {0} and length {1}'.format(type(kwargs),
len(kwargs)))
for kw, arg in kwargs.items():
print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
# But we don't have to know anything about them
# to pass them to other functions.
print('Args or kwargs can be passed without knowing what they are.')
# max can take two or more positional args: max(a, b, c...)
print('e.g. max(a, b, *args) \n{0}'.format(
max(a, b, *args)))
kweg = 'dict({0})'.format( # named args same as unknown kwargs
', '.join('{k}={v}'.format(k=k, v=v)
for k, v in sorted(kwargs.items())))
print('e.g. dict(**kwargs) (same as {kweg}) returns: \n{0}'.format(
dict(**kwargs), kweg=kweg))
```
We can check the online help for the function's signature, with `help(foo)`, which tells us
```
foo(a, b=10, *args, **kwargs)
```
Let's call this function with `foo(1, 2, 3, 4, e=5, f=6, g=7)`
which prints:
```
a is a required argument, and its value is 1
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 2
unknown arg: 3
unknown arg: 4
kwargs is of type <type 'dict'> and length 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: g, arg: 7
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
4
e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:
{'e': 5, 'g': 7, 'f': 6}
```
**Example 2**
We can also call it using another function, into which we just provide `a`:
```
def bar(a):
b, c, d, e, f = 2, 3, 4, 5, 6
# dumping every local variable into foo as a keyword argument
# by expanding the locals dict:
foo(**locals())
```
`bar(100)` prints:
```
a is a required argument, and its value is 100
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 0
kwargs is of type <type 'dict'> and length 4
unknown kwarg - kw: c, arg: 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: d, arg: 4
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
100
e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:
{'c': 3, 'e': 5, 'd': 4, 'f': 6}
```
**Example 3: practical usage in decorators**
OK, so maybe we're not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.
```
def foo(a, b, c, d=0, e=100):
# imagine this is much more code than a simple function call
preprocess()
differentiating_process_foo(a,b,c,d,e)
# imagine this is much more code than a simple function call
postprocess()
def bar(a, b, c=None, d=0, e=100, f=None):
preprocess()
differentiating_process_bar(a,b,c,d,e,f)
postprocess()
def baz(a, b, c, d, e, f):
... and so on
```
We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how `*args` and `**kwargs` can be very useful:
```
def decorator(function):
'''function to wrap other functions with a pre- and postprocess'''
@functools.wraps(function) # applies module, name, and docstring to wrapper
def wrapper(*args, **kwargs):
# again, imagine this is complicated, but we only write it once!
preprocess()
function(*args, **kwargs)
postprocess()
return wrapper
```
And now every wrapped function can be written much more succinctly, as we've factored out the redundancy:
```
@decorator
def foo(a, b, c, d=0, e=100):
differentiating_process_foo(a,b,c,d,e)
@decorator
def bar(a, b, c=None, d=0, e=100, f=None):
differentiating_process_bar(a,b,c,d,e,f)
@decorator
def baz(a, b, c=None, d=0, e=100, f=None, g=None):
differentiating_process_baz(a,b,c,d,e,f, g)
@decorator
def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):
differentiating_process_quux(a,b,c,d,e,f,g,h)
```
And by factoring out our code, which `*args` and `**kwargs` allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change. |
What does ** (double star) and * (star) do for Python parameters? | 36,901 | 833 | 2008-08-31T15:04:35Z | 34,899,056 | 12 | 2016-01-20T11:40:54Z | [
"python",
"syntax",
"parameter-passing",
"identifier",
"kwargs"
] | In the following method definitions, what does the `*` and `**` do for `param2`?
```
def foo(param1, *param2):
def bar(param1, **param2):
``` | Let us first understand what are positional arguments and keyword arguments.
Below is an example of function definition with **Positional arguments.**
```
def test(a,b,c):
print(a)
print(b)
print(c)
test(1,2,3)
#output:
1
2
3
```
So this is a function definition with positional arguments.
You can call it with keyword/named arguments as well:
```
def test(a,b,c):
print(a)
print(b)
print(c)
test(a=1,b=2,c=3)
#output:
1
2
3
```
Now let us study an example of function definition with **keyword arguments**:
```
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(a=1,b=2,c=3)
#output :
1
2
3
-------------------------
```
You can call this function with positional arguments as well:
```
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(1,2,3)
# output :
1
2
3
---------------------------------
```
So we now know function definitions with positional as well as keyword arguments.
Now let us study the '\*' operator and '\*\*' operator.
Please note these operators can be used in 2 areas:
a) **function call**
b) **function definition**
The use of '\*' operator and '\*\*' operator in **function call.**
Let us get straight to an example and then discuss it.
```
def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2)
print(a+b)
my_tuple = (1,2)
my_list = [1,2]
my_dict = {'a':1,'b':2}
# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator
sum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*'
sum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*'
sum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**'
# output is 3 in all three calls to sum function.
```
So remember
when the '\*' or '\*\*' operator is used in a **function call** -
'\*' operator unpacks data structure such as a list or tuple into arguments needed by function definition.
'\*\*' operator unpacks a dictionary into arguments needed by function definition.
Now let us study the '\*' operator use in **function definition**.
Example:
```
def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))
sum = 0
for a in args:
sum+=a
print(sum)
sum(1,2,3,4) #positional args sent to function sum
#output:
10
```
In function **definition** the '\*' operator packs the received arguments into a tuple.
Now let us see an example of '\*\*' used in function definition:
```
def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})
sum=0
for k,v in args.items():
sum+=v
print(sum)
sum(a=1,b=2,c=3,d=4) #positional args sent to function sum
```
In function **definition** The '\*\*' operator packs the received arguments into a dictionary.
So remember:
In a **function call** the '\*' **unpacks** data structure of tuple or list into positional or keyword arguments to be received by function definition.
In a **function call** the '\*\*' **unpacks** data structure of dictionary into positional or keyword arguments to be received by function definition.
In a **function definition** the '\*' **packs** positional arguments into a tuple.
In a **function definition** the '\*\*' **packs** keyword arguments into a dictionary. |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 36,937 | 610 | 2008-08-31T16:06:14Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | Before PEP 435, Python didn't have an equivalent but you could implement your own.
Myself, I like keeping it simple (I've seen some horribly complex examples on the net), something like this ...
```
class Animal:
DOG = 1
CAT = 2
x = Animal.DOG
```
---
In Python 3.4 ([PEP 435](http://www.python.org/dev/peps/pep-0435/)), you can make Enum the base class. This gets you a little bit of extra functionality, described in the PEP. For example, enum values are distinct from integers.
```
class Animal(Enum):
DOG = 1
CAT = 2
print(Animal.DOG)
<Animal.DOG: 1>
```
---
If you don't want to type the values, use the following shortcut:
```
class Animal(Enum):
DOG, CAT = range(2)
``` |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 36,940 | 17 | 2008-08-31T16:09:53Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | Hmmm... I suppose the closest thing to an enum would be a dictionary, defined either like this:
```
months = {
'January': 1,
'February': 2,
...
}
```
or
```
months = dict(
January=1,
February=2,
...
)
```
Then, you can use the symbolic name for the constants like this:
```
mymonth = months['January']
```
There are other options, like a list of tuples, or a tuple of tuples, but the dictionary is the only one that provides you with a "symbolic" (constant string) way to access the
value.
Edit: I like Alexandru's answer too! |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 37,000 | 42 | 2008-08-31T18:10:50Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | Python doesn't have a built-in equivalent to `enum`, and other answers have ideas for implementing your own (you may also be interested in the [over the top version](http://code.activestate.com/recipes/67107/) in the Python cookbook).
However, in situations where an `enum` would be called for in C, I usually end up ***just using simple strings***: because of the way objects/attributes are implemented, (C)Python is optimized to work very fast with short strings anyway, so there wouldn't really be any performance benefit to using integers. To guard against typos / invalid values you can insert checks in selected places.
```
ANIMALS = ['cat', 'dog', 'python']
def take_for_a_walk(animal):
assert animal in ANIMALS
...
```
(One disadvantage compared to using a class is that you lose the benefit of autocomplete) |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 37,081 | 140 | 2008-08-31T20:31:22Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | If you need the numeric values, here's the quickest way:
```
dog, cat, rabbit = range(3)
``` |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 38,092 | 72 | 2008-09-01T16:05:25Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | The typesafe enum pattern which was used in Java pre-JDK 5 has a
number of advantages. Much like in Alexandru's answer, you create a
class and class level fields are the enum values; however, the enum
values are instances of the class rather than small integers. This has
the advantage that your enum values don't inadvertently compare equal
to small integers, you can control how they're printed, add arbitrary
methods if that's useful and make assertions using isinstance:
```
class Animal:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return "<Animal: %s>" % self
Animal.DOG = Animal("dog")
Animal.CAT = Animal("cat")
>>> x = Animal.DOG
>>> x
<Animal: dog>
>>> x == 1
False
```
---
A recent [thread on python-dev](http://mail.python.org/pipermail/python-dev/2010-November/105873.html) pointed out there are a couple of enum libraries in the wild, including:
* [flufl.enum](http://packages.python.org/flufl.enum/docs/using.html)
* [lazr.enum](http://pypi.python.org/pypi/lazr.enum)
* ... and the imaginatively named [enum](http://pypi.python.org/pypi/enum/) |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 38,762 | 13 | 2008-09-02T03:20:30Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | davidg recommends using dicts. I'd go one step further and use sets:
```
months = set('January', 'February', ..., 'December')
```
Now you can test whether a value matches one of the values in the set like this:
```
if m in months:
```
like dF, though, I usually just use string constants in place of enums. |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 107,973 | 26 | 2008-09-20T11:49:38Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | ```
def M_add_class_attribs(attribs):
def foo(name, bases, dict_):
for v, k in attribs:
dict_[k] = v
return type(name, bases, dict_)
return foo
def enum(*names):
class Foo(object):
__metaclass__ = M_add_class_attribs(enumerate(names))
def __setattr__(self, name, value): # this makes it read-only
raise NotImplementedError
return Foo()
```
Use it like this:
```
Animal = enum('DOG', 'CAT')
Animal.DOG # returns 0
Animal.CAT # returns 1
Animal.DOG = 2 # raises NotImplementedError
```
if you just want unique symbols and don't care about the values, replace this line:
```
__metaclass__ = M_add_class_attribs(enumerate(names))
```
with this:
```
__metaclass__ = M_add_class_attribs((object(), name) for name in names)
``` |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 505,457 | 14 | 2009-02-02T23:39:53Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | What I use:
```
class Enum(object):
def __init__(self, names, separator=None):
self.names = names.split(separator)
for value, name in enumerate(self.names):
setattr(self, name.upper(), value)
def tuples(self):
return tuple(enumerate(self.names))
```
How to use:
```
>>> state = Enum('draft published retracted')
>>> state.DRAFT
0
>>> state.RETRACTED
2
>>> state.FOO
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Enum' object has no attribute 'FOO'
>>> state.tuples()
((0, 'draft'), (1, 'published'), (2, 'retracted'))
```
So this gives you integer constants like state.PUBLISHED and the two-tuples to use as choices in Django models. |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 1,529,241 | 101 | 2009-10-07T02:47:33Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | The best solution for you would depend on what you require from your *fake* **`enum`**.
**Simple enum:**
If you need the **`enum`** as only a list of *names* identifying different *items*, the solution by **Mark Harrison** (above) is great:
```
Pen, Pencil, Eraser = range(0, 3)
```
Using a **`range`** also allows you to set any *starting value*:
```
Pen, Pencil, Eraser = range(9, 12)
```
In addition to the above, if you also require that the items belong to a *container* of some sort, then embed them in a class:
```
class Stationery:
Pen, Pencil, Eraser = range(0, 3)
```
To use the enum item, you would now need to use the container name and the item name:
```
stype = Stationery.Pen
```
**Complex enum:**
For long lists of enum or more complicated uses of enum, these solutions will not suffice. You could look to the recipe by Will Ware for *Simulating Enumerations in Python* published in the *Python Cookbook*. An online version of that is available [here](http://code.activestate.com/recipes/67107/).
**More info:**
[*PEP 354: Enumerations in Python*](http://www.python.org/dev/peps/pep-0354/) has the interesting details of a proposal for enum in Python and why it was rejected. |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 1,695,250 | 1,857 | 2009-11-08T03:15:28Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | Enums have been added to Python 3.4 as described in [PEP 435](http://www.python.org/dev/peps/pep-0435/). It has also been [backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4](https://pypi.python.org/pypi/enum34) on pypi.
For more advanced Enum techniques try the [aenum library](https://pypi.python.org/pypi/aenum) (2.7, 3.3+, same author as `enum34`. Code is not perfectly compatible between py2 and py3, e.g. you'll need [`__order__` in python 2](http://stackoverflow.com/a/25982264/57461)).
* To use `enum34`, do `$ pip install enum34`
* To use `aenum`, do `$ pip install aenum`
Installing `enum` (no numbers) will install a completely different and incompatible version.
---
```
from enum import Enum # for enum34, or the stdlib version
# from aenum import Enum # for the aenum version
Animal = Enum('Animal', 'ant bee cat dog')
Animal.ant # returns <Animal.ant: 1>
Animal['ant'] # returns <Animal.ant: 1> (string lookup)
Animal.ant.name # returns 'ant' (inverse lookup)
```
or equivalently:
```
class Animal(Enum):
ant = 1
bee = 2
cat = 3
dog = 4
```
---
In earlier versions, one way of accomplishing enums is:
```
def enum(**enums):
return type('Enum', (), enums)
```
which is used like so:
```
>>> Numbers = enum(ONE=1, TWO=2, THREE='three')
>>> Numbers.ONE
1
>>> Numbers.TWO
2
>>> Numbers.THREE
'three'
```
You can also easily support automatic enumeration with something like this:
```
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
```
and used like so:
```
>>> Numbers = enum('ZERO', 'ONE', 'TWO')
>>> Numbers.ZERO
0
>>> Numbers.ONE
1
```
Support for converting the values back to names can be added this way:
```
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
reverse = dict((value, key) for key, value in enums.iteritems())
enums['reverse_mapping'] = reverse
return type('Enum', (), enums)
```
This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw KeyError if the reverse mapping doesn't exist. With the first example:
```
>>> Numbers.reverse_mapping['three']
'THREE'
``` |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 1,753,340 | 11 | 2009-11-18T02:51:40Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | This is the best one I have seen: "First Class Enums in Python"
<http://code.activestate.com/recipes/413486/>
It gives you a class, and the class contains all the enums. The enums can be compared to each other, but don't have any particular value; you can't use them as an integer value. (I resisted this at first because I am used to C enums, which are integer values. But if you can't use it as an integer, you can't use it as an integer by mistake so overall I think it is a win.) Each enum is a unique value. You can print enums, you can iterate over them, you can test that an enum value is "in" the enum. It's pretty complete and slick.
Edit (cfi): The above link is not Python 3 compatible. Here's my port of enum.py to Python 3:
```
def cmp(a,b):
if a < b: return -1
if b < a: return 1
return 0
def Enum(*names):
##assert names, "Empty enums are not supported" # <- Don't like empty enums? Uncomment!
class EnumClass(object):
__slots__ = names
def __iter__(self): return iter(constants)
def __len__(self): return len(constants)
def __getitem__(self, i): return constants[i]
def __repr__(self): return 'Enum' + str(names)
def __str__(self): return 'enum ' + str(constants)
class EnumValue(object):
__slots__ = ('__value')
def __init__(self, value): self.__value = value
Value = property(lambda self: self.__value)
EnumType = property(lambda self: EnumType)
def __hash__(self): return hash(self.__value)
def __cmp__(self, other):
# C fans might want to remove the following assertion
# to make all enums comparable by ordinal value {;))
assert self.EnumType is other.EnumType, "Only values from the same enum are comparable"
return cmp(self.__value, other.__value)
def __lt__(self, other): return self.__cmp__(other) < 0
def __eq__(self, other): return self.__cmp__(other) == 0
def __invert__(self): return constants[maximum - self.__value]
def __nonzero__(self): return bool(self.__value)
def __repr__(self): return str(names[self.__value])
maximum = len(names) - 1
constants = [None] * len(names)
for i, each in enumerate(names):
val = EnumValue(i)
setattr(EnumClass, each, val)
constants[i] = val
constants = tuple(constants)
EnumType = EnumClass()
return EnumType
if __name__ == '__main__':
print( '\n*** Enum Demo ***')
print( '--- Days of week ---')
Days = Enum('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su')
print( Days)
print( Days.Mo)
print( Days.Fr)
print( Days.Mo < Days.Fr)
print( list(Days))
for each in Days:
print( 'Day:', each)
print( '--- Yes/No ---')
Confirmation = Enum('No', 'Yes')
answer = Confirmation.No
print( 'Your answer is not', ~answer)
``` |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 2,182,437 | 270 | 2010-02-02T07:21:46Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | Here is one implementation:
```
class Enum(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
```
Here is its usage:
```
Animals = Enum(["DOG", "CAT", "HORSE"])
print(Animals.DOG)
``` |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 4,092,436 | 37 | 2010-11-03T23:02:54Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | So, I agree. Let's not enforce type safety in Python, but I would like to protect myself from silly mistakes. So what do we think about this?
```
class Animal(object):
values = ['Horse','Dog','Cat']
class __metaclass__(type):
def __getattr__(self, name):
return self.values.index(name)
```
It keeps me from value-collision in defining my enums.
```
>>> Animal.Cat
2
```
There's another handy advantage: really fast reverse lookups:
```
def name_of(self, i):
return self.values[i]
``` |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 4,300,343 | 25 | 2010-11-29T02:05:55Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | I prefer to define enums in Python like so:
```
class Animal:
class Dog: pass
class Cat: pass
x = Animal.Dog
```
It's more bug-proof than using integers since you don't have to worry about ensuring that the integers are unique (e.g. if you said Dog = 1 and Cat = 1 you'd be screwed).
It's more bug-proof than using strings since you don't have to worry about typos (e.g.
x == "catt" fails silently, but x == Animal.Catt is a runtime exception). |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 6,971,002 | 16 | 2011-08-07T05:51:01Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | Another, very simple, implementation of an enum in Python, using `namedtuple`:
```
from collections import namedtuple
def enum(*keys):
return namedtuple('Enum', keys)(*keys)
MyEnum = enum('FOO', 'BAR', 'BAZ')
```
or, alternatively,
```
# With sequential number values
def enum(*keys):
return namedtuple('Enum', keys)(*range(len(keys)))
# From a dict / keyword args
def enum(**kwargs):
return namedtuple('Enum', kwargs.keys())(*kwargs.values())
```
Like the method above that subclasses `set`, this allows:
```
'FOO' in MyEnum
other = MyEnum.FOO
assert other == MyEnum.FOO
```
But has more flexibility as it can have different keys and values. This allows
```
MyEnum.FOO < MyEnum.BAR
```
to act as is expected if you use the version that fills in sequential number values. |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 8,598,742 | 8 | 2011-12-22T02:16:04Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | I have had occasion to need of an Enum class, for the purpose of decoding a binary file format. The features I happened to want is concise enum definition, the ability to freely create instances of the enum by either integer value or string, and a useful `repr`esentation. Here's what I ended up with:
```
>>> class Enum(int):
... def __new__(cls, value):
... if isinstance(value, str):
... return getattr(cls, value)
... elif isinstance(value, int):
... return cls.__index[value]
... def __str__(self): return self.__name
... def __repr__(self): return "%s.%s" % (type(self).__name__, self.__name)
... class __metaclass__(type):
... def __new__(mcls, name, bases, attrs):
... attrs['__slots__'] = ['_Enum__name']
... cls = type.__new__(mcls, name, bases, attrs)
... cls._Enum__index = _index = {}
... for base in reversed(bases):
... if hasattr(base, '_Enum__index'):
... _index.update(base._Enum__index)
... # create all of the instances of the new class
... for attr in attrs.keys():
... value = attrs[attr]
... if isinstance(value, int):
... evalue = int.__new__(cls, value)
... evalue._Enum__name = attr
... _index[value] = evalue
... setattr(cls, attr, evalue)
... return cls
...
```
A whimsical example of using it:
```
>>> class Citrus(Enum):
... Lemon = 1
... Lime = 2
...
>>> Citrus.Lemon
Citrus.Lemon
>>>
>>> Citrus(1)
Citrus.Lemon
>>> Citrus(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __new__
KeyError: 5
>>> class Fruit(Citrus):
... Apple = 3
... Banana = 4
...
>>> Fruit.Apple
Fruit.Apple
>>> Fruit.Lemon
Citrus.Lemon
>>> Fruit(1)
Citrus.Lemon
>>> Fruit(3)
Fruit.Apple
>>> "%d %s %r" % ((Fruit.Apple,)*3)
'3 Apple Fruit.Apple'
>>> Fruit(1) is Citrus.Lemon
True
```
Key features:
* `str()`, `int()` and `repr()` all produce the most useful output possible, respectively the name of the enumartion, its integer value, and a Python expression that evaluates back to the enumeration.
* Enumerated values returned by the constructor are limited strictly to the predefined values, no accidental enum values.
* Enumerated values are singletons; they can be strictly compared with `is` |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 9,201,329 | 44 | 2012-02-08T20:59:58Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | An Enum class can be a one-liner.
```
class Enum(tuple): __getattr__ = tuple.index
```
How to use it (forward and reverse lookup, keys, values, items, etc.)
```
>>> State = Enum(['Unclaimed', 'Claimed'])
>>> State.Claimed
1
>>> State[1]
'Claimed'
>>> State
('Unclaimed', 'Claimed')
>>> range(len(State))
[0, 1]
>>> [(k, State[k]) for k in range(len(State))]
[(0, 'Unclaimed'), (1, 'Claimed')]
>>> [(k, getattr(State, k)) for k in State]
[('Unclaimed', 0), ('Claimed', 1)]
``` |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 16,486,444 | 23 | 2013-05-10T16:09:02Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | On 2013-05-10, Guido agreed to accept [PEP 435](http://www.python.org/dev/peps/pep-0435/) into the Python 3.4 standard library. This means that Python finally has builtin support for enumerations!
There is a backport available for Python 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4. It's on Pypi as [enum34](https://pypi.python.org/pypi/enum34).
Declaration:
```
>>> from enum import Enum
>>> class Color(Enum):
... red = 1
... green = 2
... blue = 3
```
Representation:
```
>>> print(Color.red)
Color.red
>>> print(repr(Color.red))
<Color.red: 1>
```
Iteration:
```
>>> for color in Color:
... print(color)
...
Color.red
Color.green
Color.blue
```
Programmatic access:
```
>>> Color(1)
Color.red
>>> Color['blue']
Color.blue
```
For more information, refer to [the proposal](http://www.python.org/dev/peps/pep-0435/). Official documentation will probably follow soon. |
How can I represent an 'Enum' in Python? | 36,932 | 1,146 | 2008-08-31T15:55:47Z | 22,723,724 | 8 | 2014-03-28T21:44:30Z | [
"python",
"python-3.x",
"enums"
] | I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python? | Keep it simple:
```
class Enum(object):
def __init__(self, tupleList):
self.tupleList = tupleList
def __getattr__(self, name):
return self.tupleList.index(name)
```
Then:
```
DIRECTION = Enum(('UP', 'DOWN', 'LEFT', 'RIGHT'))
DIRECTION.DOWN
1
``` |
Resources for lexing, tokenising and parsing in python | 36,953 | 45 | 2008-08-31T16:50:35Z | 107,187 | 23 | 2008-09-20T05:07:57Z | [
"python",
"parsing",
"resources",
"lex"
] | Can people point me to resources on lexing, parsing and tokenising with Python?
I'm doing a little hacking on an open source project ([hotwire](http://www.hotwire-shell.org/)) and wanted to do a few changes to the code that [lexes](http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/externals/shlex.py), [parses and tokenises](http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/command.py) the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.
I haven't worked on code to lex/parse/tokenise before, so I was thinking one approach would be to work through a tutorial or two on this aspect. I would hope to learn enough to navigate around the code I actually want to alter. Is there anything suitable out there? (Ideally it could be done in an afternoon without having to buy and read the dragon book first ...)
**Edit:** (7 Oct 2008) None of the below answers quite give what I want. With them I could generate parsers from scratch, but I want to learn how to write my own basic parser from scratch, not using lex and yacc or similar tools. Having done that I can then understand the existing code better.
So could someone point me to a tutorial where I can build a basic parser from scratch, using just python? | I'm a happy user of [PLY](http://www.dabeaz.com/ply/). It is a pure-Python implementation of Lex & Yacc, with lots of small niceties that make it quite Pythonic and easy to use. Since Lex & Yacc are the most popular lexing & parsing tools and are used for the most projects, PLY has the advantage of standing on giants' shoulders. A lot of knowledge exists online on Lex & Yacc, and you can freely apply it to PLY.
PLY also has a good [documentation page](http://www.dabeaz.com/ply/ply.html) with some simple examples to get you started.
For a listing of lots of Python parsing tools, see [this](http://nedbatchelder.com/text/python-parsers.html). |
Resources for lexing, tokenising and parsing in python | 36,953 | 45 | 2008-08-31T16:50:35Z | 137,207 | 15 | 2008-09-26T01:05:35Z | [
"python",
"parsing",
"resources",
"lex"
] | Can people point me to resources on lexing, parsing and tokenising with Python?
I'm doing a little hacking on an open source project ([hotwire](http://www.hotwire-shell.org/)) and wanted to do a few changes to the code that [lexes](http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/externals/shlex.py), [parses and tokenises](http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/command.py) the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.
I haven't worked on code to lex/parse/tokenise before, so I was thinking one approach would be to work through a tutorial or two on this aspect. I would hope to learn enough to navigate around the code I actually want to alter. Is there anything suitable out there? (Ideally it could be done in an afternoon without having to buy and read the dragon book first ...)
**Edit:** (7 Oct 2008) None of the below answers quite give what I want. With them I could generate parsers from scratch, but I want to learn how to write my own basic parser from scratch, not using lex and yacc or similar tools. Having done that I can then understand the existing code better.
So could someone point me to a tutorial where I can build a basic parser from scratch, using just python? | For medium-complex grammars, [PyParsing](http://pyparsing.wikispaces.com/) is brilliant. You can define grammars directly within Python code, no need for code generation:
```
>>> from pyparsing import Word, alphas
>>> greet = Word( alphas ) + "," + Word( alphas ) + "!" # <-- grammar defined here
>>> hello = "Hello, World!"
>>>> print hello, "->", greet.parseString( hello )
Hello, World! -> ['Hello', ',', 'World', '!']
```
(Example taken from the PyParsing home page).
With parse actions (functions that are invoked when a certain grammar rule is triggered), you can convert parses directly into abstract syntax trees, or any other representation.
There are many helper functions that encapsulate recurring patterns, like operator hierarchies, quoted strings, nesting or C-style comments. |
Resources for lexing, tokenising and parsing in python | 36,953 | 45 | 2008-08-31T16:50:35Z | 14,315,179 | 11 | 2013-01-14T08:36:04Z | [
"python",
"parsing",
"resources",
"lex"
] | Can people point me to resources on lexing, parsing and tokenising with Python?
I'm doing a little hacking on an open source project ([hotwire](http://www.hotwire-shell.org/)) and wanted to do a few changes to the code that [lexes](http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/externals/shlex.py), [parses and tokenises](http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/command.py) the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.
I haven't worked on code to lex/parse/tokenise before, so I was thinking one approach would be to work through a tutorial or two on this aspect. I would hope to learn enough to navigate around the code I actually want to alter. Is there anything suitable out there? (Ideally it could be done in an afternoon without having to buy and read the dragon book first ...)
**Edit:** (7 Oct 2008) None of the below answers quite give what I want. With them I could generate parsers from scratch, but I want to learn how to write my own basic parser from scratch, not using lex and yacc or similar tools. Having done that I can then understand the existing code better.
So could someone point me to a tutorial where I can build a basic parser from scratch, using just python? | This question is pretty old, but maybe my answer would help someone who wants to learn the basics. I find this resource to be very good. It is a simple interpreter written in python without the use of any external libraries. So this will help anyone who would like to understand the internal working of parsing, lexing, and tokenising:
"A Simple Intepreter from Scratch in Python:" [Part 1](http://www.jayconrod.com/posts/37/a-simple-interpreter-from-scratch-in-python-part-1), [Part 2](http://www.jayconrod.com/posts/38/a-simple-interpreter-from-scratch-in-python-part-2),
[Part 3](http://www.jayconrod.com/posts/39/a-simple-interpreter-from-scratch-in-python-part-3), and [Part 4](http://www.jayconrod.com/posts/40/a-simple-interpreter-from-scratch-in-python-part-4). |
Filter out HTML tags and resolve entities in python | 37,486 | 15 | 2008-09-01T05:25:01Z | 37,506 | 15 | 2008-09-01T05:53:39Z | [
"python",
"html"
] | Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python. | Use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/)! It's perfect for this, where you have incoming markup of dubious virtue and need to get something reasonable out of it. Just pass in the original text, extract all the string tags, and join them. |
Filter out HTML tags and resolve entities in python | 37,486 | 15 | 2008-09-01T05:25:01Z | 37,512 | 38 | 2008-09-01T06:07:01Z | [
"python",
"html"
] | Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python. | Use [lxml](http://codespeak.net/lxml/lxmlhtml.html) which is the best xml/html library for python.
```
import lxml.html
t = lxml.html.fromstring("...")
t.text_content()
```
And if you just want to sanitize the html look at the lxml.html.clean [module](http://codespeak.net/lxml/lxmlhtml.html#cleaning-up-html) |
What's the easiest way to read a FoxPro DBF file from Python? | 37,535 | 21 | 2008-09-01T06:45:40Z | 37,553 | 7 | 2008-09-01T07:02:10Z | [
"python",
"foxpro",
"dbf",
"visual-foxpro"
] | I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too.
**Update**: Thanks @cnu, I used Yusdi Santoso's [`dbf.py`](http://www.physics.ox.ac.uk/users/santoso/dbf.py.src) and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. `.fpt`, not `.FPT` which was how the filename came over from Windows. | You can try this [recipe on Active State](http://code.activestate.com/recipes/362715/).
There is also a [DBFReader module](http://code.google.com/p/lino/source/browse/lino/utils/dbfreader.py) which you can try.
For support for [memo fields](http://www.physics.ox.ac.uk/users/santoso/dbf.py.src). |
What's the easiest way to read a FoxPro DBF file from Python? | 37,535 | 21 | 2008-09-01T06:45:40Z | 37,917 | 16 | 2008-09-01T13:12:53Z | [
"python",
"foxpro",
"dbf",
"visual-foxpro"
] | I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too.
**Update**: Thanks @cnu, I used Yusdi Santoso's [`dbf.py`](http://www.physics.ox.ac.uk/users/santoso/dbf.py.src) and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. `.fpt`, not `.FPT` which was how the filename came over from Windows. | I prefer [dbfpy](http://sourceforge.net/projects/dbfpy/). It supports both reading and writing of `.DBF` files and can cope with most variations of the format. It's the only implementation I have found that could both read and write the legacy DBF files of some older systems I have worked with. |
What's the easiest way to read a FoxPro DBF file from Python? | 37,535 | 21 | 2008-09-01T06:45:40Z | 86,420 | 9 | 2008-09-17T18:59:49Z | [
"python",
"foxpro",
"dbf",
"visual-foxpro"
] | I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too.
**Update**: Thanks @cnu, I used Yusdi Santoso's [`dbf.py`](http://www.physics.ox.ac.uk/users/santoso/dbf.py.src) and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. `.fpt`, not `.FPT` which was how the filename came over from Windows. | If you're still checking this, I have a GPL FoxPro-to-PostgreSQL converter at <https://github.com/kstrauser/pgdbf> . We use it to routinely copy our tables into PostgreSQL for fast reporting. |
What's the easiest way to read a FoxPro DBF file from Python? | 37,535 | 21 | 2008-09-01T06:45:40Z | 10,254,842 | 8 | 2012-04-20T23:33:30Z | [
"python",
"foxpro",
"dbf",
"visual-foxpro"
] | I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too.
**Update**: Thanks @cnu, I used Yusdi Santoso's [`dbf.py`](http://www.physics.ox.ac.uk/users/santoso/dbf.py.src) and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. `.fpt`, not `.FPT` which was how the filename came over from Windows. | I was able to read a DBF file (with associated BAK, CDX, FBT, TBK files\*\*) using the dbf package from PyPI <http://pypi.python.org/pypi/dbf> . I am new to python and know nothing about DBF files, but it worked easily to read a DBF file from my girlfriend's business (created with a music store POS application called AIMsi).
After installing the dbf package (I used aptitude and installed dbf version 0.88 I think), the following python code worked:
```
from dbf import *
test = Table("testfile.dbf")
for record in test:
print record
x = raw_input("") # to pause between showing records
```
That's all I know for now, but hopefully it's a useful start for someone else who finds this question!
> April 21, 2012 SJK Edit: Per Ethan Furman's comment, I should point out that I actually don't know *which* of the data files were necessary, besides the DBF file. The first time I ran the script, with only the DBF available, it complained of a missing support file. So, I just copied over the BAK, CDX, FPT (not FBT as I said before edit), TBK files and then it worked. |
What are Class methods in Python for? | 38,238 | 194 | 2008-09-01T18:16:41Z | 38,254 | 22 | 2008-09-01T18:27:27Z | [
"python",
"class-method"
] | I'm teaching myself Python and my most recent lesson was that [Python is not Java](http://dirtsimple.org/2004/12/python-is-not-java.html), and so I've just spent a while turning all my Class methods into functions.
I now realise that I don't need to use Class methods for what I would done with `static` methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.
Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used? | Alternative constructors are the classic example. |
What are Class methods in Python for? | 38,238 | 194 | 2008-09-01T18:16:41Z | 38,276 | 142 | 2008-09-01T18:45:56Z | [
"python",
"class-method"
] | I'm teaching myself Python and my most recent lesson was that [Python is not Java](http://dirtsimple.org/2004/12/python-is-not-java.html), and so I've just spent a while turning all my Class methods into functions.
I now realise that I don't need to use Class methods for what I would done with `static` methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.
Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used? | Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functions.
If you have a class `MyClass`, and a module-level function that operates on MyClass (factory, dependency injection stub, etc), make it a `classmethod`. Then it'll be available to subclasses. |
What are Class methods in Python for? | 38,238 | 194 | 2008-09-01T18:16:41Z | 38,303 | 53 | 2008-09-01T19:08:25Z | [
"python",
"class-method"
] | I'm teaching myself Python and my most recent lesson was that [Python is not Java](http://dirtsimple.org/2004/12/python-is-not-java.html), and so I've just spent a while turning all my Class methods into functions.
I now realise that I don't need to use Class methods for what I would done with `static` methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.
Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used? | Factory methods (alternative constructors) are indeed a classic example of class methods.
Basically, class methods are suitable anytime you would like to have a method which naturally fits into the namespace of the class, but is not associated with a particular instance of the class.
As an example, in the excellent [unipath](http://pypi.python.org/pypi/Unipath/0.2.1) module:
## Current directory
* `Path.cwd()`
+ Return the actual current directory; e.g., `Path("/tmp/my_temp_dir")`. This is a class method.
* `.chdir()`
+ Make self the current directory.
As the current directory is process wide, the `cwd` method has no particular instance with which it should be associated. However, changing the `cwd` to the directory of a given `Path` instance should indeed be an instance method.
Hmmm... as `Path.cwd()` does indeed return a `Path` instance, I guess it could be considered to be a factory method... |
What are Class methods in Python for? | 38,238 | 194 | 2008-09-01T18:16:41Z | 2,807,576 | 23 | 2010-05-11T01:48:33Z | [
"python",
"class-method"
] | I'm teaching myself Python and my most recent lesson was that [Python is not Java](http://dirtsimple.org/2004/12/python-is-not-java.html), and so I've just spent a while turning all my Class methods into functions.
I now realise that I don't need to use Class methods for what I would done with `static` methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.
Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used? | I recently wanted a very light-weight logging class that would output varying amounts of output depending on the logging level that could be programmatically set. But I didn't want to instantiate the class every time I wanted to output a debugging message or error or warning. But I also wanted to encapsulate the functioning of this logging facility and make it reusable without the declaration of any globals.
So I used class variables and the `@classmethod` decorator to achieve this.
With my simple Logging class, I could do the following:
```
Logger._level = Logger.DEBUG
```
Then, in my code, if I wanted to spit out a bunch of debugging information, I simply had to code
```
Logger.debug( "this is some annoying message I only want to see while debugging" )
```
Errors could be out put with
```
Logger.error( "Wow, something really awful happened." )
```
In the "production" environment, I can specify
```
Logger._level = Logger.ERROR
```
and now, only the error message will be output. The debug message will not be printed.
Here's my class:
```
class Logger :
''' Handles logging of debugging and error messages. '''
DEBUG = 5
INFO = 4
WARN = 3
ERROR = 2
FATAL = 1
_level = DEBUG
def __init__( self ) :
Logger._level = Logger.DEBUG
@classmethod
def isLevel( cls, level ) :
return cls._level >= level
@classmethod
def debug( cls, message ) :
if cls.isLevel( Logger.DEBUG ) :
print "DEBUG: " + message
@classmethod
def info( cls, message ) :
if cls.isLevel( Logger.INFO ) :
print "INFO : " + message
@classmethod
def warn( cls, message ) :
if cls.isLevel( Logger.WARN ) :
print "WARN : " + message
@classmethod
def error( cls, message ) :
if cls.isLevel( Logger.ERROR ) :
print "ERROR: " + message
@classmethod
def fatal( cls, message ) :
if cls.isLevel( Logger.FATAL ) :
print "FATAL: " + message
```
And some code that tests it just a bit:
```
def logAll() :
Logger.debug( "This is a Debug message." )
Logger.info ( "This is a Info message." )
Logger.warn ( "This is a Warn message." )
Logger.error( "This is a Error message." )
Logger.fatal( "This is a Fatal message." )
if __name__ == '__main__' :
print "Should see all DEBUG and higher"
Logger._level = Logger.DEBUG
logAll()
print "Should see all ERROR and higher"
Logger._level = Logger.ERROR
logAll()
``` |
What are Class methods in Python for? | 38,238 | 194 | 2008-09-01T18:16:41Z | 3,521,920 | 37 | 2010-08-19T12:51:27Z | [
"python",
"class-method"
] | I'm teaching myself Python and my most recent lesson was that [Python is not Java](http://dirtsimple.org/2004/12/python-is-not-java.html), and so I've just spent a while turning all my Class methods into functions.
I now realise that I don't need to use Class methods for what I would done with `static` methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.
Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used? | Think about it this way: normal methods are useful to hide the details of dispatch: you can type `myobj.foo()` without worrying about whether the `foo()` method is implemented by the `myobj` object's class or one of its parent classes. Class methods are exactly analogous to this, but with the class object instead: they let you call `MyClass.foo()` without having to worry about whether `foo()` is implemented specially by `MyClass` because it needed its own specialized version, or whether it is letting its parent class handle the call.
Class methods are essential when you are doing set-up or computation that *precedes* the creation of an actual instance, because until the instance exists you obviously cannot use the instance as the dispatch point for your method calls. A good example can be viewed in the SQLAlchemy source code; take a look at the `dbapi()` class method at the following link:
<https://github.com/zzzeek/sqlalchemy/blob/ab6946769742602e40fb9ed9dde5f642885d1906/lib/sqlalchemy/dialects/mssql/pymssql.py#L47>
You can see that the `dbapi()` method, which a database backend uses to import the vendor-specific database library it needs on-demand, is a class method because it needs to run *before* instances of a particular database connection start getting created â but that it cannot be a simple function or static function, because they want it to be able to call other, supporting methods that might similarly need to be written more specifically in subclasses than in their parent class. And if you dispatch to a function or static class, then you "forget" and lose the knowledge about which class is doing the initializing. |
What are Class methods in Python for? | 38,238 | 194 | 2008-09-01T18:16:41Z | 6,001,200 | 8 | 2011-05-14T10:24:32Z | [
"python",
"class-method"
] | I'm teaching myself Python and my most recent lesson was that [Python is not Java](http://dirtsimple.org/2004/12/python-is-not-java.html), and so I've just spent a while turning all my Class methods into functions.
I now realise that I don't need to use Class methods for what I would done with `static` methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.
Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used? | I think the most clear answer is **AmanKow's** one. It boils down to how u want to organize your code. You can write everything as module level functions which are wrapped in the namespace of the module i.e
```
module.py (file 1)
---------
def f1() : pass
def f2() : pass
def f3() : pass
usage.py (file 2)
--------
from module import *
f1()
f2()
f3()
def f4():pass
def f5():pass
usage1.py (file 3)
-------------------
from usage import f4,f5
f4()
f5()
```
The above procedural code is not well organized, as you can see after only 3 modules it gets confusing, what is each method do ? You can use long descriptive names for functions(like in java) but still your code gets unmanageable very quick.
The object oriented way is to break down your code into manageable blocks i.e Classes & objects and functions can be associated with objects instances or with classes.
With class functions you gain another level of division in your code compared with module level functions.
So you can group related functions within a class to make them more specific to a task that you assigned to that class. For example you can create a file utility class :
```
class FileUtil ():
def copy(source,dest):pass
def move(source,dest):pass
def copyDir(source,dest):pass
def moveDir(source,dest):pass
//usage
FileUtil.copy("1.txt","2.txt")
FileUtil.moveDir("dir1","dir2")
```
This way is more flexible and more maintainable, you group functions together and its more obvious to what each function do. Also you prevent name conflicts, for example the function copy may exist in another imported module(for example network copy) that you use in your code, so when you use the full name FileUtil.copy() you remove the problem and both copy functions can be used side by side. |
What's the best way to return multiple values from a function in Python? | 38,508 | 49 | 2008-09-01T22:01:02Z | 38,513 | 7 | 2008-09-01T22:03:17Z | [
"python",
"variables",
"return"
] | I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string.
In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.
Related question: [Is it pythonic for a function to return multiple values?](http://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values) | Returning a tuple is the usual way to do this in Python. |
What's the best way to return multiple values from a function in Python? | 38,508 | 49 | 2008-09-01T22:01:02Z | 38,514 | 14 | 2008-09-01T22:03:41Z | [
"python",
"variables",
"return"
] | I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string.
In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.
Related question: [Is it pythonic for a function to return multiple values?](http://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values) | Return a tuple.
```
def f(x):
# do stuff
return (True, modified_string)
success, modified_string = f(something)
``` |
What's the best way to return multiple values from a function in Python? | 38,508 | 49 | 2008-09-01T22:01:02Z | 38,516 | 105 | 2008-09-01T22:04:02Z | [
"python",
"variables",
"return"
] | I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string.
In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.
Related question: [Is it pythonic for a function to return multiple values?](http://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values) | ```
def f(in_str):
out_str = in_str.upper()
return True, out_str # Creates tuple automatically
succeeded, b = f("a") # Automatic tuple unpacking
``` |
What's the best way to return multiple values from a function in Python? | 38,508 | 49 | 2008-09-01T22:01:02Z | 38,524 | 27 | 2008-09-01T22:09:00Z | [
"python",
"variables",
"return"
] | I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string.
In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.
Related question: [Is it pythonic for a function to return multiple values?](http://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values) | Why not throw an exception if the operation wasn't successful? Personally, I tend to be of the opinion that if you need to return more than one value from a function, you should reconsider if you're doing things the right way or use an object.
But more directly to the point, if you throw an exception, you're forcing them to deal with the problem. If you try to return a value that indicates failure, it's very well possible somebody could not check the value and end up with some potentially hard to debug errors. |
Using Django time/date widgets in custom form | 38,601 | 147 | 2008-09-01T23:22:55Z | 38,916 | 141 | 2008-09-02T06:10:58Z | [
"python",
"django"
] | How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?
I have looked through [the Django forms documentation](https://docs.djangoproject.com/en/dev/topics/forms/), and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?
Here is my template that I want it applied on.
```
<form action="." method="POST">
<table>
{% for f in form %}
<tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr>
{% endfor %}
</table>
<input type="submit" name="submit" value="Add Product">
</form>
```
Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:
```
(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
```
And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy... | The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that.
That said, here's what you have to do if you're determined to make this work:
1. Define your own ModelForm subclass for your model (best to put it in forms.py in your app), and tell it to use the AdminDateWidget / AdminTimeWidget / AdminSplitDateTime (replace 'mydate' etc with the proper field names from your model):
```
from django import forms
from my_app.models import Product
from django.contrib.admin import widgets
class ProductForm(forms.ModelForm):
class Meta:
model = Product
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['mydate'].widget = widgets.AdminDateWidget()
self.fields['mytime'].widget = widgets.AdminTimeWidget()
self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()
```
2. Change your URLconf to pass 'form\_class': ProductForm instead of 'model': Product to the generic create\_object view (that'll mean "from my\_app.forms import ProductForm" instead of "from my\_app.models import Product", of course).
3. In the head of your template, include {{ form.media }} to output the links to the Javascript files.
4. And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically. So in your template above {{ form.media }} you'll need:
```
<script type="text/javascript" src="/my_admin/jsi18n/"></script>
<script type="text/javascript" src="/media/admin/js/core.js"></script>
```
You may also wish to use the following admin CSS (thanks [Alex](http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/719583#719583) for mentioning this):
```
<link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/>
```
This implies that Django's admin media (ADMIN\_MEDIA\_PREFIX) is at /media/admin/ - you can change that for your setup. Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question.
This also requires that the URL /my\_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript\_catalog view (or null\_javascript\_catalog if you aren't using I18N). You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks [Jeremy](http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/408230#408230) for pointing this out). Sample code for your URLconf:
```
(r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'),
```
Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media:
```
{% load adminmedia %} /* At the top of the template. */
/* In the head section of the template. */
<script type="text/javascript">
window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";
</script>
```
Thanks [lupefiasco](http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/2818128#2818128) for this addition. |
Using Django time/date widgets in custom form | 38,601 | 147 | 2008-09-01T23:22:55Z | 72,284 | 57 | 2008-09-16T13:39:39Z | [
"python",
"django"
] | How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?
I have looked through [the Django forms documentation](https://docs.djangoproject.com/en/dev/topics/forms/), and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?
Here is my template that I want it applied on.
```
<form action="." method="POST">
<table>
{% for f in form %}
<tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr>
{% endfor %}
</table>
<input type="submit" name="submit" value="Add Product">
</form>
```
Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:
```
(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
```
And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy... | As the solution is hackish, I think using your own date/time widget with some JavaScript is more feasible. |
Using Django time/date widgets in custom form | 38,601 | 147 | 2008-09-01T23:22:55Z | 408,230 | 10 | 2009-01-02T22:53:21Z | [
"python",
"django"
] | How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?
I have looked through [the Django forms documentation](https://docs.djangoproject.com/en/dev/topics/forms/), and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?
Here is my template that I want it applied on.
```
<form action="." method="POST">
<table>
{% for f in form %}
<tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr>
{% endfor %}
</table>
<input type="submit" name="submit" value="Add Product">
</form>
```
Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:
```
(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
```
And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy... | Yep, I ended up overriding the /admin/jsi18n/ url.
Here's what I added in my urls.py. Make sure it's above the /admin/ url
```
(r'^admin/jsi18n', i18n_javascript),
```
And here is the i18n\_javascript function I created.
```
from django.contrib import admin
def i18n_javascript(request):
return admin.site.i18n_javascript(request)
``` |
Using Django time/date widgets in custom form | 38,601 | 147 | 2008-09-01T23:22:55Z | 1,392,329 | 8 | 2009-09-08T06:42:05Z | [
"python",
"django"
] | How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?
I have looked through [the Django forms documentation](https://docs.djangoproject.com/en/dev/topics/forms/), and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?
Here is my template that I want it applied on.
```
<form action="." method="POST">
<table>
{% for f in form %}
<tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr>
{% endfor %}
</table>
<input type="submit" name="submit" value="Add Product">
</form>
```
Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:
```
(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
```
And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy... | I find myself referencing this post a lot, and found that the [documentation](http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types) defines a *slightly* less hacky way to override default widgets.
(*No need to override the ModelForm's \_\_init\_\_ method*)
However, you still need to wire your JS and CSS appropriately as Carl mentions.
**forms.py**
```
from django import forms
from my_app.models import Product
from django.contrib.admin import widgets
class ProductForm(forms.ModelForm):
mydate = forms.DateField(widget=widgets.AdminDateWidget)
mytime = forms.TimeField(widget=widgets.AdminTimeWidget)
mydatetime = forms.DateTimeField(widget=widgets.AdminSplitDateTime)
class Meta:
model = Product
```
Reference [Field Types](http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#field-types) to find the default form fields. |
Using Django time/date widgets in custom form | 38,601 | 147 | 2008-09-01T23:22:55Z | 2,818,128 | 9 | 2010-05-12T11:03:15Z | [
"python",
"django"
] | How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?
I have looked through [the Django forms documentation](https://docs.djangoproject.com/en/dev/topics/forms/), and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?
Here is my template that I want it applied on.
```
<form action="." method="POST">
<table>
{% for f in form %}
<tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr>
{% endfor %}
</table>
<input type="submit" name="submit" value="Add Product">
</form>
```
Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:
```
(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
```
And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy... | Starting in Django 1.2 RC1, if you're using the Django admin date picker widge trick, the following has to be added to your template, or you'll see the calendar icon url being referenced through "/missing-admin-media-prefix/".
```
{% load adminmedia %} /* At the top of the template. */
/* In the head section of the template. */
<script type="text/javascript">
window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";
</script>
``` |
Using Django time/date widgets in custom form | 38,601 | 147 | 2008-09-01T23:22:55Z | 11,446,609 | 8 | 2012-07-12T07:06:08Z | [
"python",
"django"
] | How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?
I have looked through [the Django forms documentation](https://docs.djangoproject.com/en/dev/topics/forms/), and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?
Here is my template that I want it applied on.
```
<form action="." method="POST">
<table>
{% for f in form %}
<tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr>
{% endfor %}
</table>
<input type="submit" name="submit" value="Add Product">
</form>
```
Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:
```
(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
```
And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy... | My head code for 1.4 version(some new and some removed)
```
{% block extrahead %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/forms.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/global.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/widgets.css"/>
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/core.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/admin/RelatedObjectLookups.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.init.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/actions.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/calendar.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/admin/DateTimeShortcuts.js"></script>
{% endblock %}
``` |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 38,989 | 25 | 2008-09-02T07:49:27Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | ```
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = dict(x.items() + y.items())
print z
```
For items with keys in both dictionaries ('b'), you can control which one ends up in the output by putting that one last. |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 38,990 | 1,292 | 2008-09-02T07:50:12Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | In your case, what you can do is:
```
z = dict(x.items() + y.items())
```
This will, as you want it, put the final dict in `z`, and make the value for key `b` be properly overridden by the second (`y`) dict's value:
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = dict(x.items() + y.items())
>>> z
{'a': 1, 'c': 11, 'b': 10}
```
If you use Python 3, it is only a little more complicated. To create `z`:
```
>>> z = dict(list(x.items()) + list(y.items()))
>>> z
{'a': 1, 'c': 11, 'b': 10}
``` |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 39,437 | 472 | 2008-09-02T13:00:46Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | An alternative:
```
z = x.copy()
z.update(y)
``` |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 39,858 | 209 | 2008-09-02T15:52:07Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | Another, more concise, option:
```
z = dict(x, **y)
```
**Note**: this has become a popular answer, but it is important to point out that if `y` has any non-string keys, the fact that this works at all is an abuse of a CPython implementation detail, and it does not work in Python 3, or in PyPy, IronPython, or Jython. Also, [Guido is not a fan](http://mail.python.org/pipermail/python-dev/2010-April/099459.html). So I can't recommend this technique for forward-compatible or cross-implementation portable code, which really means it should be avoided entirely. |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 44,512 | 63 | 2008-09-04T19:08:25Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | I wanted something similar, but with the ability to specify how the values on duplicate keys were merged, so I hacked this out (but did not heavily test it). Obviously this is not a single expression, but it is a single function call.
```
def merge(d1, d2, merge_fn=lambda x,y:y):
"""
Merges two dictionaries, non-destructively, combining
values on duplicate keys as defined by the optional merge
function. The default behavior replaces the values in d1
with corresponding values in d2. (There is no other generally
applicable merge strategy, but often you'll have homogeneous
types in your dicts, so specifying a merge technique can be
valuable.)
Examples:
>>> d1
{'a': 1, 'c': 3, 'b': 2}
>>> merge(d1, d1)
{'a': 1, 'c': 3, 'b': 2}
>>> merge(d1, d1, lambda x,y: x+y)
{'a': 2, 'c': 6, 'b': 4}
"""
result = dict(d1)
for k,v in d2.iteritems():
if k in result:
result[k] = merge_fn(result[k], v)
else:
result[k] = v
return result
``` |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 49,492 | 136 | 2008-09-08T11:16:54Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | This probably won't be a popular answer, but you almost certainly do not want to do this. If you want a copy that's a merge, then use copy (or [deepcopy](https://docs.python.org/2/library/copy.html), depending on what you want) and then update. The two lines of code are much more readable - more Pythonic - than the single line creation with .items() + .items(). Explicit is better than implicit.
In addition, when you use .items() (pre Python 3.0), you're creating a new list that contains the items from the dict. If your dictionaries are large, then that is quite a lot of overhead (two large lists that will be thrown away as soon as the merged dict is created). update() can work more efficiently, because it can run through the second dict item-by-item.
In terms of [time](https://docs.python.org/2/library/timeit.html):
```
>>> timeit.Timer("dict(x, **y)", "x = dict(zip(range(1000), range(1000)))\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000)
15.52571702003479
>>> timeit.Timer("temp = x.copy()\ntemp.update(y)", "x = dict(zip(range(1000), range(1000)))\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000)
15.694622993469238
>>> timeit.Timer("dict(x.items() + y.items())", "x = dict(zip(range(1000), range(1000)))\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000)
41.484580039978027
```
IMO the tiny slowdown between the first two is worth it for the readability. In addition, keyword arguments for dictionary creation was only added in Python 2.3, whereas copy() and update() will work in older versions. |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 228,366 | 86 | 2008-10-23T02:38:56Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | In a follow-up answer, you asked about the relative performance of these two alternatives:
```
z1 = dict(x.items() + y.items())
z2 = dict(x, **y)
```
On my machine, at least (a fairly ordinary x86\_64 running Python 2.5.2), alternative `z2` is not only shorter and simpler but also significantly faster. You can verify this for yourself using the `timeit` module that comes with Python.
Example 1: identical dictionaries mapping 20 consecutive integers to themselves:
```
% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z1=dict(x.items() + y.items())'
100000 loops, best of 3: 5.67 usec per loop
% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z2=dict(x, **y)'
100000 loops, best of 3: 1.53 usec per loop
```
`z2` wins by a factor of 3.5 or so. Different dictionaries seem to yield quite different results, but `z2` always seems to come out ahead. (If you get inconsistent results for the *same* test, try passing in `-r` with a number larger than the default 3.)
Example 2: non-overlapping dictionaries mapping 252 short strings to integers and vice versa:
```
% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z1=dict(x.items() + y.items())'
1000 loops, best of 3: 260 usec per loop
% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z2=dict(x, **y)'
10000 loops, best of 3: 26.9 usec per loop
```
`z2` wins by about a factor of 10. That's a pretty big win in my book!
After comparing those two, I wondered if `z1`'s poor performance could be attributed to the overhead of constructing the two item lists, which in turn led me to wonder if this variation might work better:
```
from itertools import chain
z3 = dict(chain(x.iteritems(), y.iteritems()))
```
A few quick tests, e.g.
```
% python -m timeit -s 'from itertools import chain; from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z3=dict(chain(x.iteritems(), y.iteritems()))'
10000 loops, best of 3: 66 usec per loop
```
lead me to conclude that `z3` is somewhat faster than `z1`, but not nearly as fast as `z2`. Definitely not worth all the extra typing.
This discussion is still missing something important, which is a performance comparison of these alternatives with the "obvious" way of merging two lists: using the `update` method. To try to keep things on an equal footing with the expressions, none of which modify x or y, I'm going to make a copy of x instead of modifying it in-place, as follows:
```
z0 = dict(x)
z0.update(y)
```
A typical result:
```
% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z0=dict(x); z0.update(y)'
10000 loops, best of 3: 26.9 usec per loop
```
In other words, `z0` and `z2` seem to have essentially identical performance. Do you think this might be a coincidence? I don't....
In fact, I'd go so far as to claim that it's impossible for pure Python code to do any better than this. And if you can do significantly better in a C extension module, I imagine the Python folks might well be interested in incorporating your code (or a variation on your approach) into the Python core. Python uses `dict` in lots of places; optimizing its operations is a big deal.
You could also write this as
```
z0 = x.copy()
z0.update(y)
```
as Tony does, but (not surprisingly) the difference in notation turns out not to have any measurable effect on performance. Use whichever looks right to you. Of course, he's absolutely correct to point out that the two-statement version is much easier to understand. |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 3,936,548 | 39 | 2010-10-14T18:55:15Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | The best version I could think while not using copy would be:
```
from itertools import chain
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
dict(chain(x.iteritems(), y.iteritems()))
```
It's faster than `dict(x.items() + y.items())` but not as fast as `n = copy(a); n.update(b)`, at least on CPython. This version also works in Python 3 if you change `iteritems()` to `items()`, which is automatically done by the 2to3 tool.
Personally I like this version best because it describes fairly good what I want in a single functional syntax. The only minor problem is that it doesn't make completely obvious that values from y takes precedence over values from x, but I don't believe it's difficult to figure that out. |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 7,770,473 | 22 | 2011-10-14T16:12:33Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | While the question has already been answered several times,
this simple solution to the problem has not been listed yet.
```
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z4 = {}
z4.update(x)
z4.update(y)
```
It is as fast as z0 and the evil z2 mentioned above, but easy to understand and change. |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 8,247,023 | 15 | 2011-11-23T18:08:23Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | If you think lambdas are evil then read no further.
As requested, you can write the fast and memory-efficient solution with one expression:
```
x = {'a':1, 'b':2}
y = {'b':10, 'c':11}
z = (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)
print z
{'a': 1, 'c': 11, 'b': 10}
print x
{'a': 1, 'b': 2}
```
As suggested above, using two lines or writing a function is probably a better way to go. |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 8,310,229 | 32 | 2011-11-29T11:52:15Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | # Recursively/deep update a dict
```
def deepupdate(original, update):
"""
Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for key, value in original.iteritems():
if key not in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
return update
```
Demonstration:
```
pluto_original = {
'name': 'Pluto',
'details': {
'tail': True,
'color': 'orange'
}
}
pluto_update = {
'name': 'Pluutoo',
'details': {
'color': 'blue'
}
}
print deepupdate(pluto_original, pluto_update)
```
Outputs:
```
{
'name': 'Pluutoo',
'details': {
'color': 'blue',
'tail': True
}
}
```
Thanks rednaw for edits. |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 11,825,563 | 19 | 2012-08-06T09:24:44Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | ```
def dict_merge(a, b):
c = a.copy()
c.update(b)
return c
new = dict_merge(old, extras)
```
Among such shady and dubious answers, this shining example is the one and only good way to merge dicts in Python, endorsed by dictator for life *Guido van Rossum* himself! Someone else suggested half of this, but did not put it in a function.
```
print dict_merge(
{'color':'red', 'model':'Mini'},
{'model':'Ferrari', 'owner':'Carl'})
```
gives:
```
{'color': 'red', 'owner': 'Carl', 'model': 'Ferrari'}
``` |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 16,259,217 | 44 | 2013-04-28T03:15:38Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | In Python 3, you can use [*collections.ChainMap*](http://docs.python.org/3/library/collections.html#collections.ChainMap) which groups multiple dicts or other mappings together to create a single, updateable view:
```
>>> from collections import ChainMap
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = ChainMap({}, y, x)
>>> for k, v in z.items():
print(k, '-->', v)
a --> 1
b --> 10
c --> 11
``` |
How to merge two Python dictionaries in a single expression? | 38,987 | 1,867 | 2008-09-02T07:44:30Z | 18,114,065 | 7 | 2013-08-07T21:23:08Z | [
"python",
"dictionary",
"mapping",
"expression",
"idioms"
] | I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place.
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
```
How can I get that final merged dict in z, not x?
(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I'm looking for as well.) | Abuse leading to a one-expression solution for [Matthew's answer](http://stackoverflow.com/a/39437/15055):
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = (lambda f=x.copy(): (f.update(y), f)[1])()
>>> z
{'a': 1, 'c': 11, 'b': 10}
```
You said you wanted one expression, so I abused `lambda` to bind a name, and tuples to override lambda's one-expression limit. Feel free to cringe.
You could also do this of course if you don't care about copying it:
```
>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = (x.update(y), x)[1]
>>> z
{'a': 1, 'b': 10, 'c': 11}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.