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/wik... |
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.co... |
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... |
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-... |
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 i... | 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 h... |
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 i... | 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. Th... |
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 i... | 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 ... |
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 i... | 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,... |
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 i... | 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 ... |
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... | `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... | ```
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... |
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 ... | 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... |
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 ... | 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/):
> ``... |
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 ... | [`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 ... | 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 r... | 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 ... |
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 r... | 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 cont... |
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 r... | 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_c... |
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):
...... |
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/reci... |
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 ... |
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
... |
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 = []
s... |
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
```
Howe... |
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 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://w... | 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... |
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 ht... | 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 hav... |
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 ... | 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.... |
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 em... |
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... |
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... |
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="... |
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 `**... |
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... |
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... |
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[... |
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 **... |
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 inadve... |
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, ... |
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:
```
>>> sta... |
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 y... |
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.... |
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 beca... |
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)
```
... |
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 usi... |
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('Enu... |
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 Enu... |
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]
>>> [(... |
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.pyth... |
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),... | 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' ... |
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),... | 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, Wo... |
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),... | 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, ... |
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 n... | 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 n... | 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 n... | 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 n... | 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 A... |
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... | 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... | 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 functio... |
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... | 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 [... |
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... | 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 functi... |
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... | 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... |
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... | 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)
--------
fr... |
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 an... | 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 an... | 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 an... | ```
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 an... | 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 t... |
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 templa... | 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... |
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 templa... | 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 templa... | 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... |
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 templa... | 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 stil... |
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 templa... | 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 t... |
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 templa... | 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/cs... |
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': 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
>>>... | 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':... |
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
>>>... | 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
>>>... | 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.... |
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
>>>... | 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, n... |
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
>>>... | 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 sin... |
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
>>>... | 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... |
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
>>>... | 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 wor... |
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
>>>... | 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
>>>... | 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':... |
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
>>>... | # 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):
... |
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
>>>... | ```
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 n... |
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
>>>... | 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 = ChainM... |
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
>>>... | 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 na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.