title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
C-like structures in Python
35,988
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
210
2008-08-30T14:33:25Z
3,761,729
<p>Perhaps you are looking for Structs without constructors:</p> <pre><code>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 --&gt; OK. print v print "***" for v in s2.values: # prints 4 --&gt; OK. print v </code></pre>
56
2010-09-21T15:15:33Z
[ "python", "struct" ]
C-like structures in Python
35,988
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
210
2008-08-30T14:33:25Z
18,792,190
<p>Whenever I need an "instant data object that also behaves like a dictionary" (I <em>don't</em> think of C structs!), I think of this cute hack:</p> <pre><code>class Map(dict): def __init__(self, **kwargs): super(Map, self).__init__(**kwargs) self.__dict__ = self </code></pre> <p>Now you can just say:</p> <pre><code>struct = Map(field1='foo', field2='bar', field3=42) self.assertEquals('bar', struct.field2) self.assertEquals(42, struct['field3']) </code></pre> <p>Perfectly handy for those times when you need a "data bag that's NOT a class", and for when namedtuples are incomprehensible...</p>
6
2013-09-13T17:40:45Z
[ "python", "struct" ]
C-like structures in Python
35,988
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
210
2008-08-30T14:33:25Z
26,826,089
<p>You access access C-Style struct in python in following way.</p> <pre><code>class cstruct: var_i = 0 var_f = 0.0 var_str = "" </code></pre> <h1>if you just want use object of cstruct</h1> <pre><code>obj = cstruct() obj.var_i = 50 obj.var_f = 50.00 obj.var_str = "fifty" print "cstruct: obj i=%d f=%f s=%s" %(obj.var_i, obj.var_f, obj.var_str) </code></pre> <h1>if you want to create an array of objects of cstruct</h1> <pre><code>obj_array = [cstruct() for i in range(10)] obj_array[0].var_i = 10 obj_array[0].var_f = 10.00 obj_array[0].var_str = "ten" #go ahead and fill rest of array instaces of struct #print all the value for i in range(10): print "cstruct: obj_array i=%d f=%f s=%s" %(obj_array[i].var_i, obj_array[i].var_f, obj_array[i].var_str) </code></pre> <p>Note: instead of 'cstruct' name, please use your struct name instead of var_i, var_f, var_str, please define your structure's member variable. </p>
4
2014-11-09T07:37:47Z
[ "python", "struct" ]
C-like structures in Python
35,988
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
210
2008-08-30T14:33:25Z
29,212,925
<p>This might be a bit late but I made a solution using Python Meta-Classes (decorator version below too).</p> <p>When <code>__init__</code> is called during run time, it grabs each of the arguments and their value and assigns them as instance variables to your class. This way you can make a struct-like class without having to assign every value manually.</p> <p>My example has no error checking so it is easier to follow.</p> <pre><code>class MyStruct(type): def __call__(cls, *args, **kwargs): names = cls.__init__.func_code.co_varnames[1:] self = type.__call__(cls, *args, **kwargs) for name, value in zip(names, args): setattr(self , name, value) for name, value in kwargs.iteritems(): setattr(self , name, value) return self </code></pre> <p>Here it is in action.</p> <pre><code>&gt;&gt;&gt; class MyClass(object): __metaclass__ = MyStruct def __init__(self, a, b, c): pass &gt;&gt;&gt; my_instance = MyClass(1, 2, 3) &gt;&gt;&gt; my_instance.a 1 &gt;&gt;&gt; </code></pre> <p>I <a href="http://www.reddit.com/r/Python/comments/300psq/i_made_a_cstyle_struct_using_a_metaclass_to_save/" rel="nofollow">posted it on reddit</a> and <a href="http://www.reddit.com/user/matchu" rel="nofollow">/u/matchu</a> posted a decorator version which is cleaner. I'd encourage you to use it unless you want to expand the metaclass version.</p> <pre><code>&gt;&gt;&gt; def init_all_args(fn): @wraps(fn) def wrapped_init(self, *args, **kwargs): names = fn.func_code.co_varnames[1:] for name, value in zip(names, args): setattr(self, name, value) for name, value in kwargs.iteritems(): setattr(self, name, value) return wrapped_init &gt;&gt;&gt; class Test(object): @init_all_args def __init__(self, a, b): pass &gt;&gt;&gt; a = Test(1, 2) &gt;&gt;&gt; a.a 1 &gt;&gt;&gt; </code></pre>
3
2015-03-23T14:32:31Z
[ "python", "struct" ]
C-like structures in Python
35,988
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
210
2008-08-30T14:33:25Z
31,062,667
<p>You can subclass the C structure that is available in the standard library. The <a href="https://docs.python.org/2/library/ctypes.html">ctypes</a> module provides a <a href="https://docs.python.org/2/library/ctypes.html#structures-and-unions">Structure class</a>. The example from the docs:</p> <pre><code>&gt;&gt;&gt; from ctypes import * &gt;&gt;&gt; class POINT(Structure): ... _fields_ = [("x", c_int), ... ("y", c_int)] ... &gt;&gt;&gt; point = POINT(10, 20) &gt;&gt;&gt; print point.x, point.y 10 20 &gt;&gt;&gt; point = POINT(y=5) &gt;&gt;&gt; print point.x, point.y 0 5 &gt;&gt;&gt; POINT(1, 2, 3) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? ValueError: too many initializers &gt;&gt;&gt; &gt;&gt;&gt; class RECT(Structure): ... _fields_ = [("upperleft", POINT), ... ("lowerright", POINT)] ... &gt;&gt;&gt; rc = RECT(point) &gt;&gt;&gt; print rc.upperleft.x, rc.upperleft.y 0 5 &gt;&gt;&gt; print rc.lowerright.x, rc.lowerright.y 0 0 &gt;&gt;&gt; </code></pre>
5
2015-06-25T23:50:17Z
[ "python", "struct" ]
C-like structures in Python
35,988
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
210
2008-08-30T14:33:25Z
32,448,434
<p>I wrote a decorator which you can use on any method to make it so that all of the arguments passed in, or any defaults, are assigned to the instance.</p> <pre><code>def argumentsToAttributes(method): argumentNames = method.func_code.co_varnames[1:] # Generate a dictionary of default values: defaultsDict = {} defaults = method.func_defaults if method.func_defaults else () for i, default in enumerate(defaults, start = len(argumentNames) - len(defaults)): defaultsDict[argumentNames[i]] = default def newMethod(self, *args, **kwargs): # Use the positional arguments. for name, value in zip(argumentNames, args): setattr(self, name, value) # Add the key word arguments. If anything is missing, use the default. for name in argumentNames[len(args):]: setattr(self, name, kwargs.get(name, defaultsDict[name])) # Run whatever else the method needs to do. method(self, *args, **kwargs) return newMethod </code></pre> <p>A quick demonstration. Note that I use a positional argument <code>a</code>, use the default value for <code>b</code>, and a named argument <code>c</code>. I then print all 3 referencing <code>self</code>, to show that they've been properly assigned before the method is entered.</p> <pre><code>class A(object): @argumentsToAttributes def __init__(self, a, b = 'Invisible', c = 'Hello'): print(self.a) print(self.b) print(self.c) A('Why', c = 'Nothing') </code></pre> <p>Note that my decorator should work with any method, not just <code>__init__</code>.</p>
4
2015-09-08T02:38:18Z
[ "python", "struct" ]
How do I sort a list of strings in Python?
36,139
<p>What is the best way of creating an alphabetically sorted list in Python?</p>
211
2008-08-30T17:03:09Z
36,143
<pre><code>list.sort() </code></pre> <p>It really is that simple :)</p>
23
2008-08-30T17:04:40Z
[ "python", "string", "sorting" ]
How do I sort a list of strings in Python?
36,139
<p>What is the best way of creating an alphabetically sorted list in Python?</p>
211
2008-08-30T17:03:09Z
36,156
<p>Basic answer:</p> <pre><code>mylist = ["b", "C", "A"] mylist.sort() </code></pre> <p>This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the <a href="http://docs.python.org/library/functions.html#sorted"><code>sorted()</code></a> function:</p> <pre><code>for x in sorted(mylist): print x </code></pre> <p>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 <code>key</code> to specify custom sorting order (the alternative, using <code>cmp</code>, is a deprecated solution, as it has to be evaluated multiple times - <code>key</code> is only computed once per element).</p> <p>So, to sort according to the current locale, taking language-specific rules into account (<a href="http://docs.python.org/library/functools.html#functools.cmp_to_key"><code>cmp_to_key</code></a> is a helper function from functools):</p> <pre><code>sorted(mylist, key=cmp_to_key(locale.strcoll)) </code></pre> <p>And finally, if you need, you can specify a <a href="http://docs.python.org/library/locale.html">custom locale</a> for sorting:</p> <pre><code>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'] </code></pre> <p>Last note: you will see examples of case-insensitive sorting which use the <code>lower()</code> method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:</p> <pre><code># this is incorrect! mylist.sort(key=lambda x: x.lower()) # alternative notation, a bit faster, but still wrong mylist.sort(key=str.lower) </code></pre>
270
2008-08-30T17:10:12Z
[ "python", "string", "sorting" ]
How do I sort a list of strings in Python?
36,139
<p>What is the best way of creating an alphabetically sorted list in Python?</p>
211
2008-08-30T17:03:09Z
36,220
<blockquote> <p>But how does this handle language specific sorting rules? Does it take locale into account?</p> </blockquote> <p>No, <code>list.sort()</code> is a generic sorting function. If you want to sort according to the Unicode rules, you'll have to define a custom sort key function. You can try using the <a href="http://jtauber.com/blog/2006/01/27/python_unicode_collation_algorithm/">pyuca</a> module, but I don't know how complete it is.</p>
6
2008-08-30T18:10:45Z
[ "python", "string", "sorting" ]
How do I sort a list of strings in Python?
36,139
<p>What is the best way of creating an alphabetically sorted list in Python?</p>
211
2008-08-30T17:03:09Z
36,395
<p>It is also worth noting the <code>sorted()</code> function:</p> <pre><code>for x in sorted(list): print x </code></pre> <p>This returns a new, sorted version of a list without changing the original list.</p>
29
2008-08-30T22:14:36Z
[ "python", "string", "sorting" ]
How do I sort a list of strings in Python?
36,139
<p>What is the best way of creating an alphabetically sorted list in Python?</p>
211
2008-08-30T17:03:09Z
1,640,634
<p>The proper way to sort strings is:</p> <pre><code>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'] </code></pre> <p>The previous example of <code>mylist.sort(key=lambda x: x.lower())</code> will work fine for ASCII-only contexts.</p>
13
2009-10-28T22:45:59Z
[ "python", "string", "sorting" ]
"The system cannot find the file specified" when invoking subprocess.Popen in python
36,324
<p>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.</p> <p>I found <a href="http://www.nabble.com/problem-under-some-windows-desktop-td15868057.html" rel="nofollow">this link</a>, which describes my problem. Trying what was outlined there, I confirmed Python could find svn (it's in my path):</p> <pre> 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' </pre> <p>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:</p> <pre> 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 >>> </pre> <p>For now, I've commented out the 2.4-and-higher specific code, but I'd like to find a proper solution.</p> <p>If it's not obvious, I'm a complete python newbie, but google hasn't helped. Any pointers?</p>
4
2008-08-30T20:24:38Z
36,327
<p>It's a bug, see the <a href="http://docs.python.org/lib/node528.html" rel="nofollow">documentation of <code>subprocess.Popen</code></a>. There either needs to be a <code>"shell=True</code>" option, or the first argument needs to be a sequence <code>['svn', '--version']</code>. As it is now, <code>Popen</code> is looking for an executable named, literally, "svn --version" which it doesn't find.</p> <p>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.</p>
12
2008-08-30T20:34:35Z
[ "python", "svn-merge" ]
Setup django with WSGI and apache
36,806
<p>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.</p> <p>I am on osx 10.5 with apache 2.2 and django 1.0b2, mod_wsgi-2.3</p> <p>My application is called tred.</p> <p>Here are the relevant files: httpd-vhosts (included in httpd-conf)</p> <pre> 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 </pre> <p>mod_wsgi-handle.wsgi</p> <pre> 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() </pre> <p>When I go to <a href="http://tred">http://tred</a> 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?</p>
5
2008-08-31T12:03:20Z
37,009
<p>What happens if you remove the <code>Alias /</code> directive?</p>
5
2008-08-31T18:20:51Z
[ "python", "django", "apache", "mod-wsgi" ]
Setup django with WSGI and apache
36,806
<p>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.</p> <p>I am on osx 10.5 with apache 2.2 and django 1.0b2, mod_wsgi-2.3</p> <p>My application is called tred.</p> <p>Here are the relevant files: httpd-vhosts (included in httpd-conf)</p> <pre> 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 </pre> <p>mod_wsgi-handle.wsgi</p> <pre> 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() </pre> <p>When I go to <a href="http://tred">http://tred</a> 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?</p>
5
2008-08-31T12:03:20Z
37,218
<blockquote> <p>It works. I have no idea why, but it does.</p> </blockquote> <p>For future reference:</p> <p>It works because Apache processes alias directives in order, and uses the first match. It was always hitting <code>Alias /</code>, which will match anything, before <code>WSGIScriptAlias</code>.</p> <p>From the <a href="http://httpd.apache.org/docs/2.2/mod/mod_alias.html" rel="nofollow"><code>mod_alias</code> documentation</a>:</p> <blockquote> <p>First, all Redirects are processed before Aliases are processed, and therefore a request that matches a <code>Redirect</code> or <code>RedirectMatch</code> will never have Aliases applied. Second, the Aliases and Redirects are processed in the order they appear in the configuration files, with the first match taking precedence.</p> </blockquote>
5
2008-08-31T22:51:15Z
[ "python", "django", "apache", "mod-wsgi" ]
Setup django with WSGI and apache
36,806
<p>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.</p> <p>I am on osx 10.5 with apache 2.2 and django 1.0b2, mod_wsgi-2.3</p> <p>My application is called tred.</p> <p>Here are the relevant files: httpd-vhosts (included in httpd-conf)</p> <pre> 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 </pre> <p>mod_wsgi-handle.wsgi</p> <pre> 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() </pre> <p>When I go to <a href="http://tred">http://tred</a> 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?</p>
5
2008-08-31T12:03:20Z
1,038,110
<p>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.</p>
7
2009-06-24T12:39:13Z
[ "python", "django", "apache", "mod-wsgi" ]
Setup django with WSGI and apache
36,806
<p>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.</p> <p>I am on osx 10.5 with apache 2.2 and django 1.0b2, mod_wsgi-2.3</p> <p>My application is called tred.</p> <p>Here are the relevant files: httpd-vhosts (included in httpd-conf)</p> <pre> 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 </pre> <p>mod_wsgi-handle.wsgi</p> <pre> 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() </pre> <p>When I go to <a href="http://tred">http://tred</a> 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?</p>
5
2008-08-31T12:03:20Z
17,796,582
<p>try following this tutorial - <a href="http://singlas.in/5-step-tutorial-for-using-django-with-apache-and-mod_wsgi/" rel="nofollow">http://singlas.in/5-step-tutorial-for-using-django-with-apache-and-mod_wsgi/</a></p> <p>you are trying to host apache /var/www/ folder and the Django app both at root (/). Since Alias directive takes precedence over WSGIScriptAlias, it is rendering apache directory.</p> <p>you can try to host the django app at /app. Alternatively host the /var/www/ folder at a different location like /public</p>
1
2013-07-22T20:14:55Z
[ "python", "django", "apache", "mod-wsgi" ]
How do I add data to an existing model in Django?
36,812
<p>Currently, I am writing up a bit of a product-based CMS as my first project.</p> <p>Here is my question. How can I add additional data (products) to my Product model?</p> <p>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</p> <p>How can I do this all without using this existing django admin interface.</p>
2
2008-08-31T12:11:10Z
36,818
<p>Follow the Django tutorial for setting up the "admin" part of an application. This will allow you to modify your database.</p> <p><a href="https://docs.djangoproject.com/en/dev/intro/tutorial02/" rel="nofollow">Django Admin Setup</a></p> <p>Alternatively, you can just connect directly to the database using the standard tools for whatever database type you are using.</p>
-1
2008-08-31T12:19:14Z
[ "python", "django" ]
How do I add data to an existing model in Django?
36,812
<p>Currently, I am writing up a bit of a product-based CMS as my first project.</p> <p>Here is my question. How can I add additional data (products) to my Product model?</p> <p>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</p> <p>How can I do this all without using this existing django admin interface.</p>
2
2008-08-31T12:11:10Z
36,827
<p>This topic is covered in <a href="https://code.djangoproject.com/wiki/Tutorials" rel="nofollow">Django tutorials</a>.</p>
0
2008-08-31T12:31:49Z
[ "python", "django" ]
How do I add data to an existing model in Django?
36,812
<p>Currently, I am writing up a bit of a product-based CMS as my first project.</p> <p>Here is my question. How can I add additional data (products) to my Product model?</p> <p>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</p> <p>How can I do this all without using this existing django admin interface.</p>
2
2008-08-31T12:11:10Z
36,935
<p>You will want to wire your URL to the Django <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object" rel="nofollow">create_object generic view</a>, and pass it either "model" (the model you want to create) or "form_class" (a customized <a href="https://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#topics-forms-modelforms" rel="nofollow">ModelForm</a> class). There are a number of <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object" rel="nofollow">other arguments</a> you can also pass to override default behaviors.</p> <p>Sample URLconf for the simplest case:</p> <pre><code>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})) </code></pre> <p>Your template will get the context variable "form", which you just need to wrap in a &lt;form> tag and add a submit button. The simplest working template (by default should go in "my_products_app/product_form.html"):</p> <pre><code>&lt;form action="." method="POST"&gt; {{ form }} &lt;input type="submit" name="submit" value="add"&gt; &lt;/form&gt; </code></pre> <p>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.</p>
7
2008-08-31T15:59:11Z
[ "python", "django" ]
What does ** (double star) and * (star) do for Python parameters?
36,901
<p>In the following method definitions, what does the <code>*</code> and <code>**</code> do for <code>param2</code>?</p> <pre><code>def foo(param1, *param2): def bar(param1, **param2): </code></pre>
833
2008-08-31T15:04:35Z
36,902
<p>From the Python documentation:</p> <blockquote> <p>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). </p> <p>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. </p> </blockquote>
9
2008-08-31T15:07:48Z
[ "python", "syntax", "parameter-passing", "identifier", "kwargs" ]
What does ** (double star) and * (star) do for Python parameters?
36,901
<p>In the following method definitions, what does the <code>*</code> and <code>**</code> do for <code>param2</code>?</p> <pre><code>def foo(param1, *param2): def bar(param1, **param2): </code></pre>
833
2008-08-31T15:04:35Z
36,908
<p>The <code>*args</code> and <code>**kwargs</code> is a common idiom to allow arbitrary number of arguments to functions as described in the section <a href="http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions">more on defining functions</a> in the Python documentation.</p> <p>The <code>*args</code> will give you all function parameters <a href="https://docs.python.org/dev/tutorial/controlflow.html#arbitrary-argument-lists">as a tuple</a>:</p> <pre><code>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 </code></pre> <p>The <code>**kwargs</code> will give you all <strong>keyword arguments</strong> except for those corresponding to a formal parameter as a dictionary.</p> <pre><code>In [5]: def bar(**kwargs): ...: for a in kwargs: ...: print a, kwargs[a] ...: ...: In [6]: bar(name='one', age=27) age 27 name one </code></pre> <p>Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:</p> <pre><code>def foo(kind, *args, **kwargs): pass </code></pre> <p>Another usage of the <code>*l</code> idiom is to <strong>unpack argument lists</strong> when calling a function.</p> <pre><code>In [9]: def foo(bar, lee): ...: print bar, lee ...: ...: In [10]: l = [1,2] In [11]: foo(*l) 1 2 </code></pre> <p>In Python 3 it is possible to use <code>*l</code> on the left side of an assignment (<a href="http://www.python.org/dev/peps/pep-3132/">Extended Iterable Unpacking</a>):</p> <pre><code>first, *rest = [1,2,3,4] first, *l, last = [1,2,3,4] </code></pre> <p>Also Python 3 adds new semantic (refer <a href="https://www.python.org/dev/peps/pep-3102/">PEP 3102</a>):</p> <pre><code>def func(arg1, arg2, arg3='default', *, kwarg1='abc', kwarg2='xyz'): pass </code></pre> <p>Such function accepts only 2 positional arguments, and everything after <code>*</code> can only be passed as keyword argument, not positional one.</p> <p>In Python 2 similar was true for all parameters after <code>*args</code>.</p>
877
2008-08-31T15:17:31Z
[ "python", "syntax", "parameter-passing", "identifier", "kwargs" ]
What does ** (double star) and * (star) do for Python parameters?
36,901
<p>In the following method definitions, what does the <code>*</code> and <code>**</code> do for <code>param2</code>?</p> <pre><code>def foo(param1, *param2): def bar(param1, **param2): </code></pre>
833
2008-08-31T15:04:35Z
36,911
<p>The single * means that there can be any number of extra positional arguments. <code>foo()</code> can be invoked like <code>foo(1,2,3,4,5)</code>. In the body of foo() param2 is a sequence containing 2-5.</p> <p>The double ** means there can be any number of extra named parameters. <code>bar()</code> can be invoked like <code>bar(1, a=2, b=3)</code>. In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }</p> <p>With the following code:</p> <pre><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) </code></pre> <p>the output is</p> <pre><code>1 (2, 3, 4, 5) 1 {'a': 2, 'b': 3} </code></pre>
89
2008-08-31T15:20:21Z
[ "python", "syntax", "parameter-passing", "identifier", "kwargs" ]
What does ** (double star) and * (star) do for Python parameters?
36,901
<p>In the following method definitions, what does the <code>*</code> and <code>**</code> do for <code>param2</code>?</p> <pre><code>def foo(param1, *param2): def bar(param1, **param2): </code></pre>
833
2008-08-31T15:04:35Z
36,926
<p>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:</p> <pre><code>def foo(x,y,z): print "x=" + str(x) print "y=" + str(y) print "z=" + str(z) </code></pre> <p>You can do things like:</p> <pre><code>&gt;&gt;&gt; mylist = [1,2,3] &gt;&gt;&gt; foo(*mylist) x=1 y=2 z=3 &gt;&gt;&gt; mydict = {'x':1,'y':2,'z':3} &gt;&gt;&gt; foo(**mydict) x=1 y=2 z=3 &gt;&gt;&gt; mytuple = (1, 2, 3) &gt;&gt;&gt; foo(*mytuple) x=1 y=2 z=3 </code></pre>
244
2008-08-31T15:47:25Z
[ "python", "syntax", "parameter-passing", "identifier", "kwargs" ]
What does ** (double star) and * (star) do for Python parameters?
36,901
<p>In the following method definitions, what does the <code>*</code> and <code>**</code> do for <code>param2</code>?</p> <pre><code>def foo(param1, *param2): def bar(param1, **param2): </code></pre>
833
2008-08-31T15:04:35Z
12,362,812
<p><code>*</code> and <code>**</code> have special usage in the function argument list. <code>*</code> implies that the argument is a list and <code>**</code> implies that the argument is a dictionary. This allows functions to take arbitrary number of arguments</p>
15
2012-09-11T04:33:44Z
[ "python", "syntax", "parameter-passing", "identifier", "kwargs" ]
What does ** (double star) and * (star) do for Python parameters?
36,901
<p>In the following method definitions, what does the <code>*</code> and <code>**</code> do for <code>param2</code>?</p> <pre><code>def foo(param1, *param2): def bar(param1, **param2): </code></pre>
833
2008-08-31T15:04:35Z
26,365,795
<p><strong><code>*args</code> and <code>**kwargs</code> notation</strong></p> <p><code>*args</code> (typically said "star-args") and <code>**kwargs</code> (stars can be implied by saying "kwargs", but be explicit with "double-star kwargs") are common idioms of Python for using the <code>*</code> and <code>**</code> notation. These specific variable names aren't required (e.g. you could use <code>*foos</code> and <code>**bars</code>), but a departure from convention is likely to enrage your fellow Python coders. </p> <p>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).</p> <p><strong>Example 1</strong></p> <p>The following function describes how they can be used, and demonstrates behavior. Note the named <code>b</code> argument will be consumed by the second positional argument before :</p> <pre><code>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)) </code></pre> <p>We can check the online help for the function's signature, with <code>help(foo)</code>, which tells us </p> <pre><code>foo(a, b=10, *args, **kwargs) </code></pre> <p>Let's call this function with <code>foo(1, 2, 3, 4, e=5, f=6, g=7)</code> </p> <p>which prints:</p> <pre><code>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 &lt;type 'tuple'&gt; and length 2 unknown arg: 3 unknown arg: 4 kwargs is of type &lt;type 'dict'&gt; 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} </code></pre> <p><strong>Example 2</strong></p> <p>We can also call it using another function, into which we just provide <code>a</code>:</p> <pre><code>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()) </code></pre> <p><code>bar(100)</code> prints:</p> <pre><code>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 &lt;type 'tuple'&gt; and length 0 kwargs is of type &lt;type 'dict'&gt; 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} </code></pre> <p><strong>Example 3: practical usage in decorators</strong></p> <p>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.</p> <pre><code>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 </code></pre> <p>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 <code>*args</code> and <code>**kwargs</code> can be very useful:</p> <pre><code>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 </code></pre> <p>And now every wrapped function can be written much more succinctly, as we've factored out the redundancy:</p> <pre><code>@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) </code></pre> <p>And by factoring out our code, which <code>*args</code> and <code>**kwargs</code> 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.</p>
47
2014-10-14T16:34:01Z
[ "python", "syntax", "parameter-passing", "identifier", "kwargs" ]
What does ** (double star) and * (star) do for Python parameters?
36,901
<p>In the following method definitions, what does the <code>*</code> and <code>**</code> do for <code>param2</code>?</p> <pre><code>def foo(param1, *param2): def bar(param1, **param2): </code></pre>
833
2008-08-31T15:04:35Z
32,031,804
<p>In addition to function calls, *args and **kwargs are useful in class hierarchies and also avoid having to write <strong>init</strong> method in Python. Similar usage is seen in frameworks like Django code.</p> <p>For example,</p> <pre><code>def __init__(self, *args, **kwargs): for attribute_name, value in zip(self._expected_attributes, args): setattr(self, attribute_name, value) if kwargs.has_key(attribute_name): kwargs.pop(attribute_name) for attribute_name in kwargs.viewkeys(): setattr(self, attribute_name, kwargs[attribute_name]) </code></pre> <p>A subclass can then be</p> <pre><code>class RetailItem(Item): _expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin'] class FoodItem(RetailItem): _expected_attributes = RetailItem._expected_attributes + ['expiry_date'] </code></pre> <p>The subclass then be called as </p> <pre><code>food_item = FoodItem(name = 'Jam', price = 12.0, category = 'Foods', country_of_origin = 'US', expiry_date = datetime.datetime.now()) </code></pre> <p>Also, a subclass with a new attribute which makes sense only to that subclass instance can call the Base class <strong>init</strong> to offload the attributes setting. This is done through *args and **kwargs. kwargs mainly used so that code is readable using named arguments. For example,</p> <pre><code>class ElectronicAccessories(RetailItem): _expected_attributes = RetailItem._expected_attributes + ['specifications'] """ Depend on args and kwargs to populate the data as needed. """ def __init__(self, specifications = None, *args, **kwargs): self.specifications = specifications # Rest of attributes will make sense to parent class. super(ElectronicAccessories, self).__init__(*args, **kwargs) </code></pre> <p>which can be instatiated as</p> <pre><code>usb_key = ElectronicAccessories(name = 'Sandisk', price = '$6.00', category = 'Electronics', country_of_origin = 'CN', specifications = '4GB USB 2.0/USB 3.0') </code></pre> <p>The complete code is <a href="http://harisankar-krishnaswamy.blogspot.sg/2015/08/using-args-and-kwargs-python-code-post.html" rel="nofollow">here</a></p>
2
2015-08-16T04:23:57Z
[ "python", "syntax", "parameter-passing", "identifier", "kwargs" ]
What does ** (double star) and * (star) do for Python parameters?
36,901
<p>In the following method definitions, what does the <code>*</code> and <code>**</code> do for <code>param2</code>?</p> <pre><code>def foo(param1, *param2): def bar(param1, **param2): </code></pre>
833
2008-08-31T15:04:35Z
34,166,505
<p>In Python 3.5, you can also use this syntax in <code>list</code>, <code>dict</code>, <code>tuple</code>, and <code>set</code> displays (also sometimes called literals). See <a href="http://legacy.python.org/dev/peps/pep-0448/" rel="nofollow">PEP 488: Additional Unpacking Generalizations</a>.</p> <pre><code>&gt;&gt;&gt; (0, *range(1, 4), 5, *range(6, 8)) (0, 1, 2, 3, 5, 6, 7) &gt;&gt;&gt; [0, *range(1, 4), 5, *range(6, 8)] [0, 1, 2, 3, 5, 6, 7] &gt;&gt;&gt; {0, *range(1, 4), 5, *range(6, 8)} {0, 1, 2, 3, 5, 6, 7} &gt;&gt;&gt; d = {'one': 1, 'two': 2, 'three': 3} &gt;&gt;&gt; e = {'six': 6, 'seven': 7} &gt;&gt;&gt; {'zero': 0, **d, 'five': 5, **e} {'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0} </code></pre> <p>It also allows multiple iterables to be unpacked in a single function call.</p> <pre><code>&gt;&gt;&gt; range(*[1, 10], *[2]) range(1, 10, 2) </code></pre> <p>(Thanks to mgilson for the PEP link.)</p>
3
2015-12-08T21:38:13Z
[ "python", "syntax", "parameter-passing", "identifier", "kwargs" ]
What does ** (double star) and * (star) do for Python parameters?
36,901
<p>In the following method definitions, what does the <code>*</code> and <code>**</code> do for <code>param2</code>?</p> <pre><code>def foo(param1, *param2): def bar(param1, **param2): </code></pre>
833
2008-08-31T15:04:35Z
34,899,056
<p>Let us first understand what are positional arguments and keyword arguments. Below is an example of function definition with <strong>Positional arguments.</strong></p> <pre><code>def test(a,b,c): print(a) print(b) print(c) test(1,2,3) #output: 1 2 3 </code></pre> <p>So this is a function definition with positional arguments. You can call it with keyword/named arguments as well:</p> <pre><code>def test(a,b,c): print(a) print(b) print(c) test(a=1,b=2,c=3) #output: 1 2 3 </code></pre> <p>Now let us study an example of function definition with <strong>keyword arguments</strong>:</p> <pre><code>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 ------------------------- </code></pre> <p>You can call this function with positional arguments as well:</p> <pre><code>def test(a=0,b=0,c=0): print(a) print(b) print(c) print('-------------------------') test(1,2,3) # output : 1 2 3 --------------------------------- </code></pre> <p>So we now know function definitions with positional as well as keyword arguments.</p> <p>Now let us study the '*' operator and '**' operator.</p> <p>Please note these operators can be used in 2 areas:</p> <p>a) <strong>function call</strong></p> <p>b) <strong>function definition</strong></p> <p>The use of '*' operator and '**' operator in <strong>function call.</strong> </p> <p>Let us get straight to an example and then discuss it.</p> <pre><code>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. </code></pre> <p>So remember </p> <p>when the '*' or '**' operator is used in a <strong>function call</strong> -</p> <p>'*' operator unpacks data structure such as a list or tuple into arguments needed by function definition.</p> <p>'**' operator unpacks a dictionary into arguments needed by function definition.</p> <p>Now let us study the '*' operator use in <strong>function definition</strong>. Example:</p> <pre><code>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 </code></pre> <p>In function <strong>definition</strong> the '*' operator packs the received arguments into a tuple.</p> <p>Now let us see an example of '**' used in function definition:</p> <pre><code>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 </code></pre> <p>In function <strong>definition</strong> The '**' operator packs the received arguments into a dictionary.</p> <p>So remember:</p> <p>In a <strong>function call</strong> the '*' <strong>unpacks</strong> data structure of tuple or list into positional or keyword arguments to be received by function definition.</p> <p>In a <strong>function call</strong> the '**' <strong>unpacks</strong> data structure of dictionary into positional or keyword arguments to be received by function definition.</p> <p>In a <strong>function definition</strong> the '*' <strong>packs</strong> positional arguments into a tuple.</p> <p>In a <strong>function definition</strong> the '**' <strong>packs</strong> keyword arguments into a dictionary.</p>
12
2016-01-20T11:40:54Z
[ "python", "syntax", "parameter-passing", "identifier", "kwargs" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
36,937
<p>Before PEP 435, Python didn't have an equivalent but you could implement your own.</p> <p>Myself, I like keeping it simple (I've seen some horribly complex examples on the net), something like this ...</p> <pre><code>class Animal: DOG = 1 CAT = 2 x = Animal.DOG </code></pre> <hr> <p>In Python 3.4 (<a href="http://www.python.org/dev/peps/pep-0435/">PEP 435</a>), 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.</p> <pre><code>class Animal(Enum): DOG = 1 CAT = 2 print(Animal.DOG) &lt;Animal.DOG: 1&gt; </code></pre> <hr> <p>If you don't want to type the values, use the following shortcut:</p> <pre><code>class Animal(Enum): DOG, CAT = range(2) </code></pre>
610
2008-08-31T16:06:14Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
36,940
<p>Hmmm... I suppose the closest thing to an enum would be a dictionary, defined either like this:</p> <pre><code>months = { 'January': 1, 'February': 2, ... } </code></pre> <p>or</p> <pre><code>months = dict( January=1, February=2, ... ) </code></pre> <p>Then, you can use the symbolic name for the constants like this:</p> <pre><code>mymonth = months['January'] </code></pre> <p>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.</p> <p>Edit: I like Alexandru's answer too!</p>
17
2008-08-31T16:09:53Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
37,000
<p>Python doesn't have a built-in equivalent to <code>enum</code>, and other answers have ideas for implementing your own (you may also be interested in the <a href="http://code.activestate.com/recipes/67107/">over the top version</a> in the Python cookbook).</p> <p>However, in situations where an <code>enum</code> would be called for in C, I usually end up <strong><em>just using simple strings</em></strong>: 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.</p> <pre><code>ANIMALS = ['cat', 'dog', 'python'] def take_for_a_walk(animal): assert animal in ANIMALS ... </code></pre> <p>(One disadvantage compared to using a class is that you lose the benefit of autocomplete)</p>
42
2008-08-31T18:10:50Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
37,081
<p>If you need the numeric values, here's the quickest way:</p> <pre><code>dog, cat, rabbit = range(3) </code></pre>
140
2008-08-31T20:31:22Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
38,092
<p>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:</p> <pre><code>class Animal: def __init__(self, name): self.name = name def __str__(self): return self.name def __repr__(self): return "&lt;Animal: %s&gt;" % self Animal.DOG = Animal("dog") Animal.CAT = Animal("cat") &gt;&gt;&gt; x = Animal.DOG &gt;&gt;&gt; x &lt;Animal: dog&gt; &gt;&gt;&gt; x == 1 False </code></pre> <hr> <p>A recent <a href="http://mail.python.org/pipermail/python-dev/2010-November/105873.html">thread on python-dev</a> pointed out there are a couple of enum libraries in the wild, including:</p> <ul> <li><a href="http://packages.python.org/flufl.enum/docs/using.html">flufl.enum</a></li> <li><a href="http://pypi.python.org/pypi/lazr.enum">lazr.enum</a></li> <li>... and the imaginatively named <a href="http://pypi.python.org/pypi/enum/">enum</a></li> </ul>
72
2008-09-01T16:05:25Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
38,762
<p>davidg recommends using dicts. I'd go one step further and use sets:</p> <pre><code>months = set('January', 'February', ..., 'December') </code></pre> <p>Now you can test whether a value matches one of the values in the set like this:</p> <pre><code>if m in months: </code></pre> <p>like dF, though, I usually just use string constants in place of enums.</p>
13
2008-09-02T03:20:30Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
99,347
<p>Alexandru's suggestion of using class constants for enums works quite well. </p> <p>I also like to add a dictionary for each set of constants to lookup a human-readable string representation. </p> <p>This serves two purposes: a) it provides a simple way to pretty-print your enum and b) the dictionary logically groups the constants so that you can test for membership.</p> <pre><code>class Animal: TYPE_DOG = 1 TYPE_CAT = 2 type2str = { TYPE_DOG: "dog", TYPE_CAT: "cat" } def __init__(self, type_): assert type_ in self.type2str.keys() self._type = type_ def __repr__(self): return "&lt;%s type=%s&gt;" % ( self.__class__.__name__, self.type2str[self._type].upper()) </code></pre>
5
2008-09-19T03:37:43Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
107,973
<pre><code>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() </code></pre> <p>Use it like this: </p> <pre><code>Animal = enum('DOG', 'CAT') Animal.DOG # returns 0 Animal.CAT # returns 1 Animal.DOG = 2 # raises NotImplementedError </code></pre> <p>if you just want unique symbols and don't care about the values, replace this line: </p> <pre><code>__metaclass__ = M_add_class_attribs(enumerate(names)) </code></pre> <p>with this:</p> <pre><code>__metaclass__ = M_add_class_attribs((object(), name) for name in names) </code></pre>
26
2008-09-20T11:49:38Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
220,537
<p>It's funny, I just had a need for this the other day and I couldnt find an implementation worth using... so I wrote my own:</p> <pre><code>import functools class EnumValue(object): def __init__(self,name,value,type): self.__value=value self.__name=name self.Type=type def __str__(self): return self.__name def __repr__(self):#2.6 only... so change to what ever you need... return '{cls}({0!r},{1!r},{2})'.format(self.__name,self.__value,self.Type.__name__,cls=type(self).__name__) def __hash__(self): return hash(self.__value) def __nonzero__(self): return bool(self.__value) def __cmp__(self,other): if isinstance(other,EnumValue): return cmp(self.__value,other.__value) else: return cmp(self.__value,other)#hopefully their the same type... but who cares? def __or__(self,other): if other is None: return self elif type(self) is not type(other): raise TypeError() return EnumValue('{0.Name} | {1.Name}'.format(self,other),self.Value|other.Value,self.Type) def __and__(self,other): if other is None: return self elif type(self) is not type(other): raise TypeError() return EnumValue('{0.Name} &amp; {1.Name}'.format(self,other),self.Value&amp;other.Value,self.Type) def __contains__(self,other): if self.Value==other.Value: return True return bool(self&amp;other) def __invert__(self): enumerables=self.Type.__enumerables__ return functools.reduce(EnumValue.__or__,(enum for enum in enumerables.itervalues() if enum not in self)) @property def Name(self): return self.__name @property def Value(self): return self.__value class EnumMeta(type): @staticmethod def __addToReverseLookup(rev,value,newKeys,nextIter,force=True): if value in rev: forced,items=rev.get(value,(force,()) ) if forced and force: #value was forced, so just append rev[value]=(True,items+newKeys) elif not forced:#move it to a new spot next=nextIter.next() EnumMeta.__addToReverseLookup(rev,next,items,nextIter,False) rev[value]=(force,newKeys) else: #not forcing this value next = nextIter.next() EnumMeta.__addToReverseLookup(rev,next,newKeys,nextIter,False) rev[value]=(force,newKeys) else:#set it and forget it rev[value]=(force,newKeys) return value def __init__(cls,name,bases,atts): classVars=vars(cls) enums = classVars.get('__enumerables__',None) nextIter = getattr(cls,'__nextitr__',itertools.count)() reverseLookup={} values={} if enums is not None: #build reverse lookup for item in enums: if isinstance(item,(tuple,list)): items=list(item) value=items.pop() EnumMeta.__addToReverseLookup(reverseLookup,value,tuple(map(str,items)),nextIter) else: value=nextIter.next() value=EnumMeta.__addToReverseLookup(reverseLookup,value,(str(item),),nextIter,False)#add it to the reverse lookup, but don't force it to that value #build values and clean up reverse lookup for value,fkeys in reverseLookup.iteritems(): f,keys=fkeys for key in keys: enum=EnumValue(key,value,cls) setattr(cls,key,enum) values[key]=enum reverseLookup[value]=tuple(val for val in values.itervalues() if val.Value == value) setattr(cls,'__reverseLookup__',reverseLookup) setattr(cls,'__enumerables__',values) setattr(cls,'_Max',max([key for key in reverseLookup] or [0])) return super(EnumMeta,cls).__init__(name,bases,atts) def __iter__(cls): for enum in cls.__enumerables__.itervalues(): yield enum def GetEnumByName(cls,name): return cls.__enumerables__.get(name,None) def GetEnumByValue(cls,value): return cls.__reverseLookup__.get(value,(None,))[0] class Enum(object): __metaclass__=EnumMeta __enumerables__=None class FlagEnum(Enum): @staticmethod def __nextitr__(): yield 0 for val in itertools.count(): yield 2**val def enum(name,*args): return EnumMeta(name,(Enum,),dict(__enumerables__=args)) </code></pre> <p>Take it or leave it, it did what I needed it to do :)</p> <p>Use it like:</p> <pre><code>class Air(FlagEnum): __enumerables__=('None','Oxygen','Nitrogen','Hydrogen') class Mammals(Enum): __enumerables__=('Bat','Whale',('Dog','Puppy',1),'Cat') Bool = enum('Bool','Yes',('No',0)) </code></pre>
2
2008-10-21T02:08:29Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
505,457
<p>What I use:</p> <pre><code>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)) </code></pre> <p>How to use:</p> <pre><code>&gt;&gt;&gt; state = Enum('draft published retracted') &gt;&gt;&gt; state.DRAFT 0 &gt;&gt;&gt; state.RETRACTED 2 &gt;&gt;&gt; state.FOO Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'Enum' object has no attribute 'FOO' &gt;&gt;&gt; state.tuples() ((0, 'draft'), (1, 'published'), (2, 'retracted')) </code></pre> <p>So this gives you integer constants like state.PUBLISHED and the two-tuples to use as choices in Django models.</p>
14
2009-02-02T23:39:53Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
1,529,241
<p>The best solution for you would depend on what you require from your <em>fake</em> <strong><code>enum</code></strong>.</p> <p><strong>Simple enum:</strong></p> <p>If you need the <strong><code>enum</code></strong> as only a list of <em>names</em> identifying different <em>items</em>, the solution by <strong>Mark Harrison</strong> (above) is great:</p> <pre><code>Pen, Pencil, Eraser = range(0, 3) </code></pre> <p>Using a <strong><code>range</code></strong> also allows you to set any <em>starting value</em>:</p> <pre><code>Pen, Pencil, Eraser = range(9, 12) </code></pre> <p>In addition to the above, if you also require that the items belong to a <em>container</em> of some sort, then embed them in a class:</p> <pre><code>class Stationery: Pen, Pencil, Eraser = range(0, 3) </code></pre> <p>To use the enum item, you would now need to use the container name and the item name:</p> <pre><code>stype = Stationery.Pen </code></pre> <p><strong>Complex enum:</strong></p> <p>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 <em>Simulating Enumerations in Python</em> published in the <em>Python Cookbook</em>. An online version of that is available <a href="http://code.activestate.com/recipes/67107/">here</a>.</p> <p><strong>More info:</strong></p> <p><a href="http://www.python.org/dev/peps/pep-0354/"><em>PEP 354: Enumerations in Python</em></a> has the interesting details of a proposal for enum in Python and why it was rejected.</p>
101
2009-10-07T02:47:33Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
1,587,932
<p>Use the following.</p> <pre><code>TYPE = {'EAN13': u'EAN-13', 'CODE39': u'Code 39', 'CODE128': u'Code 128', 'i25': u'Interleaved 2 of 5',} &gt;&gt;&gt; TYPE.items() [('EAN13', u'EAN-13'), ('i25', u'Interleaved 2 of 5'), ('CODE39', u'Code 39'), ('CODE128', u'Code 128')] &gt;&gt;&gt; TYPE.keys() ['EAN13', 'i25', 'CODE39', 'CODE128'] &gt;&gt;&gt; TYPE.values() [u'EAN-13', u'Interleaved 2 of 5', u'Code 39', u'Code 128'] </code></pre> <p>I used that for <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow">Django</a> model choices, and it looks very pythonic. It is not really an Enum, but it does the job.</p>
1
2009-10-19T10:21:39Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
1,695,250
<p>Enums have been added to Python 3.4 as described in <a href="http://www.python.org/dev/peps/pep-0435/" rel="nofollow">PEP 435</a>. It has also been <a href="https://pypi.python.org/pypi/enum34" rel="nofollow">backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4</a> on pypi. </p> <p>For more advanced Enum techniques try the <a href="https://pypi.python.org/pypi/aenum" rel="nofollow">aenum library</a> (2.7, 3.3+, same author as <code>enum34</code>. Code is not perfectly compatible between py2 and py3, e.g. you'll need <a href="http://stackoverflow.com/a/25982264/57461"><code>__order__</code> in python 2</a>).</p> <ul> <li>To use <code>enum34</code>, do <code>$ pip install enum34</code></li> <li>To use <code>aenum</code>, do <code>$ pip install aenum</code></li> </ul> <p>Installing <code>enum</code> (no numbers) will install a completely different and incompatible version.</p> <hr> <pre><code>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 &lt;Animal.ant: 1&gt; Animal['ant'] # returns &lt;Animal.ant: 1&gt; (string lookup) Animal.ant.name # returns 'ant' (inverse lookup) </code></pre> <p>or equivalently:</p> <pre><code>class Animal(Enum): ant = 1 bee = 2 cat = 3 dog = 4 </code></pre> <hr> <p>In earlier versions, one way of accomplishing enums is:</p> <pre><code>def enum(**enums): return type('Enum', (), enums) </code></pre> <p>which is used like so:</p> <pre><code>&gt;&gt;&gt; Numbers = enum(ONE=1, TWO=2, THREE='three') &gt;&gt;&gt; Numbers.ONE 1 &gt;&gt;&gt; Numbers.TWO 2 &gt;&gt;&gt; Numbers.THREE 'three' </code></pre> <p>You can also easily support automatic enumeration with something like this:</p> <pre><code>def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) </code></pre> <p>and used like so:</p> <pre><code>&gt;&gt;&gt; Numbers = enum('ZERO', 'ONE', 'TWO') &gt;&gt;&gt; Numbers.ZERO 0 &gt;&gt;&gt; Numbers.ONE 1 </code></pre> <p>Support for converting the values back to names can be added this way:</p> <pre><code>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) </code></pre> <p>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:</p> <pre><code>&gt;&gt;&gt; Numbers.reverse_mapping['three'] 'THREE' </code></pre>
1,857
2009-11-08T03:15:28Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
1,751,697
<p>I had need of some symbolic constants in pyparsing to represent left and right associativity of binary operators. I used class constants like this:</p> <pre><code># an internal class, not intended to be seen by client code class _Constants(object): pass # an enumeration of constants for operator associativity opAssoc = _Constants() opAssoc.LEFT = object() opAssoc.RIGHT = object() </code></pre> <p>Now when client code wants to use these constants, they can import the entire enum using:</p> <pre><code>import opAssoc from pyparsing </code></pre> <p>The enumerations are unique, they can be tested with 'is' instead of '==', they don't take up a big footprint in my code for a minor concept, and they are easily imported into the client code. They don't support any fancy str() behavior, but so far that is in the <a href="http://c2.com/xp/YouArentGonnaNeedIt.html" rel="nofollow">YAGNI</a> category.</p>
2
2009-11-17T20:54:34Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
1,753,340
<p>This is the best one I have seen: "First Class Enums in Python"</p> <p><a href="http://code.activestate.com/recipes/413486/">http://code.activestate.com/recipes/413486/</a></p> <p>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.</p> <p>Edit (cfi): The above link is not Python 3 compatible. Here's my port of enum.py to Python 3:</p> <pre><code>def cmp(a,b): if a &lt; b: return -1 if b &lt; a: return 1 return 0 def Enum(*names): ##assert names, "Empty enums are not supported" # &lt;- 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) &lt; 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 &lt; 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) </code></pre>
11
2009-11-18T02:51:40Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
2,182,437
<p>Here is one implementation:</p> <pre><code>class Enum(set): def __getattr__(self, name): if name in self: return name raise AttributeError </code></pre> <p>Here is its usage:</p> <pre><code>Animals = Enum(["DOG", "CAT", "HORSE"]) print(Animals.DOG) </code></pre>
270
2010-02-02T07:21:46Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
2,389,722
<p>Following the Java like enum implementation proposed by Aaron Maenpaa, I came out with the following. The idea was to make it generic and parseable.</p> <pre><code>class Enum: #''' #Java like implementation for enums. # #Usage: #class Tool(Enum): name = 'Tool' #Tool.DRILL = Tool.register('drill') #Tool.HAMMER = Tool.register('hammer') #Tool.WRENCH = Tool.register('wrench') #''' name = 'Enum' # Enum name _reg = dict([]) # Enum registered values @classmethod def register(cls, value): #''' #Registers a new value in this enum. # #@param value: New enum value. # #@return: New value wrapper instance. #''' inst = cls(value) cls._reg[value] = inst return inst @classmethod def parse(cls, value): #''' #Parses a value, returning the enum instance. # #@param value: Enum value. # #@return: Value corresp instance. #''' return cls._reg.get(value) def __init__(self, value): #''' #Constructor (only for internal use). #''' self.value = value def __str__(self): #''' #str() overload. #''' return self.value def __repr__(self): #''' #repr() overload. #''' return "&lt;" + self.name + ": " + self.value + "&gt;" </code></pre>
1
2010-03-05T20:24:21Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
2,458,660
<p>The enum package from <a href="http://en.wikipedia.org/wiki/Python_Package_Index" rel="nofollow">PyPI</a> provides a robust implementation of enums. An earlier answer mentioned PEP 354; this was rejected but the proposal was implemented <a href="http://pypi.python.org/pypi/enum" rel="nofollow">http://pypi.python.org/pypi/enum</a>.</p> <p>Usage is easy and elegant:</p> <pre><code>&gt;&gt;&gt; from enum import Enum &gt;&gt;&gt; Colors = Enum('red', 'blue', 'green') &gt;&gt;&gt; shirt_color = Colors.green &gt;&gt;&gt; shirt_color = Colors[2] &gt;&gt;&gt; shirt_color &gt; Colors.red True &gt;&gt;&gt; shirt_color.index 2 &gt;&gt;&gt; str(shirt_color) 'green' </code></pre>
5
2010-03-16T22:36:42Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
2,785,738
<p>Why must enumerations be ints? Unfortunately, I can't think of any good looking construct to produce this without changing the Python language, so I'll use strings:</p> <pre><code>class Enumerator(object): def __init__(self, name): self.name = name def __eq__(self, other): if self.name == other: return True return self is other def __ne__(self, other): if self.name != other: return False return self is other def __repr__(self): return 'Enumerator({0})'.format(self.name) def __str__(self): return self.name class Enum(object): def __init__(self, *enumerators): for e in enumerators: setattr(self, e, Enumerator(e)) def __getitem__(self, key): return getattr(self, key) </code></pre> <p>Then again maybe it's even better now that we can naturally test against strings, for the sake of configuration files or other remote input.</p> <p>Example:</p> <pre><code>class Cow(object): State = Enum( 'standing', 'walking', 'eating', 'mooing', 'sleeping', 'dead', 'dying' ) state = State.standing In [1]: from enum import Enum In [2]: c = Cow() In [3]: c2 = Cow() In [4]: c.state, c2.state Out[4]: (Enumerator(standing), Enumerator(standing)) In [5]: c.state == c2.state Out[5]: True In [6]: c.State.mooing Out[6]: Enumerator(mooing) In [7]: c.State['mooing'] Out[7]: Enumerator(mooing) In [8]: c.state = Cow.State.dead In [9]: c.state == c2.state Out[9]: False In [10]: c.state == Cow.State.dead Out[10]: True In [11]: c.state == 'dead' Out[11]: True In [12]: c.state == Cow.State['dead'] Out[11]: True </code></pre>
2
2010-05-07T02:05:03Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
2,913,233
<pre><code>def enum( *names ): ''' Makes enum. Usage: E = enum( 'YOUR', 'KEYS', 'HERE' ) print( E.HERE ) ''' class Enum(): pass for index, name in enumerate( names ): setattr( Enum, name, index ) return Enum </code></pre>
1
2010-05-26T13:14:14Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
2,976,036
<p>I like the <a href="http://en.wikipedia.org/wiki/Java_%28programming_language%29" rel="nofollow">Java</a> enum, that's how I do it in Python:</p> <pre><code>def enum(clsdef): class Enum(object): __slots__=tuple([var for var in clsdef.__dict__ if isinstance((getattr(clsdef, var)), tuple) and not var.startswith('__')]) def __new__(cls, *args, **kwargs): if not '_the_instance' in cls.__dict__: cls._the_instance = object.__new__(cls, *args, **kwargs) return cls._the_instance def __init__(self): clsdef.values=lambda cls, e=Enum: e.values() clsdef.valueOf=lambda cls, n, e=self: e.valueOf(n) for ordinal, key in enumerate(self.__class__.__slots__): args=getattr(clsdef, key) instance=clsdef(*args) instance._name=key instance._ordinal=ordinal setattr(self, key, instance) @classmethod def values(cls): if not hasattr(cls, '_values'): cls._values=[getattr(cls, name) for name in cls.__slots__] return cls._values def valueOf(self, name): return getattr(self, name) def __repr__(self): return ''.join(['&lt;class Enum (', clsdef.__name__, ') at ', str(hex(id(self))), '&gt;']) return Enum() </code></pre> <p>Sample use:</p> <pre><code>i=2 @enum class Test(object): A=("a",1) B=("b",) C=("c",2) D=tuple() E=("e",3) while True: try: F, G, H, I, J, K, L, M, N, O=[tuple() for _ in range(i)] break; except ValueError: i+=1 def __init__(self, name="default", aparam=0): self.name=name self.avalue=aparam </code></pre> <p>All class variables are defined as a tuple, just like the constructor. So far, you can't use named arguments.</p>
1
2010-06-04T16:33:27Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
4,092,436
<p>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?</p> <pre><code>class Animal(object): values = ['Horse','Dog','Cat'] class __metaclass__(type): def __getattr__(self, name): return self.values.index(name) </code></pre> <p>It keeps me from value-collision in defining my enums.</p> <pre><code>&gt;&gt;&gt; Animal.Cat 2 </code></pre> <p>There's another handy advantage: really fast reverse lookups:</p> <pre><code>def name_of(self, i): return self.values[i] </code></pre>
37
2010-11-03T23:02:54Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
4,300,343
<p>I prefer to define enums in Python like so:</p> <pre><code>class Animal: class Dog: pass class Cat: pass x = Animal.Dog </code></pre> <p>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).</p> <p>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).</p>
25
2010-11-29T02:05:55Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
6,347,576
<p>Here is a variant on <a href="http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python/1695250#1695250">Alec Thomas's solution</a>:</p> <pre><code>def enum(*args, **kwargs): return type('Enum', (), dict((y, x) for x, y in enumerate(args), **kwargs)) x = enum('POOH', 'TIGGER', 'EEYORE', 'ROO', 'PIGLET', 'RABBIT', 'OWL') assert x.POOH == 0 assert x.TIGGER == 1 </code></pre>
2
2011-06-14T17:29:49Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
6,971,002
<p>Another, very simple, implementation of an enum in Python, using <code>namedtuple</code>:</p> <pre><code>from collections import namedtuple def enum(*keys): return namedtuple('Enum', keys)(*keys) MyEnum = enum('FOO', 'BAR', 'BAZ') </code></pre> <p>or, alternatively,</p> <pre><code># 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()) </code></pre> <p>Like the method above that subclasses <code>set</code>, this allows:</p> <pre><code>'FOO' in MyEnum other = MyEnum.FOO assert other == MyEnum.FOO </code></pre> <p>But has more flexibility as it can have different keys and values. This allows</p> <pre><code>MyEnum.FOO &lt; MyEnum.BAR </code></pre> <p>to act as is expected if you use the version that fills in sequential number values.</p>
16
2011-08-07T05:51:01Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
7,458,935
<p>This solution is a simple way of getting a class for the enumeration defined as a list (no more annoying integer assignments):</p> <p>enumeration.py:</p> <pre><code>import new def create(class_name, names): return new.classobj( class_name, (object,), dict((y, x) for x, y in enumerate(names)) ) </code></pre> <p>example.py:</p> <pre><code>import enumeration Colors = enumeration.create('Colors', ( 'red', 'orange', 'yellow', 'green', 'blue', 'violet', )) </code></pre>
3
2011-09-18T01:26:54Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
8,598,742
<p>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 <code>repr</code>esentation. Here's what I ended up with:</p> <pre><code>&gt;&gt;&gt; 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 ... </code></pre> <p>A whimsical example of using it:</p> <pre><code>&gt;&gt;&gt; class Citrus(Enum): ... Lemon = 1 ... Lime = 2 ... &gt;&gt;&gt; Citrus.Lemon Citrus.Lemon &gt;&gt;&gt; &gt;&gt;&gt; Citrus(1) Citrus.Lemon &gt;&gt;&gt; Citrus(5) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 6, in __new__ KeyError: 5 &gt;&gt;&gt; class Fruit(Citrus): ... Apple = 3 ... Banana = 4 ... &gt;&gt;&gt; Fruit.Apple Fruit.Apple &gt;&gt;&gt; Fruit.Lemon Citrus.Lemon &gt;&gt;&gt; Fruit(1) Citrus.Lemon &gt;&gt;&gt; Fruit(3) Fruit.Apple &gt;&gt;&gt; "%d %s %r" % ((Fruit.Apple,)*3) '3 Apple Fruit.Apple' &gt;&gt;&gt; Fruit(1) is Citrus.Lemon True </code></pre> <p>Key features:</p> <ul> <li><code>str()</code>, <code>int()</code> and <code>repr()</code> 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.</li> <li>Enumerated values returned by the constructor are limited strictly to the predefined values, no accidental enum values.</li> <li>Enumerated values are singletons; they can be strictly compared with <code>is</code></li> </ul>
8
2011-12-22T02:16:04Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
8,905,914
<p>I really like Alec Thomas' solution (http://stackoverflow.com/a/1695250):</p> <pre><code>def enum(**enums): '''simple constant "enums"''' return type('Enum', (object,), enums) </code></pre> <p>It's elegant and clean looking, but it's just a function that creates a class with the specified attributes.</p> <p>With a little modification to the function, we can get it to act a little more 'enumy':</p> <blockquote> <p>NOTE: I created the following examples by trying to reproduce the behavior of pygtk's new style 'enums' (like Gtk.MessageType.WARNING)</p> </blockquote> <pre><code>def enum_base(t, **enums): '''enums with a base class''' T = type('Enum', (t,), {}) for key,val in enums.items(): setattr(T, key, T(val)) return T </code></pre> <p>This creates an enum based off a specified type. In addition to giving attribute access like the previous function, it behaves as you would expect an Enum to with respect to types. It also inherits the base class.</p> <p>For example, integer enums:</p> <pre><code>&gt;&gt;&gt; Numbers = enum_base(int, ONE=1, TWO=2, THREE=3) &gt;&gt;&gt; Numbers.ONE 1 &gt;&gt;&gt; x = Numbers.TWO &gt;&gt;&gt; 10 + x 12 &gt;&gt;&gt; type(Numbers) &lt;type 'type'&gt; &gt;&gt;&gt; type(Numbers.ONE) &lt;class 'Enum'&gt; &gt;&gt;&gt; isinstance(x, Numbers) True </code></pre> <p>Another interesting thing that can be done with this method is customize specific behavior by overriding built-in methods:</p> <pre><code>def enum_repr(t, **enums): '''enums with a base class and repr() output''' class Enum(t): def __repr__(self): return '&lt;enum {0} of type Enum({1})&gt;'.format(self._name, t.__name__) for key,val in enums.items(): i = Enum(val) i._name = key setattr(Enum, key, i) return Enum &gt;&gt;&gt; Numbers = enum_repr(int, ONE=1, TWO=2, THREE=3) &gt;&gt;&gt; repr(Numbers.ONE) '&lt;enum ONE of type Enum(int)&gt;' &gt;&gt;&gt; str(Numbers.ONE) '1' </code></pre>
6
2012-01-18T06:09:18Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
9,201,329
<p>An Enum class can be a one-liner.</p> <pre><code>class Enum(tuple): __getattr__ = tuple.index </code></pre> <p>How to use it (forward and reverse lookup, keys, values, items, etc.)</p> <pre><code>&gt;&gt;&gt; State = Enum(['Unclaimed', 'Claimed']) &gt;&gt;&gt; State.Claimed 1 &gt;&gt;&gt; State[1] 'Claimed' &gt;&gt;&gt; State ('Unclaimed', 'Claimed') &gt;&gt;&gt; range(len(State)) [0, 1] &gt;&gt;&gt; [(k, State[k]) for k in range(len(State))] [(0, 'Unclaimed'), (1, 'Claimed')] &gt;&gt;&gt; [(k, getattr(State, k)) for k in State] [('Unclaimed', 0), ('Claimed', 1)] </code></pre>
44
2012-02-08T20:59:58Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
10,004,274
<p>I use a metaclass to implement an enumeration (in my thought, it is a const). Here is the code:</p> <pre><code>class ConstMeta(type): ''' Metaclass for some class that store constants ''' def __init__(cls, name, bases, dct): ''' init class instance ''' def static_attrs(): ''' @rtype: (static_attrs, static_val_set) @return: Static attributes in dict format and static value set ''' import types attrs = {} val_set = set() #Maybe more filter_names = set(['__doc__', '__init__', '__metaclass__', '__module__', '__main__']) for key, value in dct.iteritems(): if type(value) != types.FunctionType and key not in filter_names: if len(value) != 2: raise NotImplementedError('not support for values that is not 2 elements!') #Check value[0] duplication. if value[0] not in val_set: val_set.add(value[0]) else: raise KeyError("%s 's key: %s is duplicated!" % (dict([(key, value)]), value[0])) attrs[key] = value return attrs, val_set attrs, val_set = static_attrs() #Set STATIC_ATTRS to class instance so that can reuse setattr(cls, 'STATIC_ATTRS', attrs) setattr(cls, 'static_val_set', val_set) super(ConstMeta, cls).__init__(name, bases, dct) def __getattribute__(cls, name): ''' Rewrite the special function so as to get correct attribute value ''' static_attrs = object.__getattribute__(cls, 'STATIC_ATTRS') if name in static_attrs: return static_attrs[name][0] return object.__getattribute__(cls, name) def static_values(cls): ''' Put values in static attribute into a list, use the function to validate value. @return: Set of values ''' return cls.static_val_set def __getitem__(cls, key): ''' Rewrite to make syntax SomeConstClass[key] works, and return desc string of related static value. @return: Desc string of related static value ''' for k, v in cls.STATIC_ATTRS.iteritems(): if v[0] == key: return v[1] raise KeyError('Key: %s does not exists in %s !' % (str(key), repr(cls))) class Const(object): ''' Base class for constant class. @usage: Definition: (must inherit from Const class! &gt;&gt;&gt; class SomeConst(Const): &gt;&gt;&gt; STATUS_NAME_1 = (1, 'desc for the status1') &gt;&gt;&gt; STATUS_NAME_2 = (2, 'desc for the status2') Invoke(base upper SomeConst class): 1) SomeConst.STATUS_NAME_1 returns 1 2) SomeConst[1] returns 'desc for the status1' 3) SomeConst.STATIC_ATTRS returns {'STATUS_NAME_1': (1, 'desc for the status1'), 'STATUS_NAME_2': (2, 'desc for the status2')} 4) SomeConst.static_values() returns set([1, 2]) Attention: SomeCosnt's value 1, 2 can not be duplicated! If WrongConst is like this, it will raise KeyError: class WrongConst(Const): STATUS_NAME_1 = (1, 'desc for the status1') STATUS_NAME_2 = (1, 'desc for the status2') ''' __metaclass__ = ConstMeta ################################################################## #Const Base Class ends ################################################################## def main(): class STATUS(Const): ERROR = (-3, '??') OK = (0, '??') print STATUS.ERROR print STATUS.static_values() print STATUS.STATIC_ATTRS #Usage sample: user_input = 1 #Validate input: print user_input in STATUS.static_values() #Template render like: print '&lt;select&gt;' for key, value in STATUS.STATIC_ATTRS.items(): print '&lt;option value="%s"&gt;%s&lt;/option&gt;' % (value[0], value[1]) print '&lt;/select&gt;' if __name__ == '__main__': main() </code></pre>
1
2012-04-04T02:43:36Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
11,147,900
<p>A variant (with support to get an enum value's name) to <a href="http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python/1695250#1695250">Alec Thomas's neat answer</a>:</p> <pre><code>class EnumBase(type): def __init__(self, name, base, fields): super(EnumBase, self).__init__(name, base, fields) self.__mapping = dict((v, k) for k, v in fields.iteritems()) def __getitem__(self, val): return self.__mapping[val] def enum(*seq, **named): enums = dict(zip(seq, range(len(seq))), **named) return EnumBase('Enum', (), enums) Numbers = enum(ONE=1, TWO=2, THREE='three') print Numbers.TWO print Numbers[Numbers.ONE] print Numbers[2] print Numbers['three'] </code></pre>
2
2012-06-21T22:43:55Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
13,474,078
<p>I like to use lists or sets as enumerations. For example:</p> <pre><code>&gt;&gt;&gt; packet_types = ['INIT', 'FINI', 'RECV', 'SEND'] &gt;&gt;&gt; packet_types.index('INIT') 0 &gt;&gt;&gt; packet_types.index('FINI') 1 &gt;&gt;&gt; </code></pre>
1
2012-11-20T13:18:46Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
14,628,126
<p>The solution that I usually use is this simple function to get an instance of a dynamically created class.</p> <pre><code>def enum(names): "Create a simple enumeration having similarities to C." return type('enum', (), dict(map(reversed, enumerate( names.replace(',', ' ').split())), __slots__=()))() </code></pre> <p>Using it is as simple as calling the function with a string having the names that you want to reference.</p> <pre><code>grade = enum('A B C D F') state = enum('awake, sleeping, dead') </code></pre> <p>The values are just integers, so you can take advantage of that if desired (just like in the C language).</p> <pre><code>&gt;&gt;&gt; grade.A 0 &gt;&gt;&gt; grade.B 1 &gt;&gt;&gt; grade.F == 4 True &gt;&gt;&gt; state.dead == 2 True </code></pre>
2
2013-01-31T14:27:43Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
15,886,819
<h2>Python 2.7 and find_name()</h2> <p>Here is an easy-to-read implementation of the chosen idea with some helper methods, which perhaps are more Pythonic and cleaner to use than "reverse_mapping". Requires Python >= 2.7. </p> <p>To address some comments below, Enums are quite useful to prevent spelling mistakes in code, e.g. for state machines, error classifiers, etc.</p> <pre><code>def Enum(*sequential, **named): """Generate a new enum type. Usage example: ErrorClass = Enum('STOP','GO') print ErrorClass.find_name(ErrorClass.STOP) = "STOP" print ErrorClass.find_val("STOP") = 0 ErrorClass.FOO # Raises AttributeError """ enums = { v:k for k,v in enumerate(sequential) } if not named else named @classmethod def find_name(cls, val): result = [ k for k,v in cls.__dict__.iteritems() if v == val ] if not len(result): raise ValueError("Value %s not found in Enum" % val) return result[0] @classmethod def find_val(cls, n): return getattr(cls, n) enums['find_val'] = find_val enums['find_name'] = find_name return type('Enum', (), enums) </code></pre>
1
2013-04-08T18:58:52Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
16,095,707
<p>While the original enum proposal, <a href="http://www.python.org/dev/peps/pep-0354/" rel="nofollow">PEP 354</a>, was rejected years ago, it keeps coming back up. Some kind of enum was intended to be added to 3.2, but it got pushed back to 3.3 and then forgotten. And now there's a <a href="http://www.python.org/dev/peps/pep-0435/" rel="nofollow">PEP 435</a> intended for inclusion in Python 3.4. The reference implementation of PEP 435 is <a href="http://pythonhosted.org/flufl.enum/docs/using.html" rel="nofollow"><code>flufl.enum</code></a>.</p> <p>As of April 2013, there seems to be a general consensus that <em>something</em> should be added to the standard library in 3.4—as long as people can agree on what that "something" should be. That's the hard part. See the threads starting <a href="http://mail.python.org/pipermail/python-ideas/2013-January/019003.html" rel="nofollow">here</a> and <a href="http://mail.python.org/pipermail/python-ideas/2013-February/019332.html" rel="nofollow">here</a>, and a half dozen other threads in the early months of 2013.</p> <p>Meanwhile, every time this comes up, a slew of new designs and implementations appear on PyPI, ActiveState, etc., so if you don't like the FLUFL design, try a <a href="https://pypi.python.org/pypi?%3aaction=search&amp;term=enum&amp;submit=search" rel="nofollow">PyPI search</a>.</p>
3
2013-04-19T01:16:20Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
16,486,444
<p>On 2013-05-10, Guido agreed to accept <a href="http://www.python.org/dev/peps/pep-0435/">PEP 435</a> into the Python 3.4 standard library. This means that Python finally has builtin support for enumerations!</p> <p>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 <a href="https://pypi.python.org/pypi/enum34">enum34</a>.</p> <p>Declaration:</p> <pre><code>&gt;&gt;&gt; from enum import Enum &gt;&gt;&gt; class Color(Enum): ... red = 1 ... green = 2 ... blue = 3 </code></pre> <p>Representation:</p> <pre><code>&gt;&gt;&gt; print(Color.red) Color.red &gt;&gt;&gt; print(repr(Color.red)) &lt;Color.red: 1&gt; </code></pre> <p>Iteration:</p> <pre><code>&gt;&gt;&gt; for color in Color: ... print(color) ... Color.red Color.green Color.blue </code></pre> <p>Programmatic access:</p> <pre><code>&gt;&gt;&gt; Color(1) Color.red &gt;&gt;&gt; Color['blue'] Color.blue </code></pre> <p>For more information, refer to <a href="http://www.python.org/dev/peps/pep-0435/">the proposal</a>. Official documentation will probably follow soon.</p>
23
2013-05-10T16:09:02Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
16,486,681
<p>The new standard in Python is <a href="http://www.python.org/dev/peps/pep-0435/" rel="nofollow">PEP 435</a>, so an Enum class will be available in future versions of Python:</p> <pre><code>&gt;&gt;&gt; from enum import Enum </code></pre> <p>However to begin using it now you can install the <a href="http://bazaar.launchpad.net/~barry/flufl.enum/trunk/view/head:/flufl/enum/README.rst" rel="nofollow">original library</a> that motivated the PEP:</p> <pre><code>#sudo pip install flufl.enum //or #sudo easy_install flufl.enum </code></pre> <p>Then you <a href="http://pythonhosted.org/flufl.enum/docs/using.html" rel="nofollow">can use it as per its online guide</a>:</p> <pre><code>&gt;&gt;&gt; from flufl.enum import Enum &gt;&gt;&gt; class Colors(Enum): ... red = 1 ... green = 2 ... blue = 3 &gt;&gt;&gt; for color in Colors: print color Colors.red Colors.green Colors.blue </code></pre>
6
2013-05-10T16:22:42Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
17,201,727
<p>Here's an approach with some different characteristics I find valuable:</p> <ul> <li>allows > and &lt; comparison based on order in enum, not lexical order</li> <li>can address item by name, property or index: x.a, x['a'] or x[0]</li> <li>supports slicing operations like [:] or [-1]</li> </ul> <p>and most importantly <strong>prevents comparisons between enums of different types</strong>!</p> <p>Based closely on <a href="http://code.activestate.com/recipes/413486-first-class-enums-in-python" rel="nofollow">http://code.activestate.com/recipes/413486-first-class-enums-in-python</a>.</p> <p>Many doctests included here to illustrate what's different about this approach.</p> <pre><code>def enum(*names): """ SYNOPSIS Well-behaved enumerated type, easier than creating custom classes DESCRIPTION Create a custom type that implements an enumeration. Similar in concept to a C enum but with some additional capabilities and protections. See http://code.activestate.com/recipes/413486-first-class-enums-in-python/. PARAMETERS names Ordered list of names. The order in which names are given will be the sort order in the enum type. Duplicate names are not allowed. Unicode names are mapped to ASCII. RETURNS Object of type enum, with the input names and the enumerated values. EXAMPLES &gt;&gt;&gt; letters = enum('a','e','i','o','u','b','c','y','z') &gt;&gt;&gt; letters.a &lt; letters.e True ## index by property &gt;&gt;&gt; letters.a a ## index by position &gt;&gt;&gt; letters[0] a ## index by name, helpful for bridging string inputs to enum &gt;&gt;&gt; letters['a'] a ## sorting by order in the enum() create, not character value &gt;&gt;&gt; letters.u &lt; letters.b True ## normal slicing operations available &gt;&gt;&gt; letters[-1] z ## error since there are not 100 items in enum &gt;&gt;&gt; letters[99] Traceback (most recent call last): ... IndexError: tuple index out of range ## error since name does not exist in enum &gt;&gt;&gt; letters['ggg'] Traceback (most recent call last): ... ValueError: tuple.index(x): x not in tuple ## enums must be named using valid Python identifiers &gt;&gt;&gt; numbers = enum(1,2,3,4) Traceback (most recent call last): ... AssertionError: Enum values must be string or unicode &gt;&gt;&gt; a = enum('-a','-b') Traceback (most recent call last): ... TypeError: Error when calling the metaclass bases __slots__ must be identifiers ## create another enum &gt;&gt;&gt; tags = enum('a','b','c') &gt;&gt;&gt; tags.a a &gt;&gt;&gt; letters.a a ## can't compare values from different enums &gt;&gt;&gt; letters.a == tags.a Traceback (most recent call last): ... AssertionError: Only values from the same enum are comparable &gt;&gt;&gt; letters.a &lt; tags.a Traceback (most recent call last): ... AssertionError: Only values from the same enum are comparable ## can't update enum after create &gt;&gt;&gt; letters.a = 'x' Traceback (most recent call last): ... AttributeError: 'EnumClass' object attribute 'a' is read-only ## can't update enum after create &gt;&gt;&gt; del letters.u Traceback (most recent call last): ... AttributeError: 'EnumClass' object attribute 'u' is read-only ## can't have non-unique enum values &gt;&gt;&gt; x = enum('a','b','c','a') Traceback (most recent call last): ... AssertionError: Enums must not repeat values ## can't have zero enum values &gt;&gt;&gt; x = enum() Traceback (most recent call last): ... AssertionError: Empty enums are not supported ## can't have enum values that look like special function names ## since these could collide and lead to non-obvious errors &gt;&gt;&gt; x = enum('a','b','c','__cmp__') Traceback (most recent call last): ... AssertionError: Enum values beginning with __ are not supported LIMITATIONS Enum values of unicode type are not preserved, mapped to ASCII instead. """ ## must have at least one enum value assert names, 'Empty enums are not supported' ## enum values must be strings assert len([i for i in names if not isinstance(i, types.StringTypes) and not \ isinstance(i, unicode)]) == 0, 'Enum values must be string or unicode' ## enum values must not collide with special function names assert len([i for i in names if i.startswith("__")]) == 0,\ 'Enum values beginning with __ are not supported' ## each enum value must be unique from all others assert names == uniquify(names), 'Enums must not repeat values' class EnumClass(object): """ See parent function for explanation """ __slots__ = names def __iter__(self): return iter(constants) def __len__(self): return len(constants) def __getitem__(self, i): ## this makes xx['name'] possible if isinstance(i, types.StringTypes): i = names.index(i) ## handles the more normal xx[0] return constants[i] def __repr__(self): return 'enum' + str(names) def __str__(self): return 'enum ' + str(constants) def index(self, i): return names.index(i) class EnumValue(object): """ See parent function for explanation """ __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): assert self.enumtype is other.enumtype, 'Only values from the same enum are comparable' return cmp(self.value, other.value) def __invert__(self): return constants[maximum - self.value] def __nonzero__(self): ## return bool(self.value) ## Original code led to bool(x[0])==False, not correct return True 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 </code></pre>
3
2013-06-19T21:30:47Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
18,627,613
<p>Didn't see this one in the list of answers, here is the one I whipped up. It allows the use of 'in' keyword and len() method:</p> <pre><code>class EnumTypeError(TypeError): pass class Enum(object): """ Minics enum type from different languages Usage: Letters = Enum(list('abc')) a = Letters.a print(a in Letters) # True print(54 in Letters) # False """ def __init__(self, enums): if isinstance(enums, dict): self.__dict__.update(enums) elif isinstance(enums, list) or isinstance(enums, tuple): self.__dict__.update(**dict((v,k) for k,v in enumerate(enums))) else: raise EnumTypeError def __contains__(self, key): return key in self.__dict__.values() def __len__(self): return len(self.__dict__.values()) if __name__ == '__main__': print('Using a dictionary to create Enum:') Letters = Enum(dict((v,k) for k,v in enumerate(list('abcde')))) a = Letters.a print('\tIs a in e?', a in Letters) print('\tIs 54 in e?', 54 in Letters) print('\tLength of Letters enum:', len(Letters)) print('\nUsing a list to create Enum:') Letters = Enum(list('abcde')) a = Letters.a print('\tIs a in e?', a in Letters) print('\tIs 54 in e?', 54 in Letters) print('\tLength of Letters enum:', len(Letters)) try: # make sure we raise an exception if we pass an invalid arg Failure = Enum('This is a Failure') print('Failure') except EnumTypeError: print('Success!') </code></pre> <p>Output:</p> <pre><code>Using a dictionary to create Enum: Is a in e? True Is 54 in e? False Length of Letters enum: 5 Using a list to create Enum: Is a in e? True Is 54 in e? False Length of Letters enum: 5 Success! </code></pre>
2
2013-09-05T04:12:03Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
20,520,884
<p>From Python 3.4 there will be official support for enums. You can find documentation and examples <a href="http://docs.python.org/3.4/library/enum.html" rel="nofollow">here on Python 3.4 documentation page</a>.</p> <blockquote> <p>Enumerations are created using the class syntax, which makes them easy to read and write. An alternative creation method is described in Functional API. To define an enumeration, subclass Enum as follows:</p> </blockquote> <pre><code>from enum import Enum class Color(Enum): red = 1 green = 2 blue = 3 </code></pre>
5
2013-12-11T13:49:01Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
22,461,315
<p>Here is a nice Python recipe that I found here: <a href="http://code.activestate.com/recipes/577024-yet-another-enum-for-python/" rel="nofollow">http://code.activestate.com/recipes/577024-yet-another-enum-for-python/</a></p> <pre><code>def enum(typename, field_names): "Create a new enumeration type" if isinstance(field_names, str): field_names = field_names.replace(',', ' ').split() d = dict((reversed(nv) for nv in enumerate(field_names)), __slots__ = ()) return type(typename, (object,), d)() </code></pre> <p>Example Usage:</p> <pre><code>STATE = enum('STATE', 'GET_QUIZ, GET_VERSE, TEACH') </code></pre> <p>More details can be found on the recipe page.</p>
2
2014-03-17T17:34:55Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
22,723,724
<p>Keep it simple:</p> <pre><code>class Enum(object): def __init__(self, tupleList): self.tupleList = tupleList def __getattr__(self, name): return self.tupleList.index(name) </code></pre> <p>Then:</p> <pre><code>DIRECTION = Enum(('UP', 'DOWN', 'LEFT', 'RIGHT')) DIRECTION.DOWN 1 </code></pre>
8
2014-03-28T21:44:30Z
[ "python", "python-3.x", "enums" ]
How can I represent an 'Enum' in Python?
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
1,146
2008-08-31T15:55:47Z
26,861,507
<pre><code>def enum(*sequential, **named): enums = dict(zip(sequential, [object() for _ in range(len(sequential))]), **named) return type('Enum', (), enums) </code></pre> <p>If you name it, is your problem, but if not creating objects instead of values allows you to do this:</p> <pre><code>&gt;&gt;&gt; DOG = enum('BARK', 'WALK', 'SIT') &gt;&gt;&gt; CAT = enum('MEOW', 'WALK', 'SIT') &gt;&gt;&gt; DOG.WALK == CAT.WALK False </code></pre> <p>When using other implementations sited here (also when using named instances in my example) you must be sure you never try to compare objects from different enums. For here's a possible pitfall:</p> <pre><code>&gt;&gt;&gt; DOG = enum('BARK'=1, 'WALK'=2, 'SIT'=3) &gt;&gt;&gt; CAT = enum('WALK'=1, 'SIT'=2) &gt;&gt;&gt; pet1_state = DOG.BARK &gt;&gt;&gt; pet2_state = CAT.WALK &gt;&gt;&gt; pet1_state == pet2_state True </code></pre> <p>Yikes!</p>
6
2014-11-11T09:26:34Z
[ "python", "python-3.x", "enums" ]
Resources for lexing, tokenising and parsing in python
36,953
<p>Can people point me to resources on lexing, parsing and tokenising with Python?</p> <p>I'm doing a little hacking on an open source project (<a href="http://www.hotwire-shell.org/">hotwire</a>) and wanted to do a few changes to the code that <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/externals/shlex.py">lexes</a>, <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/command.py">parses and tokenises</a> the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.</p> <p>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 ...)</p> <p><strong>Edit:</strong> (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. </p> <p>So could someone point me to a tutorial where I can build a basic parser from scratch, using just python?</p>
45
2008-08-31T16:50:35Z
36,978
<p>Have a look at the standard module <a href="http://docs.python.org/lib/module-shlex.html" rel="nofollow">shlex</a> and modify one copy of it to match the syntax you use for your shell, it is a good starting point</p> <p>If you want all the power of a complete solution for lexing/parsing, <a href="http://www.antlr.org/wiki/display/ANTLR3/Antlr3PythonTarget" rel="nofollow">ANTLR</a> can generate python too.</p>
4
2008-08-31T17:14:06Z
[ "python", "parsing", "resources", "lex" ]
Resources for lexing, tokenising and parsing in python
36,953
<p>Can people point me to resources on lexing, parsing and tokenising with Python?</p> <p>I'm doing a little hacking on an open source project (<a href="http://www.hotwire-shell.org/">hotwire</a>) and wanted to do a few changes to the code that <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/externals/shlex.py">lexes</a>, <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/command.py">parses and tokenises</a> the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.</p> <p>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 ...)</p> <p><strong>Edit:</strong> (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. </p> <p>So could someone point me to a tutorial where I can build a basic parser from scratch, using just python?</p>
45
2008-08-31T16:50:35Z
37,245
<p>I suggest <a href="http://www.canonware.com/Parsing/" rel="nofollow">http://www.canonware.com/Parsing/</a>, since it is pure python and you don't need to learn a grammar, but it isn't widely used, and has comparatively little documentation. The heavyweight is ANTLR and PyParsing. ANTLR can generate java and C++ parsers too, and AST walkers but you will have to learn what amounts to a new language.</p>
3
2008-08-31T23:14:54Z
[ "python", "parsing", "resources", "lex" ]
Resources for lexing, tokenising and parsing in python
36,953
<p>Can people point me to resources on lexing, parsing and tokenising with Python?</p> <p>I'm doing a little hacking on an open source project (<a href="http://www.hotwire-shell.org/">hotwire</a>) and wanted to do a few changes to the code that <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/externals/shlex.py">lexes</a>, <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/command.py">parses and tokenises</a> the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.</p> <p>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 ...)</p> <p><strong>Edit:</strong> (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. </p> <p>So could someone point me to a tutorial where I can build a basic parser from scratch, using just python?</p>
45
2008-08-31T16:50:35Z
107,187
<p>I'm a happy user of <a href="http://www.dabeaz.com/ply/">PLY</a>. It is a pure-Python implementation of Lex &amp; Yacc, with lots of small niceties that make it quite Pythonic and easy to use. Since Lex &amp; Yacc are the most popular lexing &amp; 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 &amp; Yacc, and you can freely apply it to PLY.</p> <p>PLY also has a good <a href="http://www.dabeaz.com/ply/ply.html">documentation page</a> with some simple examples to get you started. </p> <p>For a listing of lots of Python parsing tools, see <a href="http://nedbatchelder.com/text/python-parsers.html">this</a>.</p>
23
2008-09-20T05:07:57Z
[ "python", "parsing", "resources", "lex" ]
Resources for lexing, tokenising and parsing in python
36,953
<p>Can people point me to resources on lexing, parsing and tokenising with Python?</p> <p>I'm doing a little hacking on an open source project (<a href="http://www.hotwire-shell.org/">hotwire</a>) and wanted to do a few changes to the code that <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/externals/shlex.py">lexes</a>, <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/command.py">parses and tokenises</a> the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.</p> <p>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 ...)</p> <p><strong>Edit:</strong> (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. </p> <p>So could someone point me to a tutorial where I can build a basic parser from scratch, using just python?</p>
45
2008-08-31T16:50:35Z
107,207
<p><a href="http://pygments.org/" rel="nofollow">pygments</a> is a source code syntax highlighter written in python. It has lexers and formatters, and may be interesting to peek at the source.</p>
4
2008-09-20T05:15:57Z
[ "python", "parsing", "resources", "lex" ]
Resources for lexing, tokenising and parsing in python
36,953
<p>Can people point me to resources on lexing, parsing and tokenising with Python?</p> <p>I'm doing a little hacking on an open source project (<a href="http://www.hotwire-shell.org/">hotwire</a>) and wanted to do a few changes to the code that <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/externals/shlex.py">lexes</a>, <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/command.py">parses and tokenises</a> the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.</p> <p>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 ...)</p> <p><strong>Edit:</strong> (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. </p> <p>So could someone point me to a tutorial where I can build a basic parser from scratch, using just python?</p>
45
2008-08-31T16:50:35Z
137,207
<p>For medium-complex grammars, <a href="http://pyparsing.wikispaces.com/">PyParsing</a> is brilliant. You can define grammars directly within Python code, no need for code generation:</p> <pre><code>&gt;&gt;&gt; from pyparsing import Word, alphas &gt;&gt;&gt; greet = Word( alphas ) + "," + Word( alphas ) + "!" # &lt;-- grammar defined here &gt;&gt;&gt; hello = "Hello, World!" &gt;&gt;&gt;&gt; print hello, "-&gt;", greet.parseString( hello ) Hello, World! -&gt; ['Hello', ',', 'World', '!'] </code></pre> <p>(Example taken from the PyParsing home page).</p> <p>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.</p> <p>There are many helper functions that encapsulate recurring patterns, like operator hierarchies, quoted strings, nesting or C-style comments.</p>
15
2008-09-26T01:05:35Z
[ "python", "parsing", "resources", "lex" ]
Resources for lexing, tokenising and parsing in python
36,953
<p>Can people point me to resources on lexing, parsing and tokenising with Python?</p> <p>I'm doing a little hacking on an open source project (<a href="http://www.hotwire-shell.org/">hotwire</a>) and wanted to do a few changes to the code that <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/externals/shlex.py">lexes</a>, <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/command.py">parses and tokenises</a> the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.</p> <p>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 ...)</p> <p><strong>Edit:</strong> (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. </p> <p>So could someone point me to a tutorial where I can build a basic parser from scratch, using just python?</p>
45
2008-08-31T16:50:35Z
279,733
<p>Here's a few things to get you started (roughly from simplest-to-most-complex, least-to-most-powerful):</p> <p><a href="http://en.wikipedia.org/wiki/Recursive_descent_parser" rel="nofollow">http://en.wikipedia.org/wiki/Recursive_descent_parser</a></p> <p><a href="http://en.wikipedia.org/wiki/Top-down_parsing" rel="nofollow">http://en.wikipedia.org/wiki/Top-down_parsing</a></p> <p><a href="http://en.wikipedia.org/wiki/LL_parser" rel="nofollow">http://en.wikipedia.org/wiki/LL_parser</a></p> <p><a href="http://effbot.org/zone/simple-top-down-parsing.htm" rel="nofollow">http://effbot.org/zone/simple-top-down-parsing.htm</a></p> <p><a href="http://en.wikipedia.org/wiki/Bottom-up_parsing" rel="nofollow">http://en.wikipedia.org/wiki/Bottom-up_parsing</a></p> <p><a href="http://en.wikipedia.org/wiki/LR_parser" rel="nofollow">http://en.wikipedia.org/wiki/LR_parser</a></p> <p><a href="http://en.wikipedia.org/wiki/GLR_parser" rel="nofollow">http://en.wikipedia.org/wiki/GLR_parser</a></p> <p>When I learned this stuff, it was in a semester-long 400-level university course. We did a number of assignments where we did parsing by hand; if you want to really understand what's going on under the hood, I'd recommend the same approach.</p> <p>This isn't the book I used, but it's pretty good: <a href="http://rads.stackoverflow.com/amzn/click/0201000229" rel="nofollow">Principles of Compiler Design</a>.</p> <p>Hopefully that's enough to get you started :)</p>
4
2008-11-11T01:13:42Z
[ "python", "parsing", "resources", "lex" ]
Resources for lexing, tokenising and parsing in python
36,953
<p>Can people point me to resources on lexing, parsing and tokenising with Python?</p> <p>I'm doing a little hacking on an open source project (<a href="http://www.hotwire-shell.org/">hotwire</a>) and wanted to do a few changes to the code that <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/externals/shlex.py">lexes</a>, <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/command.py">parses and tokenises</a> the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.</p> <p>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 ...)</p> <p><strong>Edit:</strong> (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. </p> <p>So could someone point me to a tutorial where I can build a basic parser from scratch, using just python?</p>
45
2008-08-31T16:50:35Z
14,315,179
<p>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:</p> <p>"A Simple Intepreter from Scratch in Python:" <a href="http://www.jayconrod.com/posts/37/a-simple-interpreter-from-scratch-in-python-part-1">Part 1</a>, <a href="http://www.jayconrod.com/posts/38/a-simple-interpreter-from-scratch-in-python-part-2">Part 2</a>, <a href="http://www.jayconrod.com/posts/39/a-simple-interpreter-from-scratch-in-python-part-3">Part 3</a>, and <a href="http://www.jayconrod.com/posts/40/a-simple-interpreter-from-scratch-in-python-part-4">Part 4</a>.</p>
11
2013-01-14T08:36:04Z
[ "python", "parsing", "resources", "lex" ]
How to make Ruby or Python web sites to use multiple cores?
37,142
<p>Even though <a href="http://twistedmatrix.com/pipermail/twisted-python/2004-May/007896.html">Python</a> and <a href="http://www.reddit.com/comments/6wmum/thread_safe_ruby_on_rails_in_22_release/">Ruby</a> have one kernel thread per interpreter thread, they have a global interpreter lock (GIL) that is used to protect potentially shared data structures, so this inhibits multi-processor execution. Even though the portions in those languajes that are written in C or C++ can be free-threaded, that's not possible with pure interpreted code unless you use multiple processes. What's the best way to achieve this? <a href="http://blogs.codehaus.org/people/tirsen/archives/001041_ruby_on_rails_and_fastcgi_scaling_using_processes_instead_of_threads.html">Using FastCGI</a>? Creating a <a href="http://blog.innerewut.de/files/images/stage_2.png">cluster or a farm</a> of virtualized servers? Using their Java equivalents, JRuby and Jython?</p>
7
2008-08-31T21:41:24Z
37,146
<p>Use an interface that runs each response in a separate interpreter, such as <code>mod_wsgi</code> for Python. This lets multi-threading be used without encountering the GIL.</p> <p>EDIT: Apparently, <code>mod_wsgi</code> no longer supports multiple interpreters per process because idiots couldn't figure out how to properly implement extension modules. It still supports running requests in separate processes FastCGI-style, though, so that's apparently the current accepted solution.</p>
1
2008-08-31T21:43:58Z
[ "python", "ruby", "multithreading", "multicore" ]
How to make Ruby or Python web sites to use multiple cores?
37,142
<p>Even though <a href="http://twistedmatrix.com/pipermail/twisted-python/2004-May/007896.html">Python</a> and <a href="http://www.reddit.com/comments/6wmum/thread_safe_ruby_on_rails_in_22_release/">Ruby</a> have one kernel thread per interpreter thread, they have a global interpreter lock (GIL) that is used to protect potentially shared data structures, so this inhibits multi-processor execution. Even though the portions in those languajes that are written in C or C++ can be free-threaded, that's not possible with pure interpreted code unless you use multiple processes. What's the best way to achieve this? <a href="http://blogs.codehaus.org/people/tirsen/archives/001041_ruby_on_rails_and_fastcgi_scaling_using_processes_instead_of_threads.html">Using FastCGI</a>? Creating a <a href="http://blog.innerewut.de/files/images/stage_2.png">cluster or a farm</a> of virtualized servers? Using their Java equivalents, JRuby and Jython?</p>
7
2008-08-31T21:41:24Z
37,153
<p>I'm not totally sure which problem you want so solve, but if you deploy your python/django application via an apache prefork MPM using mod_python apache will start several worker processes for handling different requests.</p> <p>If one request needs so much resources, that you want to use multiple cores have a look at <a href="http://pyprocessing.berlios.de/" rel="nofollow">pyprocessing</a>. But I don't think that would be wise.</p>
4
2008-08-31T21:53:30Z
[ "python", "ruby", "multithreading", "multicore" ]
How to make Ruby or Python web sites to use multiple cores?
37,142
<p>Even though <a href="http://twistedmatrix.com/pipermail/twisted-python/2004-May/007896.html">Python</a> and <a href="http://www.reddit.com/comments/6wmum/thread_safe_ruby_on_rails_in_22_release/">Ruby</a> have one kernel thread per interpreter thread, they have a global interpreter lock (GIL) that is used to protect potentially shared data structures, so this inhibits multi-processor execution. Even though the portions in those languajes that are written in C or C++ can be free-threaded, that's not possible with pure interpreted code unless you use multiple processes. What's the best way to achieve this? <a href="http://blogs.codehaus.org/people/tirsen/archives/001041_ruby_on_rails_and_fastcgi_scaling_using_processes_instead_of_threads.html">Using FastCGI</a>? Creating a <a href="http://blog.innerewut.de/files/images/stage_2.png">cluster or a farm</a> of virtualized servers? Using their Java equivalents, JRuby and Jython?</p>
7
2008-08-31T21:41:24Z
37,203
<p>The 'standard' way to do this with rails is to run a "pack" of Mongrel instances (ie: 4 copies of the rails application) and then use apache or nginx or some other piece of software to sit in front of them and act as a load balancer. </p> <p>This is probably how it's done with other ruby frameworks such as merb etc, but I haven't used those personally.</p> <p>The OS will take care of running each mongrel on it's own CPU.</p> <p>If you install <a href="http://www.modrails.com/" rel="nofollow">mod_rails aka phusion passenger</a> it will start and stop multiple copies of the rails process for you as well, so it will end up spreading the load across multiple CPUs/cores in a similar way.</p>
4
2008-08-31T22:41:55Z
[ "python", "ruby", "multithreading", "multicore" ]
How to make Ruby or Python web sites to use multiple cores?
37,142
<p>Even though <a href="http://twistedmatrix.com/pipermail/twisted-python/2004-May/007896.html">Python</a> and <a href="http://www.reddit.com/comments/6wmum/thread_safe_ruby_on_rails_in_22_release/">Ruby</a> have one kernel thread per interpreter thread, they have a global interpreter lock (GIL) that is used to protect potentially shared data structures, so this inhibits multi-processor execution. Even though the portions in those languajes that are written in C or C++ can be free-threaded, that's not possible with pure interpreted code unless you use multiple processes. What's the best way to achieve this? <a href="http://blogs.codehaus.org/people/tirsen/archives/001041_ruby_on_rails_and_fastcgi_scaling_using_processes_instead_of_threads.html">Using FastCGI</a>? Creating a <a href="http://blog.innerewut.de/files/images/stage_2.png">cluster or a farm</a> of virtualized servers? Using their Java equivalents, JRuby and Jython?</p>
7
2008-08-31T21:41:24Z
190,394
<p>In Python and Ruby it is only possible to use multiple cores, is to spawn new (heavyweight) processes. The Java counterparts inherit the possibilities of the Java platform. You could imply use Java threads. That is for example a reason why sometimes (often) Java Application Server like Glassfish are used for Ruby on Rails applications.</p>
1
2008-10-10T07:18:15Z
[ "python", "ruby", "multithreading", "multicore" ]
How to make Ruby or Python web sites to use multiple cores?
37,142
<p>Even though <a href="http://twistedmatrix.com/pipermail/twisted-python/2004-May/007896.html">Python</a> and <a href="http://www.reddit.com/comments/6wmum/thread_safe_ruby_on_rails_in_22_release/">Ruby</a> have one kernel thread per interpreter thread, they have a global interpreter lock (GIL) that is used to protect potentially shared data structures, so this inhibits multi-processor execution. Even though the portions in those languajes that are written in C or C++ can be free-threaded, that's not possible with pure interpreted code unless you use multiple processes. What's the best way to achieve this? <a href="http://blogs.codehaus.org/people/tirsen/archives/001041_ruby_on_rails_and_fastcgi_scaling_using_processes_instead_of_threads.html">Using FastCGI</a>? Creating a <a href="http://blog.innerewut.de/files/images/stage_2.png">cluster or a farm</a> of virtualized servers? Using their Java equivalents, JRuby and Jython?</p>
7
2008-08-31T21:41:24Z
191,257
<p>For Python, the <a href="http://pyprocessing.berlios.de/" rel="nofollow">PyProcessing</a> project allows you to program with processes much like you would use threads. It is included in the standard library of the recently released 2.6 version as <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow"><code>multiprocessing</code></a>. The module has many features for establishing and controlling access to shared data structures (queues, pipes, etc.) and support for common idioms (i.e. managers and worker pools).</p>
0
2008-10-10T13:24:31Z
[ "python", "ruby", "multithreading", "multicore" ]
How can I simply inherit methods from an existing instance?
37,479
<p>below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.</p> <pre><code>import cgi class ClassX(object): pass # ... with own __repr__ class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("&lt;H1&gt;","&lt;/H1&gt;")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() </code></pre> <p>Output:</p> <pre>Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters</pre> <p>Is what I'm trying to do possible? If so, what am I doing wrong?</p>
0
2008-09-01T05:17:35Z
37,488
<blockquote> <p>Is what I'm trying to do possible? If so, what am I doing wrong?</p> </blockquote> <p>It's certainly possible. What's wrong is that <code>HTMLDecorator.__init__()</code> doesn't accept parameters.</p> <p>Here's a simple example:</p> <pre><code>def decorator (func): def new_func (): return "new_func %s" % func () return new_func @decorator def a (): return "a" def b (): return "b" print a() # new_func a print decorator (b)() # new_func b </code></pre>
0
2008-09-01T05:26:06Z
[ "python", "oop", "inheritance", "object" ]
How can I simply inherit methods from an existing instance?
37,479
<p>below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.</p> <pre><code>import cgi class ClassX(object): pass # ... with own __repr__ class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("&lt;H1&gt;","&lt;/H1&gt;")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() </code></pre> <p>Output:</p> <pre>Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters</pre> <p>Is what I'm trying to do possible? If so, what am I doing wrong?</p>
0
2008-09-01T05:17:35Z
37,513
<p>@John (37448):</p> <p>Sorry, I might have misled you with the name (bad choice). I'm not really looking for a decorator function, or anything to do with decorators at all. What I'm after is for the html(self) def to use ClassX or ClassY's <code>__repr__</code>. I want this to work without modifying ClassX or ClassY.</p>
0
2008-09-01T06:10:04Z
[ "python", "oop", "inheritance", "object" ]
How can I simply inherit methods from an existing instance?
37,479
<p>below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.</p> <pre><code>import cgi class ClassX(object): pass # ... with own __repr__ class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("&lt;H1&gt;","&lt;/H1&gt;")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() </code></pre> <p>Output:</p> <pre>Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters</pre> <p>Is what I'm trying to do possible? If so, what am I doing wrong?</p>
0
2008-09-01T05:17:35Z
37,526
<p>Ah, in that case, perhaps code like this will be useful? It doesn't really have anything to do with decorators, but demonstrates how to pass arguments to a class's initialization function and to retrieve those arguments for later.</p> <pre><code>import cgi class ClassX(object): def __repr__ (self): return "&lt;class X&gt;" class HTMLDecorator(object): def __init__ (self, wrapped): self.__wrapped = wrapped def html (self): sep = cgi.escape (repr (self.__wrapped)) return sep.join (("&lt;H1&gt;", "&lt;/H1&gt;")) inst_x=ClassX() inst_b=True print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_b).html() </code></pre>
0
2008-09-01T06:25:43Z
[ "python", "oop", "inheritance", "object" ]
How can I simply inherit methods from an existing instance?
37,479
<p>below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.</p> <pre><code>import cgi class ClassX(object): pass # ... with own __repr__ class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("&lt;H1&gt;","&lt;/H1&gt;")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() </code></pre> <p>Output:</p> <pre>Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters</pre> <p>Is what I'm trying to do possible? If so, what am I doing wrong?</p>
0
2008-09-01T05:17:35Z
37,544
<p>@John (37479):</p> <p>Very close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way.</p> <pre><code>import cgi from math import sqrt class ClassX(object): def __repr__(self): return "Best Guess" class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True avoid="__class__ __init__ __dict__ __weakref__" class HTMLDecorator(object): def __init__(self,master): self.master = master for attr in dir(self.master): if ( not attr.startswith("__") or attr not in avoid.split() and "attr" not in attr): self.__setattr__(attr, self.master.__getattribute__(attr)) def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("&lt;H1&gt;","&lt;/H1&gt;")) def length(self): return sqrt(sum(self.__iter__())) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) print wrapped_z.length() inst_z[0] += 70 #wrapped_z[0] += 71 wrapped_z.__setitem__(0,wrapped_z.__getitem__(0)+ 71) print wrapped_z.html() print HTMLDecorator(inst_b).html() </code></pre> <p>Output:</p> <pre>&lt;H1&gt;Best Guess&lt;/H1&gt; &lt;H1&gt;&lt;__main__.ClassY object at 0x891df0c&gt;&lt;/H1&gt; 70.0 &lt;H1&gt;[141, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576]&lt;/H1&gt; &lt;H1&gt;True&lt;/H1&gt;</pre>
0
2008-09-01T06:55:13Z
[ "python", "oop", "inheritance", "object" ]
How can I simply inherit methods from an existing instance?
37,479
<p>below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.</p> <pre><code>import cgi class ClassX(object): pass # ... with own __repr__ class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("&lt;H1&gt;","&lt;/H1&gt;")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() </code></pre> <p>Output:</p> <pre>Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters</pre> <p>Is what I'm trying to do possible? If so, what am I doing wrong?</p>
0
2008-09-01T05:17:35Z
37,571
<blockquote> <p>Very close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way.</p> </blockquote> <p>Looks like you're trying to set up some sort of proxy object scheme. That's doable, and there are better solutions than your colleague's, but first consider whether it would be easier to just patch in some extra methods. This won't work for built-in classes like <code>bool</code>, but it will for your user-defined classes:</p> <pre><code>def HTMLDecorator (obj): def html (): sep = cgi.escape (repr (obj)) return sep.join (("&lt;H1&gt;", "&lt;/H1&gt;")) obj.html = html return obj </code></pre> <p>And here is the proxy version:</p> <pre><code>class HTMLDecorator(object): def __init__ (self, wrapped): self.__wrapped = wrapped def html (self): sep = cgi.escape (repr (self.__wrapped)) return sep.join (("&lt;H1&gt;", "&lt;/H1&gt;")) def __getattr__ (self, name): return getattr (self.__wrapped, name) def __setattr__ (self, name, value): if not name.startswith ('_HTMLDecorator__'): setattr (self.__wrapped, name, value) return super (HTMLDecorator, self).__setattr__ (name, value) def __delattr__ (self, name): delattr (self.__wraped, name) </code></pre>
2
2008-09-01T07:33:45Z
[ "python", "oop", "inheritance", "object" ]
How can I simply inherit methods from an existing instance?
37,479
<p>below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.</p> <pre><code>import cgi class ClassX(object): pass # ... with own __repr__ class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("&lt;H1&gt;","&lt;/H1&gt;")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() </code></pre> <p>Output:</p> <pre>Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters</pre> <p>Is what I'm trying to do possible? If so, what am I doing wrong?</p>
0
2008-09-01T05:17:35Z
37,619
<p>Both of John's solutions would work. Another option that allows HTMLDecorator to remain very simple and clean is to monkey-patch it in as a base class. This also works only for user-defined classes, not builtin types:</p> <pre><code>import cgi class ClassX(object): pass # ... with own __repr__ class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() class HTMLDecorator: def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("&lt;H1&gt;","&lt;/H1&gt;")) ClassX.__bases__ += (HTMLDecorator,) ClassY.__bases__ += (HTMLDecorator,) print inst_x.html() print inst_y.html() </code></pre> <p>Be warned, though -- monkey-patching like this comes with a high price in readability and maintainability of your code. When you go back to this code a year later, it can become very difficult to figure out how your ClassX got that html() method, especially if ClassX is defined in some other library.</p>
2
2008-09-01T08:30:41Z
[ "python", "oop", "inheritance", "object" ]
Filter out HTML tags and resolve entities in python
37,486
<p>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.</p>
15
2008-09-01T05:25:01Z
37,496
<p>How about parsing the HTML data and extracting the data with the help of the parser ?</p> <p>I'd try something like the author described in <a href="http://diveintopython.net/html_processing/extracting_data.html" rel="nofollow">chapter 8.3 in the Dive Into Python book</a> </p>
4
2008-09-01T05:35:08Z
[ "python", "html" ]
Filter out HTML tags and resolve entities in python
37,486
<p>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.</p>
15
2008-09-01T05:25:01Z
37,502
<p>While I agree with Lucas that regular expressions are not all that scary, I still think that you should go with a specialized HTML parser. This is because the HTML standard is hairy enough (especially if you want to parse arbitrarily "HTML" pages taken off the Internet) that you would need to write a lot of code to handle the corner cases. It seems that <a href="http://docs.python.org/lib/module-htmllib.html" rel="nofollow">python includes one out of the box</a>. </p> <p>You should also check out the <a href="http://utidylib.berlios.de/" rel="nofollow">python bindings for TidyLib</a> which can clean up broken HTML, making the success rate of any HTML parsing much higher.</p>
6
2008-09-01T05:49:04Z
[ "python", "html" ]
Filter out HTML tags and resolve entities in python
37,486
<p>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.</p>
15
2008-09-01T05:25:01Z
37,504
<p>You might need something more complicated than a regular expression. Web pages often have angle brackets that aren't part of a tag, like this:</p> <pre><code> &lt;div&gt;5 &lt; 7&lt;/div&gt; </code></pre> <p>Stripping the tags with regex will return the string "5 " and treat</p> <pre><code> &lt; 7&lt;/div&gt; </code></pre> <p>as a single tag and strip it out.</p> <p>I suggest looking for already-written code that does this for you. I did a search and found this: <a href="http://zesty.ca/python/scrape.html" rel="nofollow">http://zesty.ca/python/scrape.html</a> It also can resolve HTML entities.</p>
1
2008-09-01T05:50:44Z
[ "python", "html" ]
Filter out HTML tags and resolve entities in python
37,486
<p>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.</p>
15
2008-09-01T05:25:01Z
37,506
<p>Use <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a>! 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.</p>
15
2008-09-01T05:53:39Z
[ "python", "html" ]
Filter out HTML tags and resolve entities in python
37,486
<p>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.</p>
15
2008-09-01T05:25:01Z
37,512
<p>Use <a href="http://codespeak.net/lxml/lxmlhtml.html">lxml</a> which is the best xml/html library for python.</p> <pre><code>import lxml.html t = lxml.html.fromstring("...") t.text_content() </code></pre> <p>And if you just want to sanitize the html look at the lxml.html.clean <a href="http://codespeak.net/lxml/lxmlhtml.html#cleaning-up-html">module</a></p>
38
2008-09-01T06:07:01Z
[ "python", "html" ]
Filter out HTML tags and resolve entities in python
37,486
<p>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.</p>
15
2008-09-01T05:25:01Z
37,604
<p>Regular expressions are not scary, but writing your own regexes to strip HTML is a sure path to madness (and it won't work, either). Follow the path of wisdom, and use one of the many good HTML-parsing libraries.</p> <p>Lucas' example is also broken because "sub" is not a method of a Python string. You'd have to "import re", then call re.sub(pattern, repl, string). But that's neither here nor there, as the correct answer to your question does not involve writing any regexes.</p>
0
2008-09-01T08:15:28Z
[ "python", "html" ]
Filter out HTML tags and resolve entities in python
37,486
<p>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.</p>
15
2008-09-01T05:25:01Z
38,646
<p>Looking at the amount of sense people are demonstrating in other answers here, I'd say that using a regex probably isn't the best idea for your situation. Go for something tried and tested, and treat my previous answer as a demonstration that regexes need not be <em>that</em> scary.</p>
0
2008-09-02T00:11:49Z
[ "python", "html" ]
Filter out HTML tags and resolve entities in python
37,486
<p>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.</p>
15
2008-09-01T05:25:01Z
5,144,206
<p>if you use django you might also use <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#striptags" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/templates/builtins/#striptags</a> ;)</p>
2
2011-02-28T15:51:41Z
[ "python", "html" ]
What's the easiest way to read a FoxPro DBF file from Python?
37,535
<p>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.</p> <p><strong>Update</strong>: Thanks @cnu, I used Yusdi Santoso's <a href="http://www.physics.ox.ac.uk/users/santoso/dbf.py.src"><code>dbf.py</code></a> and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. <code>.fpt</code>, not <code>.FPT</code> which was how the filename came over from Windows.</p>
21
2008-09-01T06:45:40Z
37,553
<p>You can try this <a href="http://code.activestate.com/recipes/362715/" rel="nofollow">recipe on Active State</a>. </p> <p>There is also a <a href="http://code.google.com/p/lino/source/browse/lino/utils/dbfreader.py" rel="nofollow">DBFReader module</a> which you can try.</p> <p>For support for <a href="http://www.physics.ox.ac.uk/users/santoso/dbf.py.src" rel="nofollow">memo fields</a>.</p>
7
2008-09-01T07:02:10Z
[ "python", "foxpro", "dbf", "visual-foxpro" ]
What's the easiest way to read a FoxPro DBF file from Python?
37,535
<p>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.</p> <p><strong>Update</strong>: Thanks @cnu, I used Yusdi Santoso's <a href="http://www.physics.ox.ac.uk/users/santoso/dbf.py.src"><code>dbf.py</code></a> and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. <code>.fpt</code>, not <code>.FPT</code> which was how the filename came over from Windows.</p>
21
2008-09-01T06:45:40Z
37,917
<p>I prefer <a href="http://sourceforge.net/projects/dbfpy/">dbfpy</a>. It supports both reading and writing of <code>.DBF</code> 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.</p>
16
2008-09-01T13:12:53Z
[ "python", "foxpro", "dbf", "visual-foxpro" ]
What's the easiest way to read a FoxPro DBF file from Python?
37,535
<p>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.</p> <p><strong>Update</strong>: Thanks @cnu, I used Yusdi Santoso's <a href="http://www.physics.ox.ac.uk/users/santoso/dbf.py.src"><code>dbf.py</code></a> and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. <code>.fpt</code>, not <code>.FPT</code> which was how the filename came over from Windows.</p>
21
2008-09-01T06:45:40Z
86,420
<p>If you're still checking this, I have a GPL FoxPro-to-PostgreSQL converter at <a href="https://github.com/kstrauser/pgdbf">https://github.com/kstrauser/pgdbf</a> . We use it to routinely copy our tables into PostgreSQL for fast reporting.</p>
9
2008-09-17T18:59:49Z
[ "python", "foxpro", "dbf", "visual-foxpro" ]