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
list
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...
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 jus...
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=...
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 ...
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;&g...
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: defaultsDic...
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...
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 h...
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...
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=...
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 loo...
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-vh...
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-vh...
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...
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-vh...
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 ...
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-vh...
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 ...
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 templ...
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 sta...
-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 templ...
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 templ...
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...
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 position...
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>*a...
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...
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) ...
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> no...
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...
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;...
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...
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 hr...
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 ...
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> wo...
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 ina...
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 ju...
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 gro...
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,...
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__(sel...
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> ...
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 H...
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; T...
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 technique...
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 associativit...
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 valu...
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('dr...
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.or...
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 == o...
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.star...
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.in...
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...
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',...
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 v...
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)) ) </c...
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>...
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> ...
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;&...
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_attr...
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)._...
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__=()))()...
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 c...
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/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 h...
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.l...
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 importan...
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....
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 an...
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 isi...
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 </c...
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 = ...
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/hotwir...
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.o...
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/hotwir...
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++ pars...
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/hotwir...
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 advanta...
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/hotwir...
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/hotwir...
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;...
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/hotwir...
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=...
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/hotwir...
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, lexin...
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...
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 ...
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...
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...
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...
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...
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...
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...
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...
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="nof...
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__ ...
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 (): retu...
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__ ...
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 Cla...
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__ ...
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): ret...
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__ ...
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 Cla...
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__ ...
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 tha...
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__ ...
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(...
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 ...
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; </c...
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/lx...
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 ...
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....
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.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....
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....
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....
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" ]