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
listlengths
1
5
Pythonic way of searching for a substring in a list
1,260,947
<p>I have a list of strings - something like </p> <pre><code>mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text'] </code></pre> <p>I want to find the first occurrence of anything that starts with foobar. If I was grepping then I would do search for foobar*. My current solution looks like this</p> <pre><code>for i in mytext: index = i.find("foobar") if(index!=-1): print i </code></pre> <p>Which works just fine but I am wondering if there is a 'better' (i.e more pythonic) way of doing this?</p> <p>Cheers, Mike</p>
3
2009-08-11T15:03:59Z
1,261,013
<pre><code>results = [ s for s in lst if 'foobar' in s] print(results) </code></pre>
5
2009-08-11T15:15:18Z
[ "string", "list", "python", "substrings" ]
Pythonic way of searching for a substring in a list
1,260,947
<p>I have a list of strings - something like </p> <pre><code>mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text'] </code></pre> <p>I want to find the first occurrence of anything that starts with foobar. If I was grepping then I would do search for foobar*. My current solution looks like this</p> <pre><code>for i in mytext: index = i.find("foobar") if(index!=-1): print i </code></pre> <p>Which works just fine but I am wondering if there is a 'better' (i.e more pythonic) way of doing this?</p> <p>Cheers, Mike</p>
3
2009-08-11T15:03:59Z
1,261,016
<p>You can also use a list comprehension : </p> <pre><code>matches = [s for s in mytext if 'foobar' in s] </code></pre> <p>(and if you were really looking for strings <em>starting</em> with 'foobar' as THC4k noticed, consider the following : </p> <pre><code>matches = [s for s in mytext if s.startswith('foobar')] </code></pre>
15
2009-08-11T15:15:33Z
[ "string", "list", "python", "substrings" ]
Pythonic way of searching for a substring in a list
1,260,947
<p>I have a list of strings - something like </p> <pre><code>mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text'] </code></pre> <p>I want to find the first occurrence of anything that starts with foobar. If I was grepping then I would do search for foobar*. My current solution looks like this</p> <pre><code>for i in mytext: index = i.find("foobar") if(index!=-1): print i </code></pre> <p>Which works just fine but I am wondering if there is a 'better' (i.e more pythonic) way of doing this?</p> <p>Cheers, Mike</p>
3
2009-08-11T15:03:59Z
1,261,018
<p>in case you really looking for strings that <strong>start</strong> with foobar ( not with foobar <strong>in</strong> them):</p> <pre><code>for s in mylist: if s.startswith( 'foobar' ): print s </code></pre> <p>or </p> <pre><code>found = [ s for s in mylist if s.startswith('foobar') ] </code></pre>
4
2009-08-11T15:15:51Z
[ "string", "list", "python", "substrings" ]
Pythonic way of searching for a substring in a list
1,260,947
<p>I have a list of strings - something like </p> <pre><code>mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text'] </code></pre> <p>I want to find the first occurrence of anything that starts with foobar. If I was grepping then I would do search for foobar*. My current solution looks like this</p> <pre><code>for i in mytext: index = i.find("foobar") if(index!=-1): print i </code></pre> <p>Which works just fine but I am wondering if there is a 'better' (i.e more pythonic) way of doing this?</p> <p>Cheers, Mike</p>
3
2009-08-11T15:03:59Z
1,261,192
<p>If you really want the FIRST occurrence of a string that STARTS WITH foobar (which is what your words say, though very different from your code, all answers provided, your mention of grep -- how contradictory can you get?-), try:</p> <pre><code>found = next((s for s in mylist if s.startswith('foobar')), '') </code></pre> <p>this gives an empty string as the <code>found</code> result if no item of mylist meets the condition. You could also use itertools, etc, in lieu of the simple genexp, but the key trick is this way of using the <code>next</code> builtin with a default (Python 2.6 and better only).</p>
9
2009-08-11T15:39:34Z
[ "string", "list", "python", "substrings" ]
example for using streamhtmlparser
1,261,264
<p>Can anyone give me an example on how to use <a href="http://code.google.com/p/streamhtmlparser" rel="nofollow">http://code.google.com/p/streamhtmlparser</a> to parse out all the <code>A</code> tag href's from an html document? (either C++ code or python code is ok, but I would prefer an example using the python bindings)</p> <p>I can see how it works in the python tests, but they expect special tokens already in the html at which points it checks state values. I don't see how to get the proper callbacks during state changes when feeding the parser plain html.</p> <p>I can get some of the information I am looking for with the following code, but I need to feed it blocks of html not just characters at a time, and i need to know when it's finished with a tag,attribute, etc not just if it's in a tag, attribute, or value.</p> <pre><code>import py_streamhtmlparser parser = py_streamhtmlparser.HtmlParser() html = """&lt;html&gt;&lt;body&gt;&lt;a href='http://google.com'&gt;link&lt;/a&gt;&lt;/body&gt;&lt;/html&gt;""" for index, character in enumerate(html): parser.Parse(character) print index, character, parser.Tag(), parser.Attribute(), parser.Value(), parser.ValueIndex() </code></pre> <p>you can see a sample run of this code <a href="http://pastebin.com/fdc63fda" rel="nofollow">here</a></p>
0
2009-08-11T15:50:17Z
1,278,998
<pre><code>import py_streamhtmlparser parser = py_streamhtmlparser.HtmlParser() html = """&lt;html&gt;&lt;body&gt;&lt;a href='http://google.com' id=100&gt; link&lt;/a&gt;&lt;p&gt;&lt;a href=heise.de/&gt;&lt;/body&gt;&lt;/html&gt;""" cur_attr = cur_value = None for index, character in enumerate(html): parser.Parse(character) if parser.State() == py_streamhtmlparser.HTML_STATE_VALUE: # we are in an attribute value. Record what we got so far cur_tag = parser.Tag() cur_attr = parser.Attribute() cur_value = parser.Value() continue if cur_value: # we are not in the value anymore, but have seen one just before print "%r %r %r" % (cur_tag, cur_attr, cur_value) cur_value = None </code></pre> <p>gives</p> <pre><code>'a' 'href' 'http://google.com' 'a' 'id' '100' 'a' 'href' 'heise.de/' </code></pre> <p>If you only want the href attributes, check for cur_attr at the point of the print as well.</p> <p><strong>Edit</strong>: The Python bindings currently don't support any kind of event callbacks. So the only output available is the state at the end of processing the respective input. To change that, htmlparser.c:exit_attr (etc.) could be augmented with a callback function. However, this is really not the purpose of streamhtmlparser - it is meant as a templating engine, where you have markers in the source, and you process the input character by character.</p>
1
2009-08-14T17:05:35Z
[ "c++", "python", "html", "parsing" ]
substituting in a file
1,261,578
<p>I use python 2.5, i like to replace certain variables in a txt file and write the complete data into new file.</p> <p>i wrote a program to do the above,</p> <pre><code>from scipy import * import numpy from numpy import asarray from string import Template def Dat(Par): Par = numpy.asarray(Par) Par[0] = a1 Par[1] = a2 Par[2] = a3 Par[3] = a4 sTemplate=Template(open('/home/av/W/python/data.txt', 'r').read()).safe_substitute(Par) open('/home/av/W/python/data_new.txt' ,'w').write(sTemplate) Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)] Dat(Init) </code></pre> <p>when i executed the above *i obtained the error </p> <pre><code>'TypeError: 'function' object is unsubscriptable' </code></pre> <p>'data.txt' is a text file, i have placed $a1, $a2, $a3, $a4, i need to replace $a1 $a2 $a3 $a4 by 10.0 200.0 500.0 10.0</p> <p>My constraints are i need to pass the values only by array like Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)] </p> <p>please help me.</p> <p>is this error due to python 2.5 version? or any mistakes in program</p>
0
2009-08-11T16:45:20Z
1,261,595
<p>The error is here:</p> <pre><code>Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)] </code></pre> <p>which was probably meant to be</p> <pre><code>Init = numpy.asarray ([10.0, 200.0, 500.0, 10.0]) </code></pre> <p>(note the swapped braces/parens). Since python found a "<code>[</code>" after "<code>asarray</code>" (which is a function), it throws an error, because you cannot subscribe (i.e. do something like <code>x[17]</code>) a function.</p>
3
2009-08-11T16:48:24Z
[ "python" ]
substituting in a file
1,261,578
<p>I use python 2.5, i like to replace certain variables in a txt file and write the complete data into new file.</p> <p>i wrote a program to do the above,</p> <pre><code>from scipy import * import numpy from numpy import asarray from string import Template def Dat(Par): Par = numpy.asarray(Par) Par[0] = a1 Par[1] = a2 Par[2] = a3 Par[3] = a4 sTemplate=Template(open('/home/av/W/python/data.txt', 'r').read()).safe_substitute(Par) open('/home/av/W/python/data_new.txt' ,'w').write(sTemplate) Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)] Dat(Init) </code></pre> <p>when i executed the above *i obtained the error </p> <pre><code>'TypeError: 'function' object is unsubscriptable' </code></pre> <p>'data.txt' is a text file, i have placed $a1, $a2, $a3, $a4, i need to replace $a1 $a2 $a3 $a4 by 10.0 200.0 500.0 10.0</p> <p>My constraints are i need to pass the values only by array like Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)] </p> <p>please help me.</p> <p>is this error due to python 2.5 version? or any mistakes in program</p>
0
2009-08-11T16:45:20Z
1,261,609
<pre><code>Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)] </code></pre> <p>This is your problem. numpy.asarray is a function, and you are trying to use it as a list (hence the exception). Flip the brackets and parentheses and try that. </p>
0
2009-08-11T16:49:48Z
[ "python" ]
substituting in a file
1,261,578
<p>I use python 2.5, i like to replace certain variables in a txt file and write the complete data into new file.</p> <p>i wrote a program to do the above,</p> <pre><code>from scipy import * import numpy from numpy import asarray from string import Template def Dat(Par): Par = numpy.asarray(Par) Par[0] = a1 Par[1] = a2 Par[2] = a3 Par[3] = a4 sTemplate=Template(open('/home/av/W/python/data.txt', 'r').read()).safe_substitute(Par) open('/home/av/W/python/data_new.txt' ,'w').write(sTemplate) Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)] Dat(Init) </code></pre> <p>when i executed the above *i obtained the error </p> <pre><code>'TypeError: 'function' object is unsubscriptable' </code></pre> <p>'data.txt' is a text file, i have placed $a1, $a2, $a3, $a4, i need to replace $a1 $a2 $a3 $a4 by 10.0 200.0 500.0 10.0</p> <p>My constraints are i need to pass the values only by array like Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)] </p> <p>please help me.</p> <p>is this error due to python 2.5 version? or any mistakes in program</p>
0
2009-08-11T16:45:20Z
1,261,618
<p>The line</p> <pre><code>Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)] </code></pre> <p>should almost certainly be</p> <pre><code>Init = numpy.asarray([(10.0, 200.0, 500.0, 10.0)]) </code></pre> <p>I believe that is what is causing your "'function' object is unsubscriptable" error</p>
0
2009-08-11T16:51:22Z
[ "python" ]
substituting in a file
1,261,578
<p>I use python 2.5, i like to replace certain variables in a txt file and write the complete data into new file.</p> <p>i wrote a program to do the above,</p> <pre><code>from scipy import * import numpy from numpy import asarray from string import Template def Dat(Par): Par = numpy.asarray(Par) Par[0] = a1 Par[1] = a2 Par[2] = a3 Par[3] = a4 sTemplate=Template(open('/home/av/W/python/data.txt', 'r').read()).safe_substitute(Par) open('/home/av/W/python/data_new.txt' ,'w').write(sTemplate) Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)] Dat(Init) </code></pre> <p>when i executed the above *i obtained the error </p> <pre><code>'TypeError: 'function' object is unsubscriptable' </code></pre> <p>'data.txt' is a text file, i have placed $a1, $a2, $a3, $a4, i need to replace $a1 $a2 $a3 $a4 by 10.0 200.0 500.0 10.0</p> <p>My constraints are i need to pass the values only by array like Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)] </p> <p>please help me.</p> <p>is this error due to python 2.5 version? or any mistakes in program</p>
0
2009-08-11T16:45:20Z
1,266,922
<p>from scipy import *</p> <p>import numpy </p> <p>from numpy import asarray</p> <p>from string import Template</p> <p>def Dat(Par):</p> <p>Par = numpy.asarray(Par)</p> <p>ParDict =dict(a1 = Par[0], a2 = Par[1],a3 = Par[2],a4 = Par[3])</p> <p>sTemplate=Template(open('/home/av/W/python/data.txt', 'r').read()).safe_substitute(ParDict)</p> <p>open('/home/av/W/python/data_new.txt' ,'w').write(sTemplate)</p> <p>Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)]</p> <p>Dat(Init)</p> <p>In this way its works fine.</p>
0
2009-08-12T15:27:44Z
[ "python" ]
Eclipse+Pydev: "cleanup" functions aren't called when pressing "stop""?
1,261,597
<p>Trying to run this file in eclipse</p> <pre><code>class Try: def __init__(self): pass def __del__(self): print 1 a=Try() raw_input('waiting to finish') </code></pre> <p>and pressing the stop button without letting the program finish doesn't print "1", i.e the del method is never called. If i try to run the script from the shell and do ctrl-c\sys.exit "1" does get printed i.e del is called. Same thing if I try to use wait():</p> <pre><code>class A: def __enter__(self): return None def __exit__(self, type, value, traceback): print 3 with A(): print 1 raw_input('Waiting') print 2 </code></pre> <p>If i press "stop" when prompted, "3" isn't printed </p> <p>Why is that? Is there a way around it?</p> <p>Thanks, Noam</p>
2
2009-08-11T16:48:41Z
1,261,676
<p>Python docs:</p> <blockquote> <pre><code>__del__(self) </code></pre> <p>Called when the instance is about to be destroyed. This is also called a destructor. If a base class has a <code>__del__()</code> method, the derived class's <code>__del__()</code> method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance. Note that it is possible (though not recommended!) for the <code>__del__()</code> method to postpone destruction of the instance by creating a new reference to it. It may then be called at a later time when this new reference is deleted. <strong>It is not guaranteed that <code>__del__()</code> methods are called for objects that still exist when the interpreter exits.</strong></p> </blockquote> <p>If you want to guarantee that a method is called use the <a href="http://www.python.org/dev/peps/pep-0343/" rel="nofollow">with-statement</a></p>
4
2009-08-11T16:59:28Z
[ "python", "eclipse", "pydev", "del" ]
Eclipse+Pydev: "cleanup" functions aren't called when pressing "stop""?
1,261,597
<p>Trying to run this file in eclipse</p> <pre><code>class Try: def __init__(self): pass def __del__(self): print 1 a=Try() raw_input('waiting to finish') </code></pre> <p>and pressing the stop button without letting the program finish doesn't print "1", i.e the del method is never called. If i try to run the script from the shell and do ctrl-c\sys.exit "1" does get printed i.e del is called. Same thing if I try to use wait():</p> <pre><code>class A: def __enter__(self): return None def __exit__(self, type, value, traceback): print 3 with A(): print 1 raw_input('Waiting') print 2 </code></pre> <p>If i press "stop" when prompted, "3" isn't printed </p> <p>Why is that? Is there a way around it?</p> <p>Thanks, Noam</p>
2
2009-08-11T16:48:41Z
1,261,906
<p>Pressing stop in Eclipse outright kills the interpreter (though it actually fails fairly often). Like using <code>kill</code>/<code>taskkill</code>, the process is unaware of it's demise.</p> <p><a href="http://en.wikipedia.org/wiki/Control-C" rel="nofollow">Ctrl+C</a> snippet from Wikipedia...</p> <blockquote> <p>Control-C as an abort command was popularized by UNIX and adopted in other systems. In POSIX systems, the sequence causes the active program to receive a SIGINT signal. If the program does not specify how to handle this condition, it is terminated. Typically a program which does handle a SIGINT will still terminate itself, or at least terminate the task running inside it.</p> </blockquote> <p><code>Ctrl+C</code> is a control signal to interrupt the program, but as you may have noticed in the middle of that paragraph, programs can specify how to handle the signal. In Python, Ctrl+C <a href="http://effbot.org/zone/stupid-exceptions-keyboardinterrupt.htm" rel="nofollow">throws a KeyboardInterrupt exception</a> which is normally caught and then Python exits cleanly. Even if you're killing the interpreter with <code>Ctrl+C</code> it may handle it so that it cleans the environment before exiting.</p> <p>I included the following because you asked "Is there a way around it?"</p> <p>If you are wanting to stop on <code>raw_input(...)</code> calls, you could use <code>Ctrl+Z</code> to send EOF. I looked around, and there seems to be no way to send <code>Ctrl+C</code>/<code>0x03</code> in Eclipse, unfortunately.</p>
2
2009-08-11T17:42:22Z
[ "python", "eclipse", "pydev", "del" ]
cannot override sys.excepthook
1,261,668
<p>I try to customize behavior of <code>sys.excepthook</code> as described by <a href="http://mail.python.org/pipermail/python-list/2001-April/079168.html" rel="nofollow">the recipe</a>. </p> <p>in ipython:</p> <pre><code>:import pdb, sys, traceback :def info(type, value, tb): : traceback.print_exception(type, value, tb) : pdb.pm() :sys.excepthook = info :-- &gt;&gt;&gt; x[10] = 5 ------------------------------------------------- Traceback (most recent call last): File "&lt;ipython console&gt;", line 1, in &lt;module&gt; NameError: name 'x' is not defined &gt;&gt;&gt; </code></pre> <p><code>pdb.pm()</code> is not being called. It seems that <code>sys.excepthook = info</code> doesn't work in my python 2.5 installation. </p>
4
2009-08-11T16:58:23Z
1,261,863
<p>See <a href="http://stackoverflow.com/questions/1237379/how-do-i-set-sys-excepthook-to-invoke-pdb-globally-in-python">this SO question</a> and make sure there isn't something in your <code>sitecustomize.py</code> that prevents debugging in interactive mode.</p>
0
2009-08-11T17:33:45Z
[ "python", "debugging", "ipython", "pdb" ]
cannot override sys.excepthook
1,261,668
<p>I try to customize behavior of <code>sys.excepthook</code> as described by <a href="http://mail.python.org/pipermail/python-list/2001-April/079168.html" rel="nofollow">the recipe</a>. </p> <p>in ipython:</p> <pre><code>:import pdb, sys, traceback :def info(type, value, tb): : traceback.print_exception(type, value, tb) : pdb.pm() :sys.excepthook = info :-- &gt;&gt;&gt; x[10] = 5 ------------------------------------------------- Traceback (most recent call last): File "&lt;ipython console&gt;", line 1, in &lt;module&gt; NameError: name 'x' is not defined &gt;&gt;&gt; </code></pre> <p><code>pdb.pm()</code> is not being called. It seems that <code>sys.excepthook = info</code> doesn't work in my python 2.5 installation. </p>
4
2009-08-11T16:58:23Z
1,262,091
<p>ipython, which you're using instead of the normal Python interactive shell, traps all exceptions itself and does NOT use sys.excepthook. Run it as <code>ipython -pdb</code> instead of just <code>ipython</code>, and it will automatically invoke pdb upon uncaught exceptions, just as you are trying to do with your excepthook.</p>
7
2009-08-11T18:18:53Z
[ "python", "debugging", "ipython", "pdb" ]
cannot override sys.excepthook
1,261,668
<p>I try to customize behavior of <code>sys.excepthook</code> as described by <a href="http://mail.python.org/pipermail/python-list/2001-April/079168.html" rel="nofollow">the recipe</a>. </p> <p>in ipython:</p> <pre><code>:import pdb, sys, traceback :def info(type, value, tb): : traceback.print_exception(type, value, tb) : pdb.pm() :sys.excepthook = info :-- &gt;&gt;&gt; x[10] = 5 ------------------------------------------------- Traceback (most recent call last): File "&lt;ipython console&gt;", line 1, in &lt;module&gt; NameError: name 'x' is not defined &gt;&gt;&gt; </code></pre> <p><code>pdb.pm()</code> is not being called. It seems that <code>sys.excepthook = info</code> doesn't work in my python 2.5 installation. </p>
4
2009-08-11T16:58:23Z
28,758,396
<p>Five years after you wrote this, IPython still works this way, so I guess a solution might be useful to people googling this.</p> <p>IPython replaces <code>sys.excepthook</code> every time you execute a line of code, so your overriding of sys.excepthook has no effect. Furthermore, IPython doesn't even call <code>sys.excepthook</code>, it catches all exceptions and handles them itself before things get that far.</p> <p>To override the exception handler whilst IPython is running, you can monkeypatch over their shell's <code>showtraceback</code> method. For example, here's how I override to give what looks like an ordinary Python traceback (because I don't like how verbose IPython's are):</p> <pre class="lang-py prettyprint-override"><code>def showtraceback(self): traceback_lines = traceback.format_exception(*sys.exc_info()) del traceback_lines[1] message = ''.join(traceback_lines) sys.stderr.write(message) import sys import traceback import IPython IPython.core.interactiveshell.InteractiveShell.showtraceback = showtraceback </code></pre> <p>This works in both the normal terminal console and the Qt console.</p>
3
2015-02-27T05:49:38Z
[ "python", "debugging", "ipython", "pdb" ]
python2.5 says platform dependent libraries not found
1,261,848
<pre><code>Could not find platform dependent libraries &lt;exec_prefix&gt; Consider setting $PYTHONHOME to &lt;prefix&gt;[:&lt;exec_prefix&gt;] Python 2.5.2 (r252:60911, Aug 8 2009, 17:18:03) [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import re &gt;&gt;&gt; import operator Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named operator </code></pre>
1
2009-08-11T17:29:50Z
1,262,707
<p>Module <code>operator</code> should come from file <code>operator.so</code>, presumably in <code>/usr/local/lib/lib-dynload</code> in your case since that seems to be where you've installed things. So what .so files are in that directory?</p> <p>Assuming operator.so is indeed missing (i.e., assuming it's not some trivial case of wrong permissions on some directory or file) the best way to "get it back" is no doubt, as a comment already suggested, to reinstall Python 2.5 (assuming you need that release e.g. to work with app engine) from either an official Python package at python.org, or an official CentOS 5.3 one (if one exists -- I believe CentOS 5.3 uses Python 2.4 as the official /usr/bin/python but there may be RPMs to place 2.5 somewhere else).</p>
1
2009-08-11T20:24:34Z
[ "python", "configuration" ]
python2.5 says platform dependent libraries not found
1,261,848
<pre><code>Could not find platform dependent libraries &lt;exec_prefix&gt; Consider setting $PYTHONHOME to &lt;prefix&gt;[:&lt;exec_prefix&gt;] Python 2.5.2 (r252:60911, Aug 8 2009, 17:18:03) [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import re &gt;&gt;&gt; import operator Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named operator </code></pre>
1
2009-08-11T17:29:50Z
1,263,302
<p>Reiterating what I said earlier in a comment: re is a pure python module. You should see it in <code>/usr/local/lib/python25{,.zip}</code>. operator is a C module; it should be in <code>/usr/local/lib/lib-dynload</code>. If not, your installation is faulty and, yes, you should reinstall.</p>
0
2009-08-11T22:21:29Z
[ "python", "configuration" ]
python2.5 says platform dependent libraries not found
1,261,848
<pre><code>Could not find platform dependent libraries &lt;exec_prefix&gt; Consider setting $PYTHONHOME to &lt;prefix&gt;[:&lt;exec_prefix&gt;] Python 2.5.2 (r252:60911, Aug 8 2009, 17:18:03) [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import re &gt;&gt;&gt; import operator Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named operator </code></pre>
1
2009-08-11T17:29:50Z
7,209,923
<p>I renamed the /usr/local/bin/python file and the error went away. I suspect this was an old version of python because I have a file python2.7 in the same directory.</p>
1
2011-08-26T19:59:10Z
[ "python", "configuration" ]
Python nonlocal statement
1,261,875
<p>What does the Python <code>nonlocal</code> statement do (in Python 3.0 and later)? </p> <p>There's no documentation on the official Python website and <code>help("nonlocal")</code> does not work, either.</p>
99
2009-08-11T17:36:24Z
1,261,892
<p>In short, it lets you assign values to a variable in an outer (but non-global) scope. See <a href="http://www.python.org/dev/peps/pep-3104/">PEP 3104</a> for all the gory details. </p>
46
2009-08-11T17:40:52Z
[ "python", "closures", "global", "python-nonlocal" ]
Python nonlocal statement
1,261,875
<p>What does the Python <code>nonlocal</code> statement do (in Python 3.0 and later)? </p> <p>There's no documentation on the official Python website and <code>help("nonlocal")</code> does not work, either.</p>
99
2009-08-11T17:36:24Z
1,261,952
<p>A google search for "python nonlocal" turned up the Proposal, <a href="http://www.python.org/dev/peps/pep-3104/">PEP 3104</a>, which fully describes the syntax and reasoning behind the statement. in short, it works in exactly the same way as the <code>global</code> statement, except that it is used to refer to variables that are neither global nor local to the function. </p> <p>Here's a brief example of what you can do with this. The counter generator can be rewritten to use this so that it looks more like the idioms of languages with closures.</p> <pre><code>def make_counter(): count = 0 def counter(): nonlocal count count += 1 return count return counter </code></pre> <p>Obviously, you could write this as a generator, like:</p> <pre><code>def counter_generator(): count = 0 while True: count += 1 yield count </code></pre> <p><em>But</em> while this is perfectly idiomatic python, it seems that the first version would be a bit more obvious for beginners. Properly using generators, by calling the returned function, is a common point of confusion. The first version explicitly returns a function.</p>
21
2009-08-11T17:50:45Z
[ "python", "closures", "global", "python-nonlocal" ]
Python nonlocal statement
1,261,875
<p>What does the Python <code>nonlocal</code> statement do (in Python 3.0 and later)? </p> <p>There's no documentation on the official Python website and <code>help("nonlocal")</code> does not work, either.</p>
99
2009-08-11T17:36:24Z
1,261,961
<p>Compare this, without using <code>nonlocal</code>:</p> <pre><code>x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 1 # global: 0 </code></pre> <p>To this, using <strong><code>nonlocal</code></strong>, where <code>inner()</code>'s <code>x</code> is now also <code>outer()</code>'s <code>x</code>:</p> <pre><code>x = 0 def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 2 # global: 0 </code></pre> <blockquote> <p>If we were to use <strong><code>global</code></strong>, it would bind <code>x</code> to the properly "global" value:</p> <pre><code>x = 0 def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 1 # global: 2 </code></pre> </blockquote>
151
2009-08-11T17:53:30Z
[ "python", "closures", "global", "python-nonlocal" ]
Python nonlocal statement
1,261,875
<p>What does the Python <code>nonlocal</code> statement do (in Python 3.0 and later)? </p> <p>There's no documentation on the official Python website and <code>help("nonlocal")</code> does not work, either.</p>
99
2009-08-11T17:36:24Z
4,359,041
<p>@ooboo:</p> <p>It takes the one "closest" to the point of reference in the source code. This is called "Lexical Scoping" and is standard for >40 years now.</p> <p>Python's class members are really in a dictionary called <code>__dict__</code> and will never be reached by lexical scoping.</p> <p>If you don't specify <code>nonlocal</code> but do <code>x = 7</code>, it will create a new local variable "x". If you do specify <code>nonlocal</code>, it will find the "closest" "x" and assign to that. If you specify <code>nonlocal</code> and there is no "x", it will give you an error message.</p> <p>The keyword <code>global</code> has always seemed strange to me since it will happily ignore all the other "x" except for the outermost one. Weird.</p>
6
2010-12-05T13:30:02Z
[ "python", "closures", "global", "python-nonlocal" ]
Python nonlocal statement
1,261,875
<p>What does the Python <code>nonlocal</code> statement do (in Python 3.0 and later)? </p> <p>There's no documentation on the official Python website and <code>help("nonlocal")</code> does not work, either.</p>
99
2009-08-11T17:36:24Z
6,939,750
<p>My personal understanding of the "nonlocal" statement (and do excuse me as I am new to Python and Programming in general) is that the "nonlocal" is a way to use the Global functionality within iterated functions rather than the body of the code itself. A Global statement between functions if you will.</p>
1
2011-08-04T10:25:00Z
[ "python", "closures", "global", "python-nonlocal" ]
Python nonlocal statement
1,261,875
<p>What does the Python <code>nonlocal</code> statement do (in Python 3.0 and later)? </p> <p>There's no documentation on the official Python website and <code>help("nonlocal")</code> does not work, either.</p>
99
2009-08-11T17:36:24Z
6,940,232
<blockquote> <p>help('nonlocal') The <code>nonlocal</code> statement</p> <hr> <pre><code> nonlocal_stmt ::= "nonlocal" identifier ("," identifier)* </code></pre> <p>The <code>nonlocal</code> statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.</p> <p>Names listed in a <code>nonlocal</code> statement, unlike to those listed in a <code>global</code> statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).</p> <p>Names listed in a <code>nonlocal</code> statement must not collide with pre- existing bindings in the local scope.</p> <p>See also:</p> <p><strong>PEP 3104</strong> - Access to Names in Outer Scopes<br> The specification for the <code>nonlocal</code> statement.</p> <p>Related help topics: global, NAMESPACES</p> </blockquote> <p>Source: <a href="https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement" rel="nofollow">Python Language Reference</a></p>
6
2011-08-04T11:01:39Z
[ "python", "closures", "global", "python-nonlocal" ]
Python nonlocal statement
1,261,875
<p>What does the Python <code>nonlocal</code> statement do (in Python 3.0 and later)? </p> <p>There's no documentation on the official Python website and <code>help("nonlocal")</code> does not work, either.</p>
99
2009-08-11T17:36:24Z
30,077,816
<pre><code>a = 0 #1. global variable with respect to every function in program def f(): a = 0 #2. nonlocal with respect to function g def g(): nonlocal a a=a+1 print("The value of 'a' using nonlocal is ", a) def h(): global a #3. using global variable a=a+5 print("The value of a using global is ", a) def i(): a = 0 #4. variable separated from all others print("The value of 'a' inside a function is ", a) g() h() i() print("The value of 'a' global before any function", a) f() print("The value of 'a' global after using function f ", a) </code></pre>
0
2015-05-06T13:11:20Z
[ "python", "closures", "global", "python-nonlocal" ]
using setuptools with post-install and python dependencies
1,262,052
<p>This is somewhat related to <a href="http://stackoverflow.com/questions/250038/how-can-i-add-post-install-scripts-to-easyinstall-setuptools-distutils">this question</a>. Let's say I have a package that I want to deploy via rpm because I need to do some file copying on post-install and I have some non-python dependencies I want to declare. But let's also say I have some python dependencies that are easily available in PyPI. It seems like if I just package as an egg, an unzip followed by <code>python setup.py install</code> will automatically take care of my python dependencies, at the expense of losing any post-install functionality and non-python dependencies.</p> <p>Is there any recommended way of doing this? I suppose I could specify this in a pre-install script, but then I'm getting into information duplication and not really using setuptools for much of anything.</p> <p>(My current setup involves passing <code>install_requires = ['dependency_name']</code> to <code>setup</code>, which works for <code>python setup.py bdist_egg</code> and <code>unzip my_package.egg; python my_package/setup.py install</code>, but not for <code>python setup.py bdist_rpm --post-install post-install.sh</code> and <code>rpm --install my_package.rpm</code>.)</p>
4
2009-08-11T18:11:11Z
1,262,272
<p>I think it would be best if your python dependencies were available as RPMs also, and declared as dependencies in the RPM. If they aren't available elsewhere, create them yourself, and put them in your yum repository.</p> <p>Running PyPI installations as a side effect of RPM installation is evil, as it won't support proper uninstallation (i.e. uninstalling your RPM will remove your package, but leave the dependencies behind, with no proper removal procedure).</p>
6
2009-08-11T18:55:22Z
[ "python", "packaging", "setuptools", "rpm" ]
How to find the compiled extensions modules in numpy
1,262,783
<p>I am compiling numpy myself on Windows. The build and install runs fine; but how do I list the currently enabled modules .. and modules that are not made available (due to maybe compilation failure or missing libraries)?</p>
1
2009-08-11T20:39:00Z
1,336,170
<p>numpy does not have optional components. Either the build is successful, or it fails. You can run the test suite to see if the build works.</p> <pre><code>$ python -c "import numpy;numpy.test()" Running unit tests for numpy NumPy version 1.4.0.dev NumPy is installed in /Users/rkern/svn/numpy/numpy Python version 2.5.4 (r254:67916, Apr 23 2009, 14:49:51) [GCC 4.0.1 (Apple Inc. build 5465)] nose version 0.11.0 ..................... ... etc. </code></pre>
2
2009-08-26T16:58:26Z
[ "python", "windows", "numpy" ]
Why are all the tk examples in a Python distribution written in TCL?
1,263,187
<p>Now don't get me wrong, I'm not exactly a Python fan, but when you see a Tk directory inside of the python directory you kinda expect... Well Python. And yeah, I get that Tk came from TCL, but if I had to write a TCL to use Tk, I'd forget TK existed and use a completely different tool box. (The popularity of this combination completely eludes me.) </p> <p>Expecting to see a relatively readable language like Python, and finding TCL is like walking in on your grandma naked. It's just visually painful.</p> <p>I haven't drank the cool-aid when it comes to Python, but I use for simple task that I don't want to bother with C or C++ on and maybe if I want some for quick and dirty text processing. It just seems like a cruel joke to put TCL examples in the Python distribution.</p> <p>Is there an equivalent package that includes those examples written in Python?</p> <p>Edit: I guess this also kinda begs the question is Tk the best option for GUI dev in Python?</p>
3
2009-08-11T21:57:03Z
1,263,234
<p>Perhaps you should start by looking at the Python Tkinter documentation <a href="http://docs.python.org/library/tkinter.html" rel="nofollow">here</a> and the Tkinter wiki <a href="http://wiki.python.org/moin/TkInter" rel="nofollow">here</a>.</p> <p>And where are you seeing Tcl examples? Are you looking at a Tcl library supplied with Python perhaps?</p>
2
2009-08-11T22:05:15Z
[ "python", "tcl", "tk" ]
Why are all the tk examples in a Python distribution written in TCL?
1,263,187
<p>Now don't get me wrong, I'm not exactly a Python fan, but when you see a Tk directory inside of the python directory you kinda expect... Well Python. And yeah, I get that Tk came from TCL, but if I had to write a TCL to use Tk, I'd forget TK existed and use a completely different tool box. (The popularity of this combination completely eludes me.) </p> <p>Expecting to see a relatively readable language like Python, and finding TCL is like walking in on your grandma naked. It's just visually painful.</p> <p>I haven't drank the cool-aid when it comes to Python, but I use for simple task that I don't want to bother with C or C++ on and maybe if I want some for quick and dirty text processing. It just seems like a cruel joke to put TCL examples in the Python distribution.</p> <p>Is there an equivalent package that includes those examples written in Python?</p> <p>Edit: I guess this also kinda begs the question is Tk the best option for GUI dev in Python?</p>
3
2009-08-11T21:57:03Z
1,263,728
<p>There are no Tcl examples in Python's official distribution; whatever distro you're using must have bundled them on its own volition.</p> <p>IMHO, Tk's only real advantage by now is the convenience that comes from having it bundled with Python. I was criticized for covering it in "Python in a Nutshell", but I stand by that decision because it <em>is</em> still "the" bundled toolkit, after all. But if you want something better and don't mind taking a tiny amount of inconvenience to procure it (and possibly to bundle it with apps you distribute), there are other excellent choices.</p> <p><a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">PyQt</a> (if you can stand the GPL license or pay for the commercial one) and <a href="http://www.wxpython.org/" rel="nofollow">wxPython</a> are IMHO currently superior offerings for cross-platform GUI apps (though you'll have to work to bundle them with py2exe or PyInstaller if you want to distribute a stand-alone app) and other packages are excellent if you don't care about cross-platform distribution or have specialized needs (e.g. <a href="http://pyui.sourceforge.net/" rel="nofollow">pyui</a> -- while now a general-purpose UI toolkit -- for simple UIs for games if you're using PyGame or PyOpenGL anyway).</p>
3
2009-08-12T00:49:04Z
[ "python", "tcl", "tk" ]
Why are all the tk examples in a Python distribution written in TCL?
1,263,187
<p>Now don't get me wrong, I'm not exactly a Python fan, but when you see a Tk directory inside of the python directory you kinda expect... Well Python. And yeah, I get that Tk came from TCL, but if I had to write a TCL to use Tk, I'd forget TK existed and use a completely different tool box. (The popularity of this combination completely eludes me.) </p> <p>Expecting to see a relatively readable language like Python, and finding TCL is like walking in on your grandma naked. It's just visually painful.</p> <p>I haven't drank the cool-aid when it comes to Python, but I use for simple task that I don't want to bother with C or C++ on and maybe if I want some for quick and dirty text processing. It just seems like a cruel joke to put TCL examples in the Python distribution.</p> <p>Is there an equivalent package that includes those examples written in Python?</p> <p>Edit: I guess this also kinda begs the question is Tk the best option for GUI dev in Python?</p>
3
2009-08-11T21:57:03Z
34,541,040
<p>TCL / TK is a simple language to understand with which the applications are made very simple, very quickly occupying very few resources and hardware platform to be run on all platforms.</p> <p>In TCL / TK exist there is also <a href="http://www.tcl.tk/starkits/" rel="nofollow">starkits</a> or <a href="http://freewrap.sourceforge.net" rel="nofollow">freewrap</a> allowing wrap libraries, code and other files into a single package easier to carry around, to other platforms and run and install, without being necessary to bring all the libraries brings language.</p> <p>While the evaluator of TCL / TK requires 3MB, the python requires much more, and uses many more that unused libraries.</p> <p>When these applications grow, it is logical to migrate first to python and share the GUI using Tkinter, then they can move on to other GUI as QT or Wxwidgets, to work faster.</p> <p>Who want to program with Tkinter, you must know how it works TCL and TK GUI with which are made tkinter.</p> <p>Today is not here another library module GUI that there be a versatile as tkinter into a single file that allows cross-platform applications remain to be small and modular for all basic python project.</p> <p>While tkinter is 2 MB, wxwidget are 80 MB and if you take a calculator, a notepad or a drawing application, you'll want a small GUI easy to incorporate into your projects.</p> <p>Besides that today made Tkinter applications run faster and better in small devices with limited hardware, ARM or raspberry o smartphones but wxwidgets becomes slow.</p> <p>If your application is basic and small and you platform is not robust chooses Tkinter, but if is big and heavy and platform of very much resources chooses wxwidget o QT.</p>
0
2015-12-31T04:33:06Z
[ "python", "tcl", "tk" ]
Python decorators in classes
1,263,451
<p>Can one write sth like:</p> <pre><code>class Test(object): def _decorator(self, foo): foo() @self._decorator def bar(self): pass </code></pre> <p>This fails: self in @self is unknown</p> <p>I also tried:</p> <pre><code>@Test._decorator(self) </code></pre> <p>which also fails: Test unknown</p> <p>If would like to temp. change some instance variables in the decorator and the run the decorated method, before changing them back.</p> <p>Thanks.</p>
65
2009-08-11T23:01:45Z
1,263,545
<p>What you're wanting to do isn't possible. Take, for instance, whether or not the code below looks valid:</p> <pre><code>class Test(object): def _decorator(self, foo): foo() def bar(self): pass bar = self._decorator(bar) </code></pre> <p>It, of course, isn't valid since <code>self</code> isn't defined at that point. The same goes for <code>Test</code> as it won't be defined until the class itself is defined (which its in the process of). I'm showing you this code snippet because <strong>this is what your decorator snippet transforms into.</strong></p> <p>So, as you can see, accessing the instance in a decorator like that isn't really possible since decorators are applied during the definition of whatever function/method they are attached to and not during instantiation.</p> <p>If you need <strong>class-level access</strong>, try this:</p> <pre><code>class Test(object): @classmethod def _decorator(cls, foo): foo() def bar(self): pass Test.bar = Test._decorator(Test.bar) </code></pre>
51
2009-08-11T23:33:46Z
[ "python", "class", "decorator", "self" ]
Python decorators in classes
1,263,451
<p>Can one write sth like:</p> <pre><code>class Test(object): def _decorator(self, foo): foo() @self._decorator def bar(self): pass </code></pre> <p>This fails: self in @self is unknown</p> <p>I also tried:</p> <pre><code>@Test._decorator(self) </code></pre> <p>which also fails: Test unknown</p> <p>If would like to temp. change some instance variables in the decorator and the run the decorated method, before changing them back.</p> <p>Thanks.</p>
65
2009-08-11T23:01:45Z
1,263,782
<p>Would something like this do what you need?</p> <pre><code>class Test(object): def _decorator(foo): def magic( self ) : print "start magic" foo( self ) print "end magic" return magic @_decorator def bar( self ) : print "normal call" test = Test() test.bar() </code></pre> <p>This avoids the call to self to access the decorator and leaves it hidden in the class namespace as a regular method.</p> <pre><code>&gt;&gt;&gt; import stackoverflow &gt;&gt;&gt; test = stackoverflow.Test() &gt;&gt;&gt; test.bar() start magic normal call end magic &gt;&gt;&gt; </code></pre> <hr> <p>edited to answer question in comments:</p> <p>How to use the hidden decorator in another class</p> <pre><code>class Test(object): def _decorator(foo): def magic( self ) : print "start magic" foo( self ) print "end magic" return magic @_decorator def bar( self ) : print "normal call" _decorator = staticmethod( _decorator ) class TestB( Test ): @Test._decorator def bar( self ): print "override bar in" super( TestB, self ).bar() print "override bar out" print "Normal:" test = Test() test.bar() print print "Inherited:" b = TestB() b.bar() print </code></pre>
119
2009-08-12T01:13:16Z
[ "python", "class", "decorator", "self" ]
Python decorators in classes
1,263,451
<p>Can one write sth like:</p> <pre><code>class Test(object): def _decorator(self, foo): foo() @self._decorator def bar(self): pass </code></pre> <p>This fails: self in @self is unknown</p> <p>I also tried:</p> <pre><code>@Test._decorator(self) </code></pre> <p>which also fails: Test unknown</p> <p>If would like to temp. change some instance variables in the decorator and the run the decorated method, before changing them back.</p> <p>Thanks.</p>
65
2009-08-11T23:01:45Z
8,899,247
<p>I found this question while researching a very similar problem. My solution is to split the problem into two parts. First, you need to capture the data that you want to associate with the class methods. In this case, handler_for will associate a Unix command with handler for that command's output.</p> <pre><code>class OutputAnalysis(object): "analyze the output of diagnostic commands" def handler_for(name): "decorator to associate a function with a command" def wrapper(func): func.handler_for = name return func return wrapper # associate mount_p with 'mount_-p.txt' @handler_for('mount -p') def mount_p(self, slurped): pass </code></pre> <p>Now that we've associated some data with each class method, we need to gather that data and store it in a class attribute.</p> <pre><code>OutputAnalysis.cmd_handler = {} for value in OutputAnalysis.__dict__.itervalues(): try: OutputAnalysis.cmd_handler[value.handler_for] = value except AttributeError: pass </code></pre>
1
2012-01-17T17:48:25Z
[ "python", "class", "decorator", "self" ]
Python decorators in classes
1,263,451
<p>Can one write sth like:</p> <pre><code>class Test(object): def _decorator(self, foo): foo() @self._decorator def bar(self): pass </code></pre> <p>This fails: self in @self is unknown</p> <p>I also tried:</p> <pre><code>@Test._decorator(self) </code></pre> <p>which also fails: Test unknown</p> <p>If would like to temp. change some instance variables in the decorator and the run the decorated method, before changing them back.</p> <p>Thanks.</p>
65
2009-08-11T23:01:45Z
12,034,971
<p>I use this type of decorator in some debugging situations, it allows overriding class properties by decorating, without having to find the calling function.</p> <pre><code>class myclass(object): def __init__(self): self.property = "HELLO" @adecorator(property="GOODBYE") def method(self): print self.property </code></pre> <p>Here is the decorator code</p> <pre><code>class adecorator (object): def __init__ (self, *args, **kwargs): # store arguments passed to the decorator self.args = args self.kwargs = kwargs def __call__(self, func): def newf(*args, **kwargs): #the 'self' for a method function is passed as args[0] slf = args[0] # replace and store the attributes saved = {} for k,v in self.kwargs.items(): if hasattr(slf, k): saved[k] = getattr(slf,k) setattr(slf, k, v) # call the method ret = func(*args, **kwargs) #put things back for k,v in saved.items(): setattr(slf, k, v) return ret newf.__doc__ = func.__doc__ return newf </code></pre> <p>Note: because I've used a class decorator you'll need to use @adecorator() <em>with the brackets</em> on to decorate functions, even if you don't pass any arguments to the decorator class constructor.</p>
3
2012-08-20T09:13:09Z
[ "python", "class", "decorator", "self" ]
Python decorators in classes
1,263,451
<p>Can one write sth like:</p> <pre><code>class Test(object): def _decorator(self, foo): foo() @self._decorator def bar(self): pass </code></pre> <p>This fails: self in @self is unknown</p> <p>I also tried:</p> <pre><code>@Test._decorator(self) </code></pre> <p>which also fails: Test unknown</p> <p>If would like to temp. change some instance variables in the decorator and the run the decorated method, before changing them back.</p> <p>Thanks.</p>
65
2009-08-11T23:01:45Z
18,455,963
<p>Decorators seem better suited to modify the functionality of an <strong>entire object</strong> (including function objects) versus the functionality of an <strong>object method</strong> which in general will depend on instance attributes. For example: </p> <pre><code>def mod_bar(cls): # returns modified class def decorate(fcn): # returns decorated function def new_fcn(self): print self.start_str print fcn(self) print self.end_str return new_fcn cls.bar = decorate(cls.bar) return cls @mod_bar class Test(object): def __init__(self): self.start_str = "starting dec" self.end_str = "ending dec" def bar(self): return "bar" </code></pre> <p>The output is: </p> <pre><code>&gt;&gt;&gt; import Test &gt;&gt;&gt; a = Test() &gt;&gt;&gt; a.bar() starting dec bar ending dec </code></pre>
1
2013-08-27T02:22:25Z
[ "python", "class", "decorator", "self" ]
Python decorators in classes
1,263,451
<p>Can one write sth like:</p> <pre><code>class Test(object): def _decorator(self, foo): foo() @self._decorator def bar(self): pass </code></pre> <p>This fails: self in @self is unknown</p> <p>I also tried:</p> <pre><code>@Test._decorator(self) </code></pre> <p>which also fails: Test unknown</p> <p>If would like to temp. change some instance variables in the decorator and the run the decorated method, before changing them back.</p> <p>Thanks.</p>
65
2009-08-11T23:01:45Z
25,290,416
<p>You can decorate the decorator:</p> <pre><code>import decorator class Test(object): @decorator.decorator def _decorator(foo, self): foo(self) @_decorator def bar(self): pass </code></pre>
0
2014-08-13T15:37:39Z
[ "python", "class", "decorator", "self" ]
Python decorators in classes
1,263,451
<p>Can one write sth like:</p> <pre><code>class Test(object): def _decorator(self, foo): foo() @self._decorator def bar(self): pass </code></pre> <p>This fails: self in @self is unknown</p> <p>I also tried:</p> <pre><code>@Test._decorator(self) </code></pre> <p>which also fails: Test unknown</p> <p>If would like to temp. change some instance variables in the decorator and the run the decorated method, before changing them back.</p> <p>Thanks.</p>
65
2009-08-11T23:01:45Z
37,675,810
<p>This is one way I know of (and have used) to access <code>self</code> from inside a decorator defined inside the same class:</p> <pre><code>class Thing(object): def __init__(self, name): self.name = name def debug_name(function): def debug_wrapper(*args): self = args[0] print 'self.name = ' + self.name print 'running function {}()'.format(function.__name__) function(*args) print 'self.name = ' + self.name return debug_wrapper @debug_name def set_name(self, new_name): self.name = new_name </code></pre> <p>Output (tested on python 2.7.10):</p> <pre><code>&gt;&gt;&gt; a = Thing('A') &gt;&gt;&gt; a.name 'A' &gt;&gt;&gt; a.set_name('B') self.name = A running function set_name() self.name = B &gt;&gt;&gt; a.name 'B' </code></pre> <p>The example above is silly, but shows that it works. </p>
1
2016-06-07T09:43:25Z
[ "python", "class", "decorator", "self" ]
Another absolute import problem
1,263,474
<p>I'm having problems with my own modules overriding built in Python ones (specifically the logging module). Here's my project layout:</p> <pre><code>run.py package/ __init__.py logging/ __init__.py ... </code></pre> <p>run.py</p> <pre><code>from package import main main() </code></pre> <p>package/__init__.py</p> <pre><code>from __future__ import absolute_import import logging import logging.config def main(): logging.config.fileConfig(...) </code></pre> <p>package/logging/__init__.py</p> <pre><code>class Logging(object): pass </code></pre> <p>As it stands right now, the above code works. As soon as I try to import the Logging class from package.logging like so:</p> <pre><code>from __future__ import absolute_import import logging import logging.config from package.logging import Logging def main(): logging.config.fileConfig(...) </code></pre> <p>I get an error:</p> <pre><code>AttributeError: 'module' object has no attribute 'config' </code></pre> <p>I've read the <a href="http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports">PEP 328</a> release notes and found absolute imports to be rather straightforward. Unfortunately I haven't been able to figure this one out. </p> <p>What am I missing here?</p>
5
2009-08-11T23:10:06Z
1,263,508
<p>You can use <a href="http://docs.python.org/whatsnew/2.5.html#pep-328" rel="nofollow">relative imports</a> to force where python looks for the modules first:</p> <p><code>in package/__init__.py</code></p> <pre><code>from . import logging </code></pre>
1
2009-08-11T23:21:50Z
[ "python" ]
Another absolute import problem
1,263,474
<p>I'm having problems with my own modules overriding built in Python ones (specifically the logging module). Here's my project layout:</p> <pre><code>run.py package/ __init__.py logging/ __init__.py ... </code></pre> <p>run.py</p> <pre><code>from package import main main() </code></pre> <p>package/__init__.py</p> <pre><code>from __future__ import absolute_import import logging import logging.config def main(): logging.config.fileConfig(...) </code></pre> <p>package/logging/__init__.py</p> <pre><code>class Logging(object): pass </code></pre> <p>As it stands right now, the above code works. As soon as I try to import the Logging class from package.logging like so:</p> <pre><code>from __future__ import absolute_import import logging import logging.config from package.logging import Logging def main(): logging.config.fileConfig(...) </code></pre> <p>I get an error:</p> <pre><code>AttributeError: 'module' object has no attribute 'config' </code></pre> <p>I've read the <a href="http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports">PEP 328</a> release notes and found absolute imports to be rather straightforward. Unfortunately I haven't been able to figure this one out. </p> <p>What am I missing here?</p>
5
2009-08-11T23:10:06Z
8,295,885
<p>Relative and absolute imports (PEP 328) are not the problem here.</p> <p>What happens is that when a module in a package is imported, it is implicitly added to this package's namespace. So</p> <pre><code>from package.logging import Logging </code></pre> <p>not only adds 'Logging' to package.<em>_dict</em>_, but also adds 'logging' (the newly import local module) to package.<em>_dict</em>_. So you first import logging (the top-level module) and it is available as package.logging, and then you overwrite this variable with the local module. This basically means that you cannot have a package.logging to access the top-level module and your local module, as expected.</p> <p>In this specific case, you probably don't want to "export" the top-level logging module as a public name. Instead do:</p> <pre><code>from logging import config as _config def main(): _config.fileConfig(...) </code></pre>
8
2011-11-28T12:34:56Z
[ "python" ]
Reverse mapping class attributes to classes in Python
1,263,479
<p>I have some code in Python where I'll have a bunch of classes, each of which will have an attribute <code>_internal_attribute</code>. I would like to be able to generate a mapping of those attributes to the original class. Essentially I would like to be able to do this:</p> <pre><code>class A(object): _internal_attribute = 'A attribute' class B(object): _internal_attribute = 'B attribute' a_instance = magic_reverse_mapping['A attribute']() b_instance = magic_reverse_mapping['B attribute']() </code></pre> <p>What I'm missing here is how to generate <code>magic_reverse_mapping</code> dict. I have a gut feeling that having a metaclass generate A and B is the correct way to go about this; does that seem right?</p>
0
2009-08-11T23:11:58Z
1,263,507
<p>You need some data structure to store the list of applicable classes in the first place, but you don't have to generate it in the first place. You can read classes from globals instead. This naturally assumes that your classes extend <code>object</code>, as they do in your first post.</p> <pre><code>def magic_reverse_mapping(attribute_name, attribute_value): classobjects = [val for val in globals().values() if isinstance(val, object)] attrobjects = [cls for cls in classobjects if hasattr(cls, attribute_name)] resultobjects = [cls for cls in attrobjects if object.__getattribute__(cls, attribute_name) == attribute_value] return resultobjects magic_reverse_mapping('_internal_attribute', 'A attribute') #output: [&lt;class '__main__.A'&gt;] </code></pre> <p>Note that this returns a <em>list</em> of classes with that attribute value, because there may be more than one. If you wanted to instantiate the first one:</p> <pre><code>magic_reverse_mapping('_internal_attribute', 'A attribute')[0]() #output: &lt;__main__.A object at 0xb7ce486c&gt; </code></pre> <p>Unlike in sth's answer, you don't have to add a decorator to your classes (neat solution, though). However, there's no way to exclude any classes that are in the global namespace.</p>
3
2009-08-11T23:21:40Z
[ "python", "metaclass" ]
Reverse mapping class attributes to classes in Python
1,263,479
<p>I have some code in Python where I'll have a bunch of classes, each of which will have an attribute <code>_internal_attribute</code>. I would like to be able to generate a mapping of those attributes to the original class. Essentially I would like to be able to do this:</p> <pre><code>class A(object): _internal_attribute = 'A attribute' class B(object): _internal_attribute = 'B attribute' a_instance = magic_reverse_mapping['A attribute']() b_instance = magic_reverse_mapping['B attribute']() </code></pre> <p>What I'm missing here is how to generate <code>magic_reverse_mapping</code> dict. I have a gut feeling that having a metaclass generate A and B is the correct way to go about this; does that seem right?</p>
0
2009-08-11T23:11:58Z
1,263,617
<p>You <em>can</em> use a meta class to automatically register your classes in <code>magic_reverse_mapping</code>:</p> <pre><code>magic_reverse_mapping = {} class MagicRegister(type): def __new__(meta, name, bases, dict): cls = type.__new__(meta, name, bases, dict) magic_reverse_mapping[dict['_internal_attribute']] = cls return cls class A(object): __metaclass__ = MagicRegister _internal_attribute = 'A attribute' afoo = magic_reverse_mapping['A attribute']() </code></pre> <p>Alternatively you can use a decorator on your classes to register them. I think this is more readable and easier to understand:</p> <pre><code>magic_reverse_mapping = {} def magic_register(cls): magic_reverse_mapping[cls._internal_attribute] = cls return cls @magic_register class A(object): _internal_attribute = 'A attribute' afoo = magic_reverse_mapping['A attribute']() </code></pre> <p>Or you could even do it by hand. It's not that much more work without using any magic:</p> <pre><code>reverse_mapping = {} class A(object): _internal_attribute = 'A attribute' reverse_mapping[A._internal_attribute] = A </code></pre> <p>Looking at the different variants I think the decorator version would be the most pleasant to use.</p>
5
2009-08-12T00:02:52Z
[ "python", "metaclass" ]
Use cases for doctest advanced API
1,263,648
<p>Python's doctest module has a section for <a href="http://docs.python.org/library/doctest#advanced-api" rel="nofollow">advanced API</a>. Has anyone found a particular use for this API?</p> <p>A quick look at the API structure (from the docs):</p> <pre><code> list of: +------+ +---------+ |module| --DocTestFinder-&gt; | DocTest | --DocTestRunner-&gt; results +------+ | ^ +---------+ | ^ (printed) | | | Example | | | v | | ... | v | DocTestParser | Example | OutputChecker +---------+ </code></pre>
0
2009-08-12T00:18:29Z
1,263,679
<p>You use that API when you are extending doctests, <a href="http://www.somethingaboutorange.com/mrl/projects/nose/doc/plugin%5Fdoctests.html" rel="nofollow">like the nose unit testing suite does</a>.</p>
1
2009-08-12T00:32:44Z
[ "python", "api", "doctest", "use-case" ]
Is there a class library diagram for django?
1,263,677
<p>I'm looking for a way to find out the class structure at a glance for django. Is there a link to an overview of it? </p>
1
2009-08-12T00:32:20Z
1,264,195
<p>I'm not aware of a reference diagram. But you could probably generate one using a tool like the following:</p> <ul> <li><a href="http://sourceforge.net/projects/eclipse-pyuml/" rel="nofollow">Eclipse-PyUML</a></li> <li><a href="http://www.andypatterns.com/index.php/products/pynsource%5F-%5Fuml%5Ftool%5Ffor%5Fpython/" rel="nofollow">PyNSource</a></li> </ul>
0
2009-08-12T04:20:35Z
[ "python", "django" ]
Is there a class library diagram for django?
1,263,677
<p>I'm looking for a way to find out the class structure at a glance for django. Is there a link to an overview of it? </p>
1
2009-08-12T00:32:20Z
1,264,270
<p><a href="http://www.graphviz.org/" rel="nofollow">Graphviz</a> is solution worth looking at. Personally, I much prefer a graphic representation over UML</p>
0
2009-08-12T04:54:40Z
[ "python", "django" ]
Is there a class library diagram for django?
1,263,677
<p>I'm looking for a way to find out the class structure at a glance for django. Is there a link to an overview of it? </p>
1
2009-08-12T00:32:20Z
1,264,807
<p>In the app django_extensions on google code. There is <a href="http://code.google.com/p/django-command-extensions/wiki/GraphModels">GraphModels</a> command</p>
8
2009-08-12T07:48:44Z
[ "python", "django" ]
Is there a class library diagram for django?
1,263,677
<p>I'm looking for a way to find out the class structure at a glance for django. Is there a link to an overview of it? </p>
1
2009-08-12T00:32:20Z
1,264,897
<p>A class diagram of most of django's class structure is really not very interesting or useful for that matter. The problem is that most classes you use for development with django are standalone in the sense that they don't branch out to child classes. The only thing that comes to mind is the structure of the <a href="http://code.djangoproject.com/ticket/6735" rel="nofollow">class-based generic views</a>, but that's not yet committed to trunk.</p> <p>Other than that, there's really not much class structure that you use when developing <strong>with</strong> django. There are several examples for development <strong>for</strong> django, but most are transparent to the user (e.g. <code>QuerySet</code> and its children classes). I think a much better source for a better overview is the <a href="http://docs.djangoproject.com/en/dev/" rel="nofollow">documentation</a> and the <a href="http://code.djangoproject.com/browser/django/trunk/django" rel="nofollow">source</a> in general (no pun intended).</p>
1
2009-08-12T08:18:57Z
[ "python", "django" ]
technology recommendation for LAN Dashboard
1,263,756
<p>I'm about to start a fairly large project for a mid-sized business with a lot of integration with other systems (POS, accounting, website, inventory, purchasing, etc.) The purpose of the system is to try to reduce current data siloing and give employees role-based access to the specific data entry and reports they need, as well as to replace some manual and redundant business processes. The system needs to be cross-platform (Windows/Linux), open source and is primarily for LAN use.</p> <p>My experience is mostly PHP/web/app development, but I have developed a few LAN apps using Java/Servoy (like Filemaker). I found Servoy to be very rapid and to easily make use of different data providers (DB products), but it's not open source, and any non-standard development is in Java/Swing (which is verbose and takes a lot of time). </p> <p>I'm interested in learning Python/Django or Ruby/Rails - but I'm not sure if these are the best solutions for building a mission critical data entry/reporting LAN app. Is a web client/server really a good choice for this type of application? </p> <p>Thanks in advance for any tips/ advice.</p>
1
2009-08-12T01:01:34Z
1,263,768
<p>If you're comfortable with a LAMP-style stack with PHP, then there's no reason you can't use either Django or Rails. Both are mature, well documented platforms with active, helpful communities. </p> <p>Based on what you've described, there's no reason that you can't use either technology. </p>
1
2009-08-12T01:07:02Z
[ "python", "ruby-on-rails", "django", "dashboard", "filemaker" ]
technology recommendation for LAN Dashboard
1,263,756
<p>I'm about to start a fairly large project for a mid-sized business with a lot of integration with other systems (POS, accounting, website, inventory, purchasing, etc.) The purpose of the system is to try to reduce current data siloing and give employees role-based access to the specific data entry and reports they need, as well as to replace some manual and redundant business processes. The system needs to be cross-platform (Windows/Linux), open source and is primarily for LAN use.</p> <p>My experience is mostly PHP/web/app development, but I have developed a few LAN apps using Java/Servoy (like Filemaker). I found Servoy to be very rapid and to easily make use of different data providers (DB products), but it's not open source, and any non-standard development is in Java/Swing (which is verbose and takes a lot of time). </p> <p>I'm interested in learning Python/Django or Ruby/Rails - but I'm not sure if these are the best solutions for building a mission critical data entry/reporting LAN app. Is a web client/server really a good choice for this type of application? </p> <p>Thanks in advance for any tips/ advice.</p>
1
2009-08-12T01:01:34Z
1,264,058
<p>Both of these technologies are certainly mature enough to run Mission Critical applications, you just need to look at the number of big sites already on the internet that are running these technologies, so from that point of view you shouldn't be concerned.</p> <p>You only need to worry about your learning curve, if you feel confident in learning them well enough to write quality code for your client then go for it. Have a look at each of them, decide which technology you would prefer and get coding.</p> <p>Hope your application goes well :)</p>
0
2009-08-12T03:21:53Z
[ "python", "ruby-on-rails", "django", "dashboard", "filemaker" ]
technology recommendation for LAN Dashboard
1,263,756
<p>I'm about to start a fairly large project for a mid-sized business with a lot of integration with other systems (POS, accounting, website, inventory, purchasing, etc.) The purpose of the system is to try to reduce current data siloing and give employees role-based access to the specific data entry and reports they need, as well as to replace some manual and redundant business processes. The system needs to be cross-platform (Windows/Linux), open source and is primarily for LAN use.</p> <p>My experience is mostly PHP/web/app development, but I have developed a few LAN apps using Java/Servoy (like Filemaker). I found Servoy to be very rapid and to easily make use of different data providers (DB products), but it's not open source, and any non-standard development is in Java/Swing (which is verbose and takes a lot of time). </p> <p>I'm interested in learning Python/Django or Ruby/Rails - but I'm not sure if these are the best solutions for building a mission critical data entry/reporting LAN app. Is a web client/server really a good choice for this type of application? </p> <p>Thanks in advance for any tips/ advice.</p>
1
2009-08-12T01:01:34Z
1,265,425
<p>You could also take a look at ExtJS for the frontend. I've made an ExtJS frontend for a company Dashboard, and using a Django backend managing the URL dispatching, the ORM and the data retrieval (communicating with the frontend with JSON webservices) and users love it, because it's almost as interactive as a local application (use something modern like Firefox 3.5, Chrome, Safari 4 or Explorer 8 for better javascript performance) but easy to manage for programmers and administrators (no installations, no local backups, no upgrade problems, etc.)</p>
0
2009-08-12T10:40:22Z
[ "python", "ruby-on-rails", "django", "dashboard", "filemaker" ]
technology recommendation for LAN Dashboard
1,263,756
<p>I'm about to start a fairly large project for a mid-sized business with a lot of integration with other systems (POS, accounting, website, inventory, purchasing, etc.) The purpose of the system is to try to reduce current data siloing and give employees role-based access to the specific data entry and reports they need, as well as to replace some manual and redundant business processes. The system needs to be cross-platform (Windows/Linux), open source and is primarily for LAN use.</p> <p>My experience is mostly PHP/web/app development, but I have developed a few LAN apps using Java/Servoy (like Filemaker). I found Servoy to be very rapid and to easily make use of different data providers (DB products), but it's not open source, and any non-standard development is in Java/Swing (which is verbose and takes a lot of time). </p> <p>I'm interested in learning Python/Django or Ruby/Rails - but I'm not sure if these are the best solutions for building a mission critical data entry/reporting LAN app. Is a web client/server really a good choice for this type of application? </p> <p>Thanks in advance for any tips/ advice.</p>
1
2009-08-12T01:01:34Z
1,275,182
<p>Thank you everyone for your helpful answers! I think they address most of the issues raised by the question. But I think the key to the "final answer" (IMO) rests on the "multiple database" aspect. Railsninja suggested a piece of software he used for a project to extend rails functionality in this manner - thank you for the link! That could have been a possible solution - but it sounds like it was used for one project, and I worry about the testing since it is not a part of the mainstream Rails build. </p> <p>Then I found out that multi-db support is just around the corner for a Django core update (eta late August 2009). So I think I am going to dive in to the project with Django.</p>
0
2009-08-13T23:14:41Z
[ "python", "ruby-on-rails", "django", "dashboard", "filemaker" ]
How do I convert unicode characters to floats in Python?
1,263,796
<p>I am parsing a webpage which has Unicode representations of fractions. I would like to be able to take those strings directly and convert them to floats. For example:</p> <p>"⅕" would become 0.2</p> <p>Any suggestions of how to do this in Python?</p>
10
2009-08-12T01:23:15Z
1,263,810
<p>Since there are only a fixed number of fractions defined in Unicode, a dictionary seems appropriate:</p> <pre><code>Fractions = { u'¼': 0.25, u'½': 0.5, u'¾': 0.75, u'⅕': 0.2, # add any other fractions here } </code></pre> <p>Update: the <code>unicodedata</code> module is a much better solution.</p>
1
2009-08-12T01:27:59Z
[ "python", "unicode", "floating-point" ]
How do I convert unicode characters to floats in Python?
1,263,796
<p>I am parsing a webpage which has Unicode representations of fractions. I would like to be able to take those strings directly and convert them to floats. For example:</p> <p>"⅕" would become 0.2</p> <p>Any suggestions of how to do this in Python?</p>
10
2009-08-12T01:23:15Z
1,263,811
<p>You want to use the <a href="http://docs.python.org/library/unicodedata.html">unicodedata</a> module:</p> <pre><code>import unicodedata unicodedata.numeric(u'⅕') </code></pre> <p>This will print:</p> <pre><code>0.20000000000000001 </code></pre> <p>If the character does not have a numeric value, then <code>unicodedata.numeric(unichr[, default])</code> will return default, or if default is not given will raise ValueError.</p>
21
2009-08-12T01:28:06Z
[ "python", "unicode", "floating-point" ]
How do I convert unicode characters to floats in Python?
1,263,796
<p>I am parsing a webpage which has Unicode representations of fractions. I would like to be able to take those strings directly and convert them to floats. For example:</p> <p>"⅕" would become 0.2</p> <p>Any suggestions of how to do this in Python?</p>
10
2009-08-12T01:23:15Z
1,263,820
<p>Maybe you could decompose the fraction using the <a href="http://docs.python.org/library/unicodedata.html" rel="nofollow">"unicodedata" module</a> and then look for the <a href="http://www.fileformat.info/info/unicode/char/2044/index.htm" rel="nofollow">FRACTION SLASH character</a> and then it's just a matter of simple division.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; import unicodedata &gt;&gt;&gt; unicodedata.lookup('VULGAR FRACTION ONE QUARTER') u'\xbc' &gt;&gt;&gt; unicodedata.decomposition(unicodedata.lookup('VULGAR FRACTION ONE QUARTER')) '&lt;fraction&gt; 0031 2044 0034' </code></pre> <p><strong>Update:</strong> I'll leave this answer here for reference but using unicodedata.numeric() as per Karl's answer is a much better idea.</p>
1
2009-08-12T01:31:32Z
[ "python", "unicode", "floating-point" ]
How do I convert unicode characters to floats in Python?
1,263,796
<p>I am parsing a webpage which has Unicode representations of fractions. I would like to be able to take those strings directly and convert them to floats. For example:</p> <p>"⅕" would become 0.2</p> <p>Any suggestions of how to do this in Python?</p>
10
2009-08-12T01:23:15Z
1,265,869
<p>In Python 3.1, you don't need the 'u', and it will produce 0.2 instead of 0.20000000000000001 .</p> <pre><code>&gt;&gt;&gt; unicodedata.numeric('⅕') 0.2 </code></pre>
1
2009-08-12T12:30:40Z
[ "python", "unicode", "floating-point" ]
How do I convert unicode characters to floats in Python?
1,263,796
<p>I am parsing a webpage which has Unicode representations of fractions. I would like to be able to take those strings directly and convert them to floats. For example:</p> <p>"⅕" would become 0.2</p> <p>Any suggestions of how to do this in Python?</p>
10
2009-08-12T01:23:15Z
36,586,275
<p>I'm stating the obvious here, but it's very simple to extend this for cases when people write "1¾" meaning "1.75", so I'm just going to share it here for quick reference:</p> <pre><code>import unicodedata # Assuming that the unicode is always the last character. You always going to see stuff like "3¼", or "19¼" whereas stuff like "3¼5" # does not have a clear interpretation def convertVulgarFractions(vulgarFraction): if (len(vulgarFraction) == 1): return unicodedata.numeric(vulgarFraction) if (len(vulgarFraction) &gt; 1) &amp; (not (vulgarFraction[:len(vulgarFraction)-1].isdigit())): raise ArithmeticError("The format needs to be numbers ending with a vulgar fraction. The number inserted was " + str(vulgarFraction)) if vulgarFraction[len(vulgarFraction)-1].isdigit(): return float(vulgarFraction) else: return float(vulgarFraction[:len(vulgarFraction)-1]) + unicodedata.numeric(vulgarFraction[len(vulgarFraction)-1]) </code></pre>
0
2016-04-13T00:11:24Z
[ "python", "unicode", "floating-point" ]
Mechanize and BeautifulSoup for PHP?
1,263,800
<p>I was wondering if there was anything similar like Mechanize or BeautifulSoup for PHP?</p>
18
2009-08-12T01:24:42Z
1,263,812
<p>SimpleTest provides you with similar functionality:</p> <p><a href="http://www.simpletest.org/en/browser_documentation.html" rel="nofollow">http://www.simpletest.org/en/browser_documentation.html</a></p>
8
2009-08-12T01:28:32Z
[ "php", "python", "beautifulsoup", "mechanize" ]
Mechanize and BeautifulSoup for PHP?
1,263,800
<p>I was wondering if there was anything similar like Mechanize or BeautifulSoup for PHP?</p>
18
2009-08-12T01:24:42Z
1,264,191
<p>I don't know how powerful BeautifulSoup is, so maybe this won't be as great ; but you could try using <a href="http://php.net/manual/en/domdocument.loadhtml.php"><code>DOMDocument::loadHTML</code></a> :</p> <blockquote> <p>The function parses the HTML contained in the string source . Unlike loading XML, HTML does not have to be well-formed to load.</p> </blockquote> <p>After using this, you should be able to access the HTML document using DOM methods -- including XPath queries.</p>
5
2009-08-12T04:20:21Z
[ "php", "python", "beautifulsoup", "mechanize" ]
Mechanize and BeautifulSoup for PHP?
1,263,800
<p>I was wondering if there was anything similar like Mechanize or BeautifulSoup for PHP?</p>
18
2009-08-12T01:24:42Z
1,264,317
<p>Don't know about BeautifulSoup, but there is <a href="http://code.google.com/p/phpquery/" rel="nofollow">phpquery</a> which is similar to jquery</p> <pre><code>$doc = phpQuery::newDocument('&lt;div/&gt;'); $doc['div']-&gt;append('&lt;ul&gt;&lt;/ul&gt;'); $doc['div ul'] = '&lt;li&gt;1&lt;/li&gt;&lt;li&gt;2&lt;/li&gt;&lt;li&gt;3&lt;/li&gt;'; $doc['ul &gt; li:last'] = 'hello'; </code></pre>
3
2009-08-12T05:13:48Z
[ "php", "python", "beautifulsoup", "mechanize" ]
How to catch errors elegantly and keep methods clean?
1,264,150
<p>I am in the process of writing a small(er) Python script to automate a semi-frequent, long, and error-prone task. This script is responsible for making various system calls - either though os.system or through os.(mkdir|chdir|etc).</p> <p>Here is an example of my code right now:</p> <pre><code>class AClass: def __init__(self, foo, bar, verbose=False, silent=False): # Sets up variables needed for each instance, etc self.redirect = '' if silent: self.redirect = '&gt; 2&gt;&amp;1' self.verbose = verbose def a_method(self): """ Responsible for running 4-6 things via system calls as described """ if self.verbose and not self.silent: print "Creating a directory" try: os.mkdir('foobar') except OSError, e: raise OSError, "Problem creating directory %s: %s" % (e.filename, e.strerror) if self.verbose and not self.silent: print "Listing a directory" if (os.system('ls foobar %s') % self.redirect) is not 0: raise OSError, "Could not list directory foobar" def b_method(self): """ Looks very similar to a_method() """ def run(self): """ Stitches everything together """ try: a_method() except OSError, e: print "a_method(): %s" % e.strerror sys.exit(-1) try: b_method() except OSError, e: print "b_method(): %s" % e.strerror sys.exit(-1) </code></pre> <p>Obviously writing all the <code>if self.verbose and not self.silent</code> is messy and then the <code>try/catch</code> or <code>if</code> around each call is ugly to look at. I would have liked to use Python's logging class and simply have one logging level (verbose) configurable via command line and then I can simple call <code>logger.debug('My message')</code> but I am using Python 2.2 and I do not have access to the <code>logging</code> class.</p> <p><strong>Summary/Base Questions</strong><br /> I am using Python 2.2 and I cannot change this. I am running on an ESX 3.0.2 server and I cannot touch it in any other way for the time being.<br /> What is the best way to handle error checking and verbose output without tying this logic to your class (which should only do One Thing)?<br /> How can I reduce the clutter with something more simple or elegant to look at?</p> <p>Thanks!</p>
1
2009-08-12T03:59:31Z
1,264,163
<p><strong>How to clean up your verbose output</strong></p> <p>Move the verbose/quiet logic into a single function, and then call that function for all of your output. If you make it something nice and short it keeps your mainline code quite tidy.</p> <pre><code>def P(s): if (verbose): print s </code></pre> <p>I have a package that does this in our internal code, it has the following methods:</p> <ul> <li><strong>P</strong> -- normal print: <code>P('this prints regardless, --quiet does not shut it up')</code></li> <li><strong>V</strong> -- verbose print: <code>V('this only prints if --verbose')</code></li> <li><strong>D</strong> -- debug print: <code>D('this only prints if --debug')</code></li> </ul>
4
2009-08-12T04:06:57Z
[ "python" ]
How to catch errors elegantly and keep methods clean?
1,264,150
<p>I am in the process of writing a small(er) Python script to automate a semi-frequent, long, and error-prone task. This script is responsible for making various system calls - either though os.system or through os.(mkdir|chdir|etc).</p> <p>Here is an example of my code right now:</p> <pre><code>class AClass: def __init__(self, foo, bar, verbose=False, silent=False): # Sets up variables needed for each instance, etc self.redirect = '' if silent: self.redirect = '&gt; 2&gt;&amp;1' self.verbose = verbose def a_method(self): """ Responsible for running 4-6 things via system calls as described """ if self.verbose and not self.silent: print "Creating a directory" try: os.mkdir('foobar') except OSError, e: raise OSError, "Problem creating directory %s: %s" % (e.filename, e.strerror) if self.verbose and not self.silent: print "Listing a directory" if (os.system('ls foobar %s') % self.redirect) is not 0: raise OSError, "Could not list directory foobar" def b_method(self): """ Looks very similar to a_method() """ def run(self): """ Stitches everything together """ try: a_method() except OSError, e: print "a_method(): %s" % e.strerror sys.exit(-1) try: b_method() except OSError, e: print "b_method(): %s" % e.strerror sys.exit(-1) </code></pre> <p>Obviously writing all the <code>if self.verbose and not self.silent</code> is messy and then the <code>try/catch</code> or <code>if</code> around each call is ugly to look at. I would have liked to use Python's logging class and simply have one logging level (verbose) configurable via command line and then I can simple call <code>logger.debug('My message')</code> but I am using Python 2.2 and I do not have access to the <code>logging</code> class.</p> <p><strong>Summary/Base Questions</strong><br /> I am using Python 2.2 and I cannot change this. I am running on an ESX 3.0.2 server and I cannot touch it in any other way for the time being.<br /> What is the best way to handle error checking and verbose output without tying this logic to your class (which should only do One Thing)?<br /> How can I reduce the clutter with something more simple or elegant to look at?</p> <p>Thanks!</p>
1
2009-08-12T03:59:31Z
1,264,171
<pre><code>writing all the if verbose and not silent is messy </code></pre> <p>So, instead, assign sys.stdout to a dummy class whose write is a no-op if you need to be unverbose or silent, then just use print without needing guards. (Do remember to restore sys.stdout to the real thing for prints that aren't so conditioned -- easier to encapsulate in a couple of functions, actually).</p> <p>For error checks, all the blocks like:</p> <pre><code> try: a_method() except OSError, e: print "a_method(): %s" % e.strerror sys.exit(-1) </code></pre> <p>can and should be like</p> <pre><code> docall(a_method) </code></pre> <p>for what I hope is a pretty obvious <code>def docall(acallable):</code>.</p> <p>Similarly, other try/except case and ones where the new exception is raised conditionally can become calls to functions with appropriate arguments (including callables, i.e. higher order functions). I'll be glad to add detailed code if you clarify what parts of this are hard or unclear to you!</p> <p>Python 2.2, while now very old, was a great language in its way, and it's just as feasible to use it neatly, as you wish, as it would be for other great old languages, like, say, MacLisp;-).</p>
4
2009-08-12T04:09:27Z
[ "python" ]
Django saving objects - works, but values of objects seem to be cached until I restart server
1,264,246
<p>I'm writing an app for tagging photos. One of the views handles adding new tags and without boilerplate for POST/GET and handling field errors it does this:</p> <pre><code>tagName = request.cleaned_attributes['tagName'] t = Tag.objects.create(name = tagName) t.save() </code></pre> <p>Now in a view for another request to retrieve all tags I have:</p> <pre><code>tags = Tag.objects.all() </code></pre> <p>I see the data only after restarting Django development server, which is odd to me. Seems like <code>Tag.objects.all()</code> has some caching mechanism that is not invalidated properly? The data is for sure saved to the database.</p> <p>The database backend is <code>sqlite</code>. I guess I am either missing some configuration or just forgot to do something simple. Ideas?</p>
0
2009-08-12T04:41:13Z
1,264,301
<p><code>Tag.objects.all()</code> is a QuerySet. These do not hit the database until you do something to <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#when-querysets-are-evaluated" rel="nofollow">evaluate</a> them. So, how exactly are you using it in your view? If you are using a generic view and passing the queryset through <code>extra_context</code>, for example, it <a href="http://docs.djangoproject.com/en/1.0/topics/generic-views/#adding-extra-context" rel="nofollow">wouldn't be re-evaluated</a>. </p> <p>Also, as an aside, <code>Tag.objects.create(name = tagName)</code> will <a href="http://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.QuerySet.create" rel="nofollow">automatically save</a> to the db.</p>
3
2009-08-12T05:08:49Z
[ "python", "django", "django-models" ]
HTTP POST binary files using Python: concise non-pycurl examples?
1,264,300
<p>I'm interested in writing a short python script which uploads a short binary file (.wav/.raw audio) via a POST request to a remote server.</p> <p>I've done this with pycurl, which makes it very simple and results in a concise script; unfortunately it also requires that the end user have pycurl installed, which I can't rely on. </p> <p>I've also seen some examples in other posts which rely only on basic libraries, urllib, urllib2, etc., however these generally seem to be quite verbose, which is also something I'd like to avoid. </p> <p>I'm wondering if there are any concise examples which do not require the use of external libraries, and which will be quick and easy for 3rd parties to understand - even if they aren't particularly familiar with python.</p> <p>What I'm using at present looks like,</p> <pre><code> def upload_wav( wavfile, url=None, **kwargs ): """Upload a wav file to the server, return the response.""" class responseCallback: """Store the server response.""" def __init__(self): self.contents='' def body_callback(self, buf): self.contents = self.contents + buf def decode( self ): self.contents = urllib.unquote(self.contents) try: self.contents = simplejson.loads(self.contents) except: return self.contents t = responseCallback() c = pycurl.Curl() c.setopt(c.POST,1) c.setopt(c.WRITEFUNCTION, t.body_callback) c.setopt(c.URL,url) postdict = [ ('userfile',(c.FORM_FILE,wavfile)), #wav file to post ] #If there are extra keyword args add them to the postdict for key in kwargs: postdict.append( (key,kwargs[key]) ) c.setopt(c.HTTPPOST,postdict) c.setopt(c.VERBOSE,verbose) c.perform() c.close() t.decode() return t.contents </code></pre> <p>this isn't exact, but it gives you the general idea. It works great, it's simple for 3rd parties to understand, <em>but</em> it requires pycurl.</p>
5
2009-08-12T05:07:57Z
1,264,425
<p>How's urllib substantially more verbose? You build postdict basically the same way, except you start with</p> <pre><code>postdict = [ ('userfile', open(wavfile, 'rb').read()) ] </code></pre> <p>Once you vave postdict,</p> <pre><code>resp = urllib.urlopen(url, urllib.urlencode(postdict)) </code></pre> <p>and then you get and save <code>resp.read()</code> and maybe unquote and try JSON-loading if needed. Seems like it would be actually shorter! So what am I missing...?</p>
1
2009-08-12T05:58:16Z
[ "python", "http", "post", "binary" ]
HTTP POST binary files using Python: concise non-pycurl examples?
1,264,300
<p>I'm interested in writing a short python script which uploads a short binary file (.wav/.raw audio) via a POST request to a remote server.</p> <p>I've done this with pycurl, which makes it very simple and results in a concise script; unfortunately it also requires that the end user have pycurl installed, which I can't rely on. </p> <p>I've also seen some examples in other posts which rely only on basic libraries, urllib, urllib2, etc., however these generally seem to be quite verbose, which is also something I'd like to avoid. </p> <p>I'm wondering if there are any concise examples which do not require the use of external libraries, and which will be quick and easy for 3rd parties to understand - even if they aren't particularly familiar with python.</p> <p>What I'm using at present looks like,</p> <pre><code> def upload_wav( wavfile, url=None, **kwargs ): """Upload a wav file to the server, return the response.""" class responseCallback: """Store the server response.""" def __init__(self): self.contents='' def body_callback(self, buf): self.contents = self.contents + buf def decode( self ): self.contents = urllib.unquote(self.contents) try: self.contents = simplejson.loads(self.contents) except: return self.contents t = responseCallback() c = pycurl.Curl() c.setopt(c.POST,1) c.setopt(c.WRITEFUNCTION, t.body_callback) c.setopt(c.URL,url) postdict = [ ('userfile',(c.FORM_FILE,wavfile)), #wav file to post ] #If there are extra keyword args add them to the postdict for key in kwargs: postdict.append( (key,kwargs[key]) ) c.setopt(c.HTTPPOST,postdict) c.setopt(c.VERBOSE,verbose) c.perform() c.close() t.decode() return t.contents </code></pre> <p>this isn't exact, but it gives you the general idea. It works great, it's simple for 3rd parties to understand, <em>but</em> it requires pycurl.</p>
5
2009-08-12T05:07:57Z
1,264,540
<p>POSTing a file requires <code>multipart/form-data</code> encoding and, as far as I know, there's no easy way (i.e. one-liner or something) to do this with the stdlib. But as you mentioned, there are plenty of recipes out there. </p> <p>Although they seem verbose, your use case suggests that you can probably just encapsulate it once into a function or class and not worry too much, right? Take a look at the recipe on ActiveState and read the comments for suggestions:</p> <ul> <li><a href="http://code.activestate.com/recipes/146306/" rel="nofollow">Recipe 146306: Http client to POST using multipart/form-data</a></li> </ul> <p>or see the <code>MultiPartForm</code> class in this PyMOTW, which seems pretty reusable:</p> <ul> <li><a href="http://pymotw.com/2/urllib2/" rel="nofollow">PyMOTW: urllib2 - Library for opening URLs.</a></li> </ul> <p>I believe both handle binary files.</p>
4
2009-08-12T06:37:41Z
[ "python", "http", "post", "binary" ]
HTTP POST binary files using Python: concise non-pycurl examples?
1,264,300
<p>I'm interested in writing a short python script which uploads a short binary file (.wav/.raw audio) via a POST request to a remote server.</p> <p>I've done this with pycurl, which makes it very simple and results in a concise script; unfortunately it also requires that the end user have pycurl installed, which I can't rely on. </p> <p>I've also seen some examples in other posts which rely only on basic libraries, urllib, urllib2, etc., however these generally seem to be quite verbose, which is also something I'd like to avoid. </p> <p>I'm wondering if there are any concise examples which do not require the use of external libraries, and which will be quick and easy for 3rd parties to understand - even if they aren't particularly familiar with python.</p> <p>What I'm using at present looks like,</p> <pre><code> def upload_wav( wavfile, url=None, **kwargs ): """Upload a wav file to the server, return the response.""" class responseCallback: """Store the server response.""" def __init__(self): self.contents='' def body_callback(self, buf): self.contents = self.contents + buf def decode( self ): self.contents = urllib.unquote(self.contents) try: self.contents = simplejson.loads(self.contents) except: return self.contents t = responseCallback() c = pycurl.Curl() c.setopt(c.POST,1) c.setopt(c.WRITEFUNCTION, t.body_callback) c.setopt(c.URL,url) postdict = [ ('userfile',(c.FORM_FILE,wavfile)), #wav file to post ] #If there are extra keyword args add them to the postdict for key in kwargs: postdict.append( (key,kwargs[key]) ) c.setopt(c.HTTPPOST,postdict) c.setopt(c.VERBOSE,verbose) c.perform() c.close() t.decode() return t.contents </code></pre> <p>this isn't exact, but it gives you the general idea. It works great, it's simple for 3rd parties to understand, <em>but</em> it requires pycurl.</p>
5
2009-08-12T05:07:57Z
3,547,822
<p>urllib.urlencode doesn't like some kinds of binary data.</p>
0
2010-08-23T13:10:38Z
[ "python", "http", "post", "binary" ]
HTTP POST binary files using Python: concise non-pycurl examples?
1,264,300
<p>I'm interested in writing a short python script which uploads a short binary file (.wav/.raw audio) via a POST request to a remote server.</p> <p>I've done this with pycurl, which makes it very simple and results in a concise script; unfortunately it also requires that the end user have pycurl installed, which I can't rely on. </p> <p>I've also seen some examples in other posts which rely only on basic libraries, urllib, urllib2, etc., however these generally seem to be quite verbose, which is also something I'd like to avoid. </p> <p>I'm wondering if there are any concise examples which do not require the use of external libraries, and which will be quick and easy for 3rd parties to understand - even if they aren't particularly familiar with python.</p> <p>What I'm using at present looks like,</p> <pre><code> def upload_wav( wavfile, url=None, **kwargs ): """Upload a wav file to the server, return the response.""" class responseCallback: """Store the server response.""" def __init__(self): self.contents='' def body_callback(self, buf): self.contents = self.contents + buf def decode( self ): self.contents = urllib.unquote(self.contents) try: self.contents = simplejson.loads(self.contents) except: return self.contents t = responseCallback() c = pycurl.Curl() c.setopt(c.POST,1) c.setopt(c.WRITEFUNCTION, t.body_callback) c.setopt(c.URL,url) postdict = [ ('userfile',(c.FORM_FILE,wavfile)), #wav file to post ] #If there are extra keyword args add them to the postdict for key in kwargs: postdict.append( (key,kwargs[key]) ) c.setopt(c.HTTPPOST,postdict) c.setopt(c.VERBOSE,verbose) c.perform() c.close() t.decode() return t.contents </code></pre> <p>this isn't exact, but it gives you the general idea. It works great, it's simple for 3rd parties to understand, <em>but</em> it requires pycurl.</p>
5
2009-08-12T05:07:57Z
5,488,769
<p>I met similar issue today, after tried both and pycurl and multipart/form-data, I decide to read python httplib/urllib2 source code to find out, I did get one comparably good solution:</p> <ol> <li>set Content-Length header(of the file) before doing post</li> <li>pass a opened file when doing post</li> </ol> <p>Here is the code:</p> <pre><code>import urllib2, os image_path = "png\\01.png" url = 'http://xx.oo.com/webserviceapi/postfile/' length = os.path.getsize(image_path) png_data = open(image_path, "rb") request = urllib2.Request(url, data=png_data) request.add_header('Cache-Control', 'no-cache') request.add_header('Content-Length', '%d' % length) request.add_header('Content-Type', 'image/png') res = urllib2.urlopen(request).read().strip() return res </code></pre> <p>see my blog post: <a href="http://www.2maomao.com/blog/python-http-post-a-binary-file-using-urllib2/" rel="nofollow">http://www.2maomao.com/blog/python-http-post-a-binary-file-using-urllib2/</a></p>
1
2011-03-30T15:52:58Z
[ "python", "http", "post", "binary" ]
HTTP POST binary files using Python: concise non-pycurl examples?
1,264,300
<p>I'm interested in writing a short python script which uploads a short binary file (.wav/.raw audio) via a POST request to a remote server.</p> <p>I've done this with pycurl, which makes it very simple and results in a concise script; unfortunately it also requires that the end user have pycurl installed, which I can't rely on. </p> <p>I've also seen some examples in other posts which rely only on basic libraries, urllib, urllib2, etc., however these generally seem to be quite verbose, which is also something I'd like to avoid. </p> <p>I'm wondering if there are any concise examples which do not require the use of external libraries, and which will be quick and easy for 3rd parties to understand - even if they aren't particularly familiar with python.</p> <p>What I'm using at present looks like,</p> <pre><code> def upload_wav( wavfile, url=None, **kwargs ): """Upload a wav file to the server, return the response.""" class responseCallback: """Store the server response.""" def __init__(self): self.contents='' def body_callback(self, buf): self.contents = self.contents + buf def decode( self ): self.contents = urllib.unquote(self.contents) try: self.contents = simplejson.loads(self.contents) except: return self.contents t = responseCallback() c = pycurl.Curl() c.setopt(c.POST,1) c.setopt(c.WRITEFUNCTION, t.body_callback) c.setopt(c.URL,url) postdict = [ ('userfile',(c.FORM_FILE,wavfile)), #wav file to post ] #If there are extra keyword args add them to the postdict for key in kwargs: postdict.append( (key,kwargs[key]) ) c.setopt(c.HTTPPOST,postdict) c.setopt(c.VERBOSE,verbose) c.perform() c.close() t.decode() return t.contents </code></pre> <p>this isn't exact, but it gives you the general idea. It works great, it's simple for 3rd parties to understand, <em>but</em> it requires pycurl.</p>
5
2009-08-12T05:07:57Z
8,984,371
<p>I know this is an old old stack, but I have a different solution.</p> <p>If you went thru the trouble of building all the magic headers and everything, and are just UPSET that suddenly a binary file can't pass because python library is mean.. you can monkey patch a solution..</p> <pre><code>import httplib class HTTPSConnection(httplib.HTTPSConnection): def _send_output(self, message_body=None): self._buffer.extend(("","")) msg = "\r\n".join(self._buffer) del self._buffer[:] self.send(msg) if message_body is not None: self.send(message_body) httplib.HTTPSConnection = HTTPSConnection </code></pre> <p>If you are using HTTP:// instead of HTTPS:// then replace all instances of HTTPSConnection above with HTTPConnection.</p> <p>Before people get upset with me, YES, this is a BAD SOLUTION, but it is a way to fix existing code you really don't want to re-engineer to do it some other way.</p> <p>Why does this fix it? Go look at the original Python source, httplib.py file.</p>
2
2012-01-24T09:20:18Z
[ "python", "http", "post", "binary" ]
Need to add an element at the start of an iterator in python
1,264,319
<p>I have a program as follows:</p> <pre><code>a=reader.next() if *some condition holds*: #Do some processing and continue the iteration else: #Append the variable a back to the iterator #That is nullify the operation *a=reader.next()* </code></pre> <p>How do I add an element to the start of the iterator? (Or is there an easier way to do this?)</p> <p>EDIT: OK let me put it this way. I need the next element in an iterator without removing it. How do I do this>?</p>
0
2009-08-12T05:14:12Z
1,264,331
<p>Python iterators, as such, have very limited functionality -- no "appending" or anything like that. You'll need to wrap the generic iterator in a wrapper adding that functionality. E.g.:</p> <pre><code>class Wrapper(object): def __init__(self, it): self.it = it self.pushedback = [] def __iter__(self): return self def next(self): if self.pushedback: return self.pushedback.pop() else: return self.it.next() def pushback(self, val): self.pushedback.append(val) </code></pre> <p>This is Python 2.5 (should work in 2.6 too) -- slight variants advised for 2.6 and mandatory for 3.any (use <code>next(self.it)</code> instead of <code>self.it.next()</code> and define <code>__next__</code> instead of <code>next</code>).</p> <p><strong>Edit</strong>: the OP now says what they need is "peek ahead without consuming". Wrapping is still the best option, but an alternative is:</p> <pre><code>import itertools ... o, peek = itertools.tee(o) if isneat(peek.next()): ... </code></pre> <p>this doesn't advance <code>o</code> (remember to advance it if and when you decide you DO want to;-).</p>
5
2009-08-12T05:18:26Z
[ "python", "iterator" ]
Need to add an element at the start of an iterator in python
1,264,319
<p>I have a program as follows:</p> <pre><code>a=reader.next() if *some condition holds*: #Do some processing and continue the iteration else: #Append the variable a back to the iterator #That is nullify the operation *a=reader.next()* </code></pre> <p>How do I add an element to the start of the iterator? (Or is there an easier way to do this?)</p> <p>EDIT: OK let me put it this way. I need the next element in an iterator without removing it. How do I do this>?</p>
0
2009-08-12T05:14:12Z
1,264,369
<p>By design (in general development concepts) iterators are intended to be read-only, and any attempt to change them would break. </p> <p>Alternatively, you could read the iterator backwards, and add it to the end of hte element (which is actually the start :) )? </p>
1
2009-08-12T05:36:53Z
[ "python", "iterator" ]
Need to add an element at the start of an iterator in python
1,264,319
<p>I have a program as follows:</p> <pre><code>a=reader.next() if *some condition holds*: #Do some processing and continue the iteration else: #Append the variable a back to the iterator #That is nullify the operation *a=reader.next()* </code></pre> <p>How do I add an element to the start of the iterator? (Or is there an easier way to do this?)</p> <p>EDIT: OK let me put it this way. I need the next element in an iterator without removing it. How do I do this>?</p>
0
2009-08-12T05:14:12Z
1,265,571
<p>This isn't too close what you asked for, but if you have control over the generator and you don't need to "peek" before the value is generated (and any side effects have occurred), you can use the <a href="http://docs.python.org/reference/expressions.html#generator.send" rel="nofollow"><code>generator.send</code></a> method to tell the generator to repeat the last value it yielded:</p> <pre><code>&gt;&gt;&gt; def a(): ... for x in (1,2,3): ... rcvd = yield x ... if rcvd is not None: ... yield x ... &gt;&gt;&gt; gen = a() &gt;&gt;&gt; gen.send("just checking") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: can't send non-None value to a just-started generator &gt;&gt;&gt; gen.next() 1 &gt;&gt;&gt; gen.send("just checking") 1 &gt;&gt;&gt; gen.next() 2 &gt;&gt;&gt; gen.next() 3 &gt;&gt;&gt; gen.next() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration </code></pre>
0
2009-08-12T11:25:53Z
[ "python", "iterator" ]
Plone navigation with one-language-per-folder site
1,264,421
<p>I am developing a multi-lingual site with Plone. I want to have one language per folder but the Plone navigation UI is causing problems.</p> <p>I have several different folders in my root, such as en, de, nl, etcetera. Inside those folders is the actual content, such as en/news, nl/nieuw, de/nachrichten, etcetera. I have set up Plone Language Tool to pick the language setting from the URL, but the navigation is not showing the correct items.</p> <p>The tabbed navigation is making tabs for the language folders. The path bar is showing <code>"You are here: Home -&gt; en -&gt; news"</code>. How can I change the tabbed navigation and the path bar to show the items inside the language specific folder? I want to have a tab for "news", not for "en" on the English site. The path bar should show <code>"You are here: Home -&gt; news"</code>.</p> <p>I am using Plone 3.2.3 with Plone Language Tool 3.0.2 and LinguaPlone 2.4.</p>
1
2009-08-12T05:56:23Z
1,264,656
<p>Each language folder should implement INavigationRoot. You can set that up by going to the ZMI, finding the folder, and going to the Interfaces tab. There you will find plone.app.layout.navigation.interfaces.INavigationRoot. Click it, and navigation will treat it as the root of the tree. (Note that in Plone 3.3 the support for INavigationRoot has gotten better, so you may want to upgrade. -- edit by Maurits)</p>
4
2009-08-12T07:12:13Z
[ "python", "localization", "multilingual", "plone", "linguaplone" ]
How to run Python egg files directly without installing them?
1,264,447
<p>Is it possible to run Python egg files directly as you can run jar files with Java?</p> <p>For example, with Java you might dos something like: </p> <pre class="lang-sh prettyprint-override"><code>$ java -jar jar-file </code></pre>
30
2009-08-12T06:07:31Z
1,264,625
<p>A <a href="http://peak.telecommunity.com/DevCenter/PythonEggs">python egg</a> is a "a single-file importable distribution format". Which is typically a python package.</p> <p>You can import the package in the egg as long as you know it's name and it's in your path.</p> <p>You can execute a package using the "-m" option and the package name. </p> <p>However, python packages generally do not do anything when executed, and you may get an error. The -c option can be used to run code. (See <a href="http://docs.python.org/using/cmdline.html">http://docs.python.org/using/cmdline.html</a> for details on command line options)</p> <pre><code>&gt; python -m sphinx sphinx is a package and cannot be directly executed &gt; python -c "import &lt;package in an egg&gt;; &lt;function&gt;();" &gt; python -c "import sphinx; print sphinx.package_dir" C:\Python26\lib\site-packages\sphinx-0.6.1-py2.6.egg\sphinx </code></pre>
16
2009-08-12T07:05:03Z
[ "python", "egg" ]
How to run Python egg files directly without installing them?
1,264,447
<p>Is it possible to run Python egg files directly as you can run jar files with Java?</p> <p>For example, with Java you might dos something like: </p> <pre class="lang-sh prettyprint-override"><code>$ java -jar jar-file </code></pre>
30
2009-08-12T06:07:31Z
2,898,358
<p>As of Python 2.6, you can use <code>python some.egg</code> and it will be executed if it includes a module named <code>__main__</code>.</p> <p>For earlier versions of Python, you can use <code>PYTHONPATH=some.egg python -m some module</code>, and <code>somemodule</code> from the egg will be run as the main module. (Note: if you're on Windows, you'd need to do a separate <code>SET PYTHONPATH=some.egg</code>.)</p>
13
2010-05-24T16:08:31Z
[ "python", "egg" ]
How to run Python egg files directly without installing them?
1,264,447
<p>Is it possible to run Python egg files directly as you can run jar files with Java?</p> <p>For example, with Java you might dos something like: </p> <pre class="lang-sh prettyprint-override"><code>$ java -jar jar-file </code></pre>
30
2009-08-12T06:07:31Z
15,497,133
<p>For example, if you want to import the suds module which is available as .egg file:</p> <pre><code>egg_path='/home/shahid/suds_2.4.egg' sys.path.append(egg_path) import suds #... rest of code </code></pre>
4
2013-03-19T10:37:48Z
[ "python", "egg" ]
using the "pefile.py" to get file(.exe) version
1,264,472
<p>I want to use python to get the executable file version, and i know of <a href="http://code.google.com/p/pefile/" rel="nofollow">pefile.py</a></p> <p>how to use it to do this?</p> <p>notes: the executable file may be not complete.</p>
4
2009-08-12T06:16:51Z
1,264,515
<p>The version numbers of Windows programs are stored in the resource section of the program file, not in the PE format header. I'm not familiar with <code>pefile.py</code>, so I don't know whether it directly handles resource sections too. If not, you should be able to find the information you need for that in <a href="http://msdn.microsoft.com/en-us/magazine/cc301808.aspx" rel="nofollow">this MSDN article</a>.</p>
0
2009-08-12T06:30:24Z
[ "python" ]
using the "pefile.py" to get file(.exe) version
1,264,472
<p>I want to use python to get the executable file version, and i know of <a href="http://code.google.com/p/pefile/" rel="nofollow">pefile.py</a></p> <p>how to use it to do this?</p> <p>notes: the executable file may be not complete.</p>
4
2009-08-12T06:16:51Z
1,843,135
<p>Assuming by "executable file version" you mean a) on Windows, b) the information shown in the Properties, Details tab, under "File version", you can retrieve this using the <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a> package with a command like the following:</p> <pre><code>&gt;&gt;&gt; import win32api as w &gt;&gt;&gt; hex(w.GetFileVersionInfo('c:/windows/regedit.exe', '\\')['FileVersionMS']) '0x60000' &gt;&gt;&gt; hex(w.GetFileVersionInfo('c:/windows/regedit.exe', '\\')['FileVersionLS']) '0x17714650' </code></pre> <p>Note that 0x60000 has the major/minor numbers (6.0) and 0x17714650 is the next two, which if taken as two separate words (0x1771 and 0x4650, or 6001 and 18000 in decimal) correspond to the values on my machine, where regedit's version is 6.0.6001.18000.</p>
0
2009-12-03T21:45:25Z
[ "python" ]
using the "pefile.py" to get file(.exe) version
1,264,472
<p>I want to use python to get the executable file version, and i know of <a href="http://code.google.com/p/pefile/" rel="nofollow">pefile.py</a></p> <p>how to use it to do this?</p> <p>notes: the executable file may be not complete.</p>
4
2009-08-12T06:16:51Z
17,579,067
<p>Here's a complete example script that does what you want:</p> <pre><code>import sys def main(pename): from pefile import PE pe = PE(pename) if not 'VS_FIXEDFILEINFO' in pe.__dict__: print "ERROR: Oops, %s has no version info. Can't continue." % (pename) return if not pe.VS_FIXEDFILEINFO: print "ERROR: VS_FIXEDFILEINFO field not set for %s. Can't continue." % (pename) return verinfo = pe.VS_FIXEDFILEINFO filever = (verinfo.FileVersionMS &gt;&gt; 16, verinfo.FileVersionMS &amp; 0xFFFF, verinfo.FileVersionLS &gt;&gt; 16, verinfo.FileVersionLS &amp; 0xFFFF) prodver = (verinfo.ProductVersionMS &gt;&gt; 16, verinfo.ProductVersionMS &amp; 0xFFFF, verinfo.ProductVersionLS &gt;&gt; 16, verinfo.ProductVersionLS &amp; 0xFFFF) print "Product version: %d.%d.%d.%d" % prodver print "File version: %d.%d.%d.%d" % filever if __name__ == '__main__': if len(sys.argv) != 2: sys.stderr.write("ERROR:\n\tSyntax: verinfo &lt;pefile&gt;\n") sys.exit(1) sys.exit(main(sys.argv[1])) </code></pre> <p>The relevant lines being:</p> <pre><code> verinfo = pe.VS_FIXEDFILEINFO filever = (verinfo.FileVersionMS &gt;&gt; 16, verinfo.FileVersionMS &amp; 0xFFFF, verinfo.FileVersionLS &gt;&gt; 16, verinfo.FileVersionLS &amp; 0xFFFF) prodver = (verinfo.ProductVersionMS &gt;&gt; 16, verinfo.ProductVersionMS &amp; 0xFFFF, verinfo.ProductVersionLS &gt;&gt; 16, verinfo.ProductVersionLS &amp; 0xFFFF) </code></pre> <p>all of which happens only after checking that we have something meaningful in these properties.</p>
2
2013-07-10T19:12:47Z
[ "python" ]
Signal Handler exits, but program continue to run?
1,264,766
<p>Apparently when my signal handler exits, my program CONTINUE TO RUN. this is evident by the exception raised even AFTER the "log Done, close now". Can someone explain why this is so? Note the functions have been simplified</p> <pre><code>^Clog Ctrl-C backup State: not_span 328, pos 22, all_cycles 19 backup backup complete, you may force exit now log Done, close now Traceback (most recent call last): File "singleEdger.py", line 219, in &lt;module&gt; mySingleEdger.outputAllCycles() File "singleEdger.py", line 141, in outputAllCycles r = self.returnCycle( self.dfs_tree, self.not_span[self.pos]) File "singleEdger.py", line 72, in returnCycle udfs = nx.Graph(dfs) # The trick is to make it undirected File "/var/lib/python-support/python2.6/networkx/graph.py", line 86, in __init__ convert.from_whatever(data,create_using=self) File "/var/lib/python-support/python2.6/networkx/convert.py", line 76, in from_whatever "Input is not a correct NetworkX graph." networkx.exception.NetworkXError: Input is not a correct NetworkX graph. </code></pre> <p>These are the functions for reference </p> <pre><code> def sigHandler(self, arg1, arg2): out('log', 'Ctrl-C') self.backup() out('log', 'Done, close now') exit() def outputAllCycles(self): while self.pos &lt; len(self.not_span): r = self.returnCycle( self.dfs_tree, self.not_span[self.pos]) if r: self.all_cycles.append( r ) for each in r: # now it's [ (3,4), (5,6) ] each = (sellHash(each[0]), sellHash( each[1]) ) self.outfo.write( each[0] +'\t'+ each[1] ) self.outfo.write( '\n') self.outfo.write( '\n') self.pos += 1 out( "singleEdger", "outputAllCycles done") def backup(self): out( 'backup', 'State: not_span %i, pos %i, all_cycles %i' % ( len(self.not_span), self.pos, len(self.all_cycles)) ) out( 'backup', 'backup complete, you may force exit now') </code></pre>
2
2009-08-12T07:38:17Z
1,264,822
<p>I don't think your code is still running. Despite its position in the code, the exception output is not guaranteed to appear before your final print message. Exception output is going to STDERR, but your print statement is going to STDOUT; both just happen to be writing to the same terminal device in this example. The two are buffered independently so the order of output is not mandated; i.e. you can't infer anything from the relative position of the outputs.</p> <p>You can see the same phenomena with the unit testing framework, if you put print statements into your unit tests.</p>
1
2009-08-12T07:53:38Z
[ "python" ]
Signal Handler exits, but program continue to run?
1,264,766
<p>Apparently when my signal handler exits, my program CONTINUE TO RUN. this is evident by the exception raised even AFTER the "log Done, close now". Can someone explain why this is so? Note the functions have been simplified</p> <pre><code>^Clog Ctrl-C backup State: not_span 328, pos 22, all_cycles 19 backup backup complete, you may force exit now log Done, close now Traceback (most recent call last): File "singleEdger.py", line 219, in &lt;module&gt; mySingleEdger.outputAllCycles() File "singleEdger.py", line 141, in outputAllCycles r = self.returnCycle( self.dfs_tree, self.not_span[self.pos]) File "singleEdger.py", line 72, in returnCycle udfs = nx.Graph(dfs) # The trick is to make it undirected File "/var/lib/python-support/python2.6/networkx/graph.py", line 86, in __init__ convert.from_whatever(data,create_using=self) File "/var/lib/python-support/python2.6/networkx/convert.py", line 76, in from_whatever "Input is not a correct NetworkX graph." networkx.exception.NetworkXError: Input is not a correct NetworkX graph. </code></pre> <p>These are the functions for reference </p> <pre><code> def sigHandler(self, arg1, arg2): out('log', 'Ctrl-C') self.backup() out('log', 'Done, close now') exit() def outputAllCycles(self): while self.pos &lt; len(self.not_span): r = self.returnCycle( self.dfs_tree, self.not_span[self.pos]) if r: self.all_cycles.append( r ) for each in r: # now it's [ (3,4), (5,6) ] each = (sellHash(each[0]), sellHash( each[1]) ) self.outfo.write( each[0] +'\t'+ each[1] ) self.outfo.write( '\n') self.outfo.write( '\n') self.pos += 1 out( "singleEdger", "outputAllCycles done") def backup(self): out( 'backup', 'State: not_span %i, pos %i, all_cycles %i' % ( len(self.not_span), self.pos, len(self.all_cycles)) ) out( 'backup', 'backup complete, you may force exit now') </code></pre>
2
2009-08-12T07:38:17Z
1,270,133
<p>Something else that you should be aware of is that you should avoid lengthy processing (calling <code>backup()</code> indicates a potentially lengthy process) in the signal handler; it's better to set a flag, return from the signal handler and then do your processing. The reason is that (in Python) the signal handler will still be registered and any subsequent signal of the same type will interrupt the signal handler itself, causing it to execute again. This may not be what you'd like to happen.</p> <p>Or you could ignore the signal within the handler, e.g.</p> <pre><code>import signal def sigHandler(sig, frame): oldHandler = signal.signal(sig, signal.SIG_IGN) backup() # lengthy processing here... signal.signal(sig, oldHandler) </code></pre> <p>but note that that will only ignore the same signal - it is still possible to be interrupted by other signals. Is your <code>backup()</code> reentrant?</p> <p><a href="http://www.gnu.org/s/libc/manual/html%5Fnode/Nonreentrancy.html#Nonreentrancy" rel="nofollow">This discussion on reentrancy</a> is relevant, although it's wrt C and Python is a bit different, e.g. signals can not be blocked (unless you use <code>ctypes</code>).</p>
0
2009-08-13T05:12:31Z
[ "python" ]
Signal Handler exits, but program continue to run?
1,264,766
<p>Apparently when my signal handler exits, my program CONTINUE TO RUN. this is evident by the exception raised even AFTER the "log Done, close now". Can someone explain why this is so? Note the functions have been simplified</p> <pre><code>^Clog Ctrl-C backup State: not_span 328, pos 22, all_cycles 19 backup backup complete, you may force exit now log Done, close now Traceback (most recent call last): File "singleEdger.py", line 219, in &lt;module&gt; mySingleEdger.outputAllCycles() File "singleEdger.py", line 141, in outputAllCycles r = self.returnCycle( self.dfs_tree, self.not_span[self.pos]) File "singleEdger.py", line 72, in returnCycle udfs = nx.Graph(dfs) # The trick is to make it undirected File "/var/lib/python-support/python2.6/networkx/graph.py", line 86, in __init__ convert.from_whatever(data,create_using=self) File "/var/lib/python-support/python2.6/networkx/convert.py", line 76, in from_whatever "Input is not a correct NetworkX graph." networkx.exception.NetworkXError: Input is not a correct NetworkX graph. </code></pre> <p>These are the functions for reference </p> <pre><code> def sigHandler(self, arg1, arg2): out('log', 'Ctrl-C') self.backup() out('log', 'Done, close now') exit() def outputAllCycles(self): while self.pos &lt; len(self.not_span): r = self.returnCycle( self.dfs_tree, self.not_span[self.pos]) if r: self.all_cycles.append( r ) for each in r: # now it's [ (3,4), (5,6) ] each = (sellHash(each[0]), sellHash( each[1]) ) self.outfo.write( each[0] +'\t'+ each[1] ) self.outfo.write( '\n') self.outfo.write( '\n') self.pos += 1 out( "singleEdger", "outputAllCycles done") def backup(self): out( 'backup', 'State: not_span %i, pos %i, all_cycles %i' % ( len(self.not_span), self.pos, len(self.all_cycles)) ) out( 'backup', 'backup complete, you may force exit now') </code></pre>
2
2009-08-12T07:38:17Z
12,154,678
<p>If there's a try/except block around the code in progress when ^C is pressed, it won't work because exit() actually raises an exception. See <a href="http://bugs.python.org/issue8021" rel="nofollow">http://bugs.python.org/issue8021</a></p> <p>This holds even if the try block is not in your own code, but in library code you are calling. I noticed this while using urllib2.urlopen in a loop for a robot I'm writing; urllib2's do_open() routine uses try/except around the code that attempts to connect to a URL.</p>
0
2012-08-28T07:30:52Z
[ "python" ]
Python Class Factory to Produce simple Struct-like classes
1,264,833
<p>While investigating Ruby I came across this to create a simple Struct-like class:</p> <pre><code>Person = Struct.new(:forname, :surname) person1 = Person.new('John', 'Doe') puts person1 #&lt;struct Person forname="John", surname="Doe"&gt; </code></pre> <p>Which raised a few Python questions for me. I have written a [VERY] basic clone of this mechanism in Python:</p> <pre><code>def Struct(*args): class NewStruct: def __init__(self): for arg in args: self.__dict__[arg] = None return NewStruct &gt;&gt;&gt; Person = Struct('forename', 'surname') &gt;&gt;&gt; person1 = Person() &gt;&gt;&gt; person2 = Person() &gt;&gt;&gt; person1.forename, person1.surname = 'John','Doe' &gt;&gt;&gt; person2.forename, person2.surname = 'Foo','Bar' &gt;&gt;&gt; person1.forename 'John' &gt;&gt;&gt; person2.forename 'Foo' </code></pre> <ol> <li><p>Is there already a similar mechanism in Python to handle this? (I usually just use dictionaries).</p></li> <li><p>How would I get the <code>Struct()</code> function to create the correct <code>__init__()</code> arguments. (in this case I would like to perform <code>person1 = Person('John', 'Doe')</code> Named Arguments if possible: <code>person1 = Person(surname='Doe', forename='John')</code></p></li> </ol> <p>I Would like, as a matter of interest, to have Question 2 answered even if there is a better Python mechanism to do this.</p>
9
2009-08-12T07:57:57Z
1,264,841
<p>There is <a href="http://docs.python.org/dev/library/collections.html#collections.namedtuple" rel="nofollow">namedtuple</a></p> <pre><code>&gt;&gt;&gt; from collections import namedtuple &gt;&gt;&gt; Person = namedtuple("Person", ("forename", "surname")) &gt;&gt;&gt; john = Person("John", "Doe") &gt;&gt;&gt; john.forename 'John' &gt;&gt;&gt; john.surname 'Doe' </code></pre>
1
2009-08-12T08:00:34Z
[ "python", "struct", "class-factory" ]
Python Class Factory to Produce simple Struct-like classes
1,264,833
<p>While investigating Ruby I came across this to create a simple Struct-like class:</p> <pre><code>Person = Struct.new(:forname, :surname) person1 = Person.new('John', 'Doe') puts person1 #&lt;struct Person forname="John", surname="Doe"&gt; </code></pre> <p>Which raised a few Python questions for me. I have written a [VERY] basic clone of this mechanism in Python:</p> <pre><code>def Struct(*args): class NewStruct: def __init__(self): for arg in args: self.__dict__[arg] = None return NewStruct &gt;&gt;&gt; Person = Struct('forename', 'surname') &gt;&gt;&gt; person1 = Person() &gt;&gt;&gt; person2 = Person() &gt;&gt;&gt; person1.forename, person1.surname = 'John','Doe' &gt;&gt;&gt; person2.forename, person2.surname = 'Foo','Bar' &gt;&gt;&gt; person1.forename 'John' &gt;&gt;&gt; person2.forename 'Foo' </code></pre> <ol> <li><p>Is there already a similar mechanism in Python to handle this? (I usually just use dictionaries).</p></li> <li><p>How would I get the <code>Struct()</code> function to create the correct <code>__init__()</code> arguments. (in this case I would like to perform <code>person1 = Person('John', 'Doe')</code> Named Arguments if possible: <code>person1 = Person(surname='Doe', forename='John')</code></p></li> </ol> <p>I Would like, as a matter of interest, to have Question 2 answered even if there is a better Python mechanism to do this.</p>
9
2009-08-12T07:57:57Z
1,264,843
<p>If you're using Python 2.6, try the standard library <a href="http://docs.python.org/library/collections.html#collections.namedtuple">namedtuple</a> class.</p> <pre><code>&gt;&gt;&gt; from collections import namedtuple &gt;&gt;&gt; Person = namedtuple('Person', ('forename', 'surname')) &gt;&gt;&gt; person1 = Person('John', 'Doe') &gt;&gt;&gt; person2 = Person(forename='Adam', surname='Monroe') &gt;&gt;&gt; person1.forename 'John' &gt;&gt;&gt; person2.surname 'Monroe' </code></pre> <p><strong>Edit:</strong> As per comments, there is a <a href="http://code.activestate.com/recipes/500261/">backport for earlier versions of Python</a></p>
16
2009-08-12T08:01:06Z
[ "python", "struct", "class-factory" ]
Python Class Factory to Produce simple Struct-like classes
1,264,833
<p>While investigating Ruby I came across this to create a simple Struct-like class:</p> <pre><code>Person = Struct.new(:forname, :surname) person1 = Person.new('John', 'Doe') puts person1 #&lt;struct Person forname="John", surname="Doe"&gt; </code></pre> <p>Which raised a few Python questions for me. I have written a [VERY] basic clone of this mechanism in Python:</p> <pre><code>def Struct(*args): class NewStruct: def __init__(self): for arg in args: self.__dict__[arg] = None return NewStruct &gt;&gt;&gt; Person = Struct('forename', 'surname') &gt;&gt;&gt; person1 = Person() &gt;&gt;&gt; person2 = Person() &gt;&gt;&gt; person1.forename, person1.surname = 'John','Doe' &gt;&gt;&gt; person2.forename, person2.surname = 'Foo','Bar' &gt;&gt;&gt; person1.forename 'John' &gt;&gt;&gt; person2.forename 'Foo' </code></pre> <ol> <li><p>Is there already a similar mechanism in Python to handle this? (I usually just use dictionaries).</p></li> <li><p>How would I get the <code>Struct()</code> function to create the correct <code>__init__()</code> arguments. (in this case I would like to perform <code>person1 = Person('John', 'Doe')</code> Named Arguments if possible: <code>person1 = Person(surname='Doe', forename='John')</code></p></li> </ol> <p>I Would like, as a matter of interest, to have Question 2 answered even if there is a better Python mechanism to do this.</p>
9
2009-08-12T07:57:57Z
1,264,923
<p>As others have said, named tuples in Python 2.6/3.x. With older versions, I usually use the Stuff class:</p> <pre><code>class Stuff(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) john = Stuff(forename='John', surname='Doe') </code></pre> <p>This doesn't protect you from mispellings though. There's also a recipe for named tuples on ActiveState:</p> <p><a href="http://code.activestate.com/recipes/500261/" rel="nofollow">http://code.activestate.com/recipes/500261/</a></p>
5
2009-08-12T08:26:24Z
[ "python", "struct", "class-factory" ]
Python Class Factory to Produce simple Struct-like classes
1,264,833
<p>While investigating Ruby I came across this to create a simple Struct-like class:</p> <pre><code>Person = Struct.new(:forname, :surname) person1 = Person.new('John', 'Doe') puts person1 #&lt;struct Person forname="John", surname="Doe"&gt; </code></pre> <p>Which raised a few Python questions for me. I have written a [VERY] basic clone of this mechanism in Python:</p> <pre><code>def Struct(*args): class NewStruct: def __init__(self): for arg in args: self.__dict__[arg] = None return NewStruct &gt;&gt;&gt; Person = Struct('forename', 'surname') &gt;&gt;&gt; person1 = Person() &gt;&gt;&gt; person2 = Person() &gt;&gt;&gt; person1.forename, person1.surname = 'John','Doe' &gt;&gt;&gt; person2.forename, person2.surname = 'Foo','Bar' &gt;&gt;&gt; person1.forename 'John' &gt;&gt;&gt; person2.forename 'Foo' </code></pre> <ol> <li><p>Is there already a similar mechanism in Python to handle this? (I usually just use dictionaries).</p></li> <li><p>How would I get the <code>Struct()</code> function to create the correct <code>__init__()</code> arguments. (in this case I would like to perform <code>person1 = Person('John', 'Doe')</code> Named Arguments if possible: <code>person1 = Person(surname='Doe', forename='John')</code></p></li> </ol> <p>I Would like, as a matter of interest, to have Question 2 answered even if there is a better Python mechanism to do this.</p>
9
2009-08-12T07:57:57Z
1,264,975
<p>If you're running python &lt;2.6 or would like to extend your class to do more stuff, I would suggest using the <code>type()</code> builtin. This has the advantage over your solution in that the setting up of <code>__dict__</code> happens at class creation rather than instantiation. It also doesn't define an <code>__init__</code> method and thus doesn't lead to strange behavior if the class calls <code>__init__</code> again for some reason. For example:</p> <pre><code>def Struct(*args, **kwargs): name = kwargs.pop("name", "MyStruct") kwargs.update(dict((k, None) for k in args)) return type(name, (object,), kwargs) </code></pre> <p>Used like so:</p> <pre><code>&gt;&gt;&gt; MyStruct = Struct("forename", "lastname") </code></pre> <p>Equivalent to:</p> <pre><code>class MyStruct(object): forename = None lastname = None </code></pre> <p>While this:</p> <pre><code>&gt;&gt;&gt; TestStruct = Struct("forename", age=18, name="TestStruct") </code></pre> <p>Is equivalent to:</p> <pre><code>class TestStruct(object): forename = None age = 18 </code></pre> <p><strong>Update</strong></p> <p>Additionally, you can edit this code to very easily prevent assignment of other variables than the ones specificed. Just change the Struct() factory to assign <a href="http://www.python.org/doc/2.5.2/ref/slots.html"><code>__slots__</code></a>.</p> <pre><code>def Struct(*args, **kwargs): name = kwargs.pop("name", "MyStruct") kwargs.update(dict((k, None) for k in args)) kwargs['__slots__'] = kwargs.keys() return type(name, (object,), kwargs) </code></pre>
8
2009-08-12T08:43:38Z
[ "python", "struct", "class-factory" ]
Python Class Factory to Produce simple Struct-like classes
1,264,833
<p>While investigating Ruby I came across this to create a simple Struct-like class:</p> <pre><code>Person = Struct.new(:forname, :surname) person1 = Person.new('John', 'Doe') puts person1 #&lt;struct Person forname="John", surname="Doe"&gt; </code></pre> <p>Which raised a few Python questions for me. I have written a [VERY] basic clone of this mechanism in Python:</p> <pre><code>def Struct(*args): class NewStruct: def __init__(self): for arg in args: self.__dict__[arg] = None return NewStruct &gt;&gt;&gt; Person = Struct('forename', 'surname') &gt;&gt;&gt; person1 = Person() &gt;&gt;&gt; person2 = Person() &gt;&gt;&gt; person1.forename, person1.surname = 'John','Doe' &gt;&gt;&gt; person2.forename, person2.surname = 'Foo','Bar' &gt;&gt;&gt; person1.forename 'John' &gt;&gt;&gt; person2.forename 'Foo' </code></pre> <ol> <li><p>Is there already a similar mechanism in Python to handle this? (I usually just use dictionaries).</p></li> <li><p>How would I get the <code>Struct()</code> function to create the correct <code>__init__()</code> arguments. (in this case I would like to perform <code>person1 = Person('John', 'Doe')</code> Named Arguments if possible: <code>person1 = Person(surname='Doe', forename='John')</code></p></li> </ol> <p>I Would like, as a matter of interest, to have Question 2 answered even if there is a better Python mechanism to do this.</p>
9
2009-08-12T07:57:57Z
1,271,552
<p>This is following up on Cide's answer (and probably only interesting for people who want to dig deeper).</p> <p>I experienced a problem using Cide's updated definition of Struct(), the one using __slots__. The problem is that instances of returned classes have read-only attributes:</p> <pre><code>&gt;&gt;&gt; MS = Struct('forename','lastname') &gt;&gt;&gt; m=MS() &gt;&gt;&gt; m.forename='Jack' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'MyStruct' object attribute 'forename' is read-only </code></pre> <p>Seems that __slots__ is blocking instance-level attributes when there are class attributes of same names. I've tried to overcome this by providing an __init__ method, so instance attributes can be set at object creation time:</p> <pre><code>def Struct1(*args, **kwargs): def init(self): for k,v in kwargs.items(): setattr(self, k, v) name = kwargs.pop("name", "MyStruct") kwargs.update(dict((k, None) for k in args)) return type(name, (object,), {'__init__': init, '__slots__': kwargs.keys()}) </code></pre> <p>As a net effect the constructed class only sees the __init__ method and the __slots__ member, which is working as desired:</p> <pre><code>&gt;&gt;&gt; MS1 = Struct1('forename','lastname') &gt;&gt;&gt; m=MS1() &gt;&gt;&gt; m.forename='Jack' &gt;&gt;&gt; m.forename 'Jack' </code></pre>
2
2009-08-13T12:01:17Z
[ "python", "struct", "class-factory" ]
Python Class Factory to Produce simple Struct-like classes
1,264,833
<p>While investigating Ruby I came across this to create a simple Struct-like class:</p> <pre><code>Person = Struct.new(:forname, :surname) person1 = Person.new('John', 'Doe') puts person1 #&lt;struct Person forname="John", surname="Doe"&gt; </code></pre> <p>Which raised a few Python questions for me. I have written a [VERY] basic clone of this mechanism in Python:</p> <pre><code>def Struct(*args): class NewStruct: def __init__(self): for arg in args: self.__dict__[arg] = None return NewStruct &gt;&gt;&gt; Person = Struct('forename', 'surname') &gt;&gt;&gt; person1 = Person() &gt;&gt;&gt; person2 = Person() &gt;&gt;&gt; person1.forename, person1.surname = 'John','Doe' &gt;&gt;&gt; person2.forename, person2.surname = 'Foo','Bar' &gt;&gt;&gt; person1.forename 'John' &gt;&gt;&gt; person2.forename 'Foo' </code></pre> <ol> <li><p>Is there already a similar mechanism in Python to handle this? (I usually just use dictionaries).</p></li> <li><p>How would I get the <code>Struct()</code> function to create the correct <code>__init__()</code> arguments. (in this case I would like to perform <code>person1 = Person('John', 'Doe')</code> Named Arguments if possible: <code>person1 = Person(surname='Doe', forename='John')</code></p></li> </ol> <p>I Would like, as a matter of interest, to have Question 2 answered even if there is a better Python mechanism to do this.</p>
9
2009-08-12T07:57:57Z
1,275,088
<p>An update of ThomasH's variant:</p> <pre><code>def Struct(*args, **kwargs): def init(self, *iargs, **ikwargs): for k,v in kwargs.items(): setattr(self, k, v) for i in range(len(iargs)): setattr(self, args[i], iargs[i]) for k,v in ikwargs.items(): setattr(self, k, v) name = kwargs.pop("name", "MyStruct") kwargs.update(dict((k, None) for k in args)) return type(name, (object,), {'__init__': init, '__slots__': kwargs.keys()}) </code></pre> <p>This allows parameters (and named parameters) passed into <code>__init__()</code> (without any validation - seems crude):</p> <pre><code>&gt;&gt;&gt; Person = Struct('fname', 'age') &gt;&gt;&gt; person1 = Person('Kevin', 25) &gt;&gt;&gt; person2 = Person(age=42, fname='Terry') &gt;&gt;&gt; person1.age += 10 &gt;&gt;&gt; person2.age -= 10 &gt;&gt;&gt; person1.fname, person1.age, person2.fname, person2.age ('Kevin', 35, 'Terry', 32) &gt;&gt;&gt; </code></pre> <h2>Update</h2> <p>Having a look into how <a href="http://docs.python.org/library/collections.html#collections.namedtuple" rel="nofollow"><code>namedtuple()</code></a> does this in <a href="http://svn.python.org/view/python/trunk/Lib/collections.py?view=markup" rel="nofollow">collections.py</a>. The class is created and expanded as a string and evaluated. Also has support for pickling and so on, etc.</p>
2
2009-08-13T22:54:16Z
[ "python", "struct", "class-factory" ]
Error with time.strptime() and python-twitter
1,265,064
<p>I use <a href="http://code.google.com/p/python-twitter/" rel="nofollow">python-twitter</a> to get the date of a tweet and try to parse it with the <code>time.strptime()</code> function. When I do it interactively, everything works fine. When I call the program from my bash, I get a <code>ValueError</code> saying (for example): </p> <pre><code>time data u'Wed Aug 12 08:43:35 +0000 2009' does not match format '%a %b %d %H:%M:%S +0000 %Y' </code></pre> <p>Code looks like this:</p> <pre><code>api = twitter.Api(username='username', password='pw') user = api.GetUser(username) latest = user.GetStatus() date = latest.GetCreatedAt() date_struct = time.strptime(date, '%a %b %d %H:%M:%S +0000 %Y') </code></pre> <p>which throws the exception mentioned above.</p> <p>It works on the interactive shell:</p> <pre><code>&gt;&gt;&gt; user = api.GetUser('username') &gt;&gt;&gt; latest = user.GetStatus() &gt;&gt;&gt; date = latest.GetCreatedAt() &gt;&gt;&gt; date u'Wed Aug 12 08:15:10 +0000 2009' &gt;&gt;&gt;&gt; struct = time.strptime(date, '%a %b %d %H:%M:%S +0000 %Y') &gt;&gt;&gt;&gt; struct time.struct_time(tm_year=2009, tm_mon=8, tm_mday=12, tm_hour=8, tm_min=15, tm_sec=10, tm_wday=2, tm_yday=224, tm_isdst=-1) </code></pre> <p>Someone any idea why this is happening?</p> <p>I am Using Ubuntu 9.04, Python 2.6.2 and python-twitter 0.6. All files in unicode. </p>
1
2009-08-12T09:07:02Z
1,265,272
<p>Things to try:</p> <p>(1) Is it possible that your interactive session and your "bash" are using different locales? Put <code>print time.strftime(some known struct_time)</code> into your script and see if the day and month come out in a different language.</p> <p>(2) Put <code>print repr(date)</code> in your script to show unambiguously what you are getting from the <code>latest.GetCreatedAt()</code> call.</p>
2
2009-08-12T09:56:15Z
[ "python", "twitter" ]
how can I used the “pefile.py” to get file(.exe) version
1,265,078
<p>I want to used python to get the executed file version, and i know the <a href="http://code.google.com/p/pefile/" rel="nofollow">pefile.py</a></p> <p>how to used it to do this?</p> <p>notes: the executed file may be not completely.</p>
1
2009-08-12T07:30:49Z
1,266,694
<p>I'm not sure that I understand your problem correctly, but if it's something along the lines of using pefile to retrieve the version of a provided executable, then perhaps (taken from [the tutorial][1])</p> <pre><code>import pefile pe = pefile.PE("/path/to/pefile.exe") print pe.dump_info() </code></pre> <p>will provide you with the version information. I have no idea how sensible pefile is when parsing incomplete files, but conjecturing that the version information is somewhere in the header and that pefile uses a generator to read the file, then it should be possible to read the information if the header is parseable.</p>
2
2009-08-12T14:52:21Z
[ "python" ]
how can I used the “pefile.py” to get file(.exe) version
1,265,078
<p>I want to used python to get the executed file version, and i know the <a href="http://code.google.com/p/pefile/" rel="nofollow">pefile.py</a></p> <p>how to used it to do this?</p> <p>notes: the executed file may be not completely.</p>
1
2009-08-12T07:30:49Z
4,572,288
<p>This is the best answer I think you can find:</p> <pre><code>import pefile pe = pefile.PE("/path/to/something.exe") print hex(pe.VS_VERSIONINFO.Length) print hex(pe.VS_VERSIONINFO.Type) print hex(pe.VS_VERSIONINFO.ValueLength) print hex(pe.VS_FIXEDFILEINFO.Signature) print hex(pe.VS_FIXEDFILEINFO.FileFlags) print hex(pe.VS_FIXEDFILEINFO.FileOS) for fileinfo in pe.FileInfo: if fileinfo.Key == 'StringFileInfo': for st in fileinfo.StringTable: for entry in st.entries.items(): print '%s: %s' % (entry[0], entry[1]) if fileinfo.Key == 'VarFileInfo': for var in fileinfo.Var: print '%s: %s' % var.entry.items()[0] </code></pre> <p><a href="http://blog.dkbza.org/2007/02/pefile-parsing-version-information-from.html" rel="nofollow">From Ero Carrera's (the author of <code>pefile.py</code>) own blog</a></p>
4
2010-12-31T21:01:36Z
[ "python" ]
xmpp with python: xmpp.protocol.InvalidFrom: (u'invalid-from', '')
1,265,146
<p>cl = xmpp.Client('myserver.com') if not cl.connect(server=('mysefver.com',5223)): raise IOError('cannot connect to server') cl.RegisterHandler('message',messageHandler) cl.auth('myemail@myserver.com', 'mypassword', 'statusbot') cl.sendInitPresence()</p> <pre><code>msgtext = formatToDo(cal, 'text') message = xmpp.Message('anotheremail@myserver.com', msgtext) message.setAttr('type', 'chat') cl.send(message) </code></pre> <p>I get the following error message when I try to run it:</p> <pre><code>xmpp.protocol.InvalidFrom: (u'invalid-from', '') </code></pre> <p>Why is this happening :( </p>
1
2009-08-12T09:24:56Z
1,265,342
<p>From the XMPP protocol <a href="http://www.isi.edu/in-notes/rfc3920.txt" rel="nofollow">specification</a>:</p> <blockquote> <p>If the value of the 'from' address does not match the hostname represented by the Receiving Server when opening the TCP connection (or any validated domain thereof, such as a validated subdomain of the Receiving Server's hostname or another validated domain hosted by the Receiving Server), then the Authoritative Server MUST generate an stream error condition and terminate both the XML stream and the underlying TCP connection.</p> </blockquote> <p>which basically means, that if the sender is not recognized by the xmpp-server, it'll reply with this message. XMPP supplies a registration mechanism: <a href="http://xmpppy.sourceforge.net/apidocs/xmpp.features-module.html#register" rel="nofollow">xmpp.features.register</a></p>
4
2009-08-12T10:14:40Z
[ "python", "xmpp", "bots" ]
System standard sound in Python
1,265,599
<p>How play standard system sounds from a Python script?</p> <p>I'm writing a GUI program in wxPython that needs to beep on events to attract user's attention, maybe there are functions in wxPython I can utilize?</p>
0
2009-08-12T11:31:22Z
1,265,641
<p>on windows you could use <a href="http://docs.python.org/library/winsound.html#module-winsound" rel="nofollow"><code>winsound</code></a> and I suppose <a href="http://docs.python.org/library/curses.html#curses.beep" rel="nofollow"><code>curses.beep</code></a> on Unix.</p>
3
2009-08-12T11:41:34Z
[ "python", "audio", "wxpython", "system-sounds" ]
System standard sound in Python
1,265,599
<p>How play standard system sounds from a Python script?</p> <p>I'm writing a GUI program in wxPython that needs to beep on events to attract user's attention, maybe there are functions in wxPython I can utilize?</p>
0
2009-08-12T11:31:22Z
1,265,664
<p>from the <a href="http://docs.wxwidgets.org/stable/wx%5Fdialogfunctions.html#wxbell" rel="nofollow">documentation</a>, you could use wx.Bell() function (not tested though)</p>
2
2009-08-12T11:45:51Z
[ "python", "audio", "wxpython", "system-sounds" ]
System standard sound in Python
1,265,599
<p>How play standard system sounds from a Python script?</p> <p>I'm writing a GUI program in wxPython that needs to beep on events to attract user's attention, maybe there are functions in wxPython I can utilize?</p>
0
2009-08-12T11:31:22Z
1,265,745
<p>From the documentation:</p> <blockquote> <p><strong>wxTopLevelWindow::RequestUserAttention</strong></p> <p><strong>void RequestUserAttention(int flags = wxUSER_ATTENTION_INFO)</strong></p> <p>Use a system-dependent way to attract users attention to the window when it is in background.</p> <p>flags may have the value of either wxUSER_ATTENTION_INFO (default) or wxUSER_ATTENTION_ERROR which results in a more drastic action. When in doubt, use the default value.</p> <p>Note that this function should normally be only used when the application is not already in foreground.</p> <p>This function is currently implemented for Win32 where it flashes the window icon in the taskbar, and for wxGTK with task bars supporting it.</p> </blockquote>
1
2009-08-12T12:01:39Z
[ "python", "audio", "wxpython", "system-sounds" ]
Combining two QMainWindows
1,265,646
<p>Good day pythonistas and the rest of the coding crowd,</p> <p>I have two QMainWindows designed and coded separately. I need to:</p> <ol> <li>display first</li> <li>on a button-press close the first window</li> <li>construct and display the second window using the arguments from the first</li> </ol> <p>I have tried to design a third class to control the flow but it does not understand my signal/slot attempt:</p> <pre><code> QtCore.QObject.connect(self.firstWindow,QtCore.SIGNAL("destroyed()"),self.openSecondWindow) </code></pre> <p>Oh gurus, would you enlighten me on some clever way or a witty hack to solve my hardships.</p> <p>Cheers.</p>
0
2009-08-12T11:43:01Z
1,265,882
<p><strong>Answer:</strong></p> <p>I had some trouble with connecting signals recently. I found that it worked when I removed the parentheses from the <code>QtCore.SIGNAL</code>.</p> <p>try changing this:</p> <pre><code>QtCore.SIGNAL("destroyed()") </code></pre> <p>to this:</p> <pre><code>QtCore.SIGNAL("destroyed") </code></pre> <p><strong>Reference:</strong></p> <p>This is because your are using the "old style" signals/slots according to Riverbank. Here's the <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#connecting-signals-and-slots" rel="nofollow">reference to the docs</a>. Specifically, this is the line you're looking for:</p> <pre><code>QtCore.QObject.connect(a, QtCore.SIGNAL("PySig"), pyFunction) </code></pre> <p><strong>Also:</strong></p> <p>Make sure your <code>this.FirstWindow</code> class has this line before your <code>__init__(self...)</code>:</p> <pre><code>__pyqtSignals__ = ( "destroyed" ) </code></pre>
1
2009-08-12T12:32:08Z
[ "python", "pyqt", "signals-slots" ]
Combining two QMainWindows
1,265,646
<p>Good day pythonistas and the rest of the coding crowd,</p> <p>I have two QMainWindows designed and coded separately. I need to:</p> <ol> <li>display first</li> <li>on a button-press close the first window</li> <li>construct and display the second window using the arguments from the first</li> </ol> <p>I have tried to design a third class to control the flow but it does not understand my signal/slot attempt:</p> <pre><code> QtCore.QObject.connect(self.firstWindow,QtCore.SIGNAL("destroyed()"),self.openSecondWindow) </code></pre> <p>Oh gurus, would you enlighten me on some clever way or a witty hack to solve my hardships.</p> <p>Cheers.</p>
0
2009-08-12T11:43:01Z
1,267,211
<p>Well, I have given up on the control class (next time will make the control as the first thing and only after that make the windows)</p> <p>Instead have mated the windows by injecting the seconds' constructor seed into the body of the first one and then <code>self.close()</code> the young mother. So tragic.</p>
0
2009-08-12T16:21:03Z
[ "python", "pyqt", "signals-slots" ]
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
1,265,696
<p>with positive integers you could use <a href="http://docs.python.org/library/stdtypes.html#str.isdigit"><code>.isdigit</code></a>:</p> <pre><code>&gt;&gt;&gt; '16'.isdigit() True </code></pre> <p>it doesn't work with negative integers though. suppose you could try the following:</p> <pre><code>&gt;&gt;&gt; s = '-17' &gt;&gt;&gt; s.startswith('-') and s[1:].isdigit() True </code></pre> <p>it won't work with <code>'16.0'</code> format, which is similar to <code>int</code> casting in this sense.</p> <p><strong>edit</strong>:</p> <pre><code>def check_int(s): if s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit() </code></pre>
235
2009-08-12T11:52:09Z
[ "python", "string", "integer" ]
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
1,265,709
<p>Use a regular expression:</p> <pre><code>import re def RepresentsInt(s): return re.match(r"[-+]?\d+$", s) is not None </code></pre> <p>If you must accept decimal fractions also:</p> <pre><code>def RepresentsInt(s): return re.match(r"[-+]?\d+(\.0*)?$", s) is not None </code></pre> <p>For improved performance if you're doing this often, compile the regular expression only once using <code>re.compile()</code>.</p>
16
2009-08-12T11:54:20Z
[ "python", "string", "integer" ]
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
1,265,925
<p>Greg Hewgill's approach was missing a few components: the leading "^" to only match the start of the string, and compiling the re beforehand. But this approach will allow you to avoid a try: exept:</p> <pre><code>import re INT_RE = re.compile(r"^[-]?\d+$") def RepresentsInt(s): return INT_RE.match(str(s)) is not None </code></pre> <p>I would be interested why you are trying to avoid try: except?</p>
3
2009-08-12T12:37:28Z
[ "python", "string", "integer" ]
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
1,267,145
<p>If you're really just annoyed at using <code>try/except</code>s all over the place, please just write a helper function:</p> <pre><code>def RepresentsInt(s): try: int(s) return True except ValueError: return False &gt;&gt;&gt; print RepresentsInt("+123") True &gt;&gt;&gt; print RepresentsInt("10.0") False </code></pre> <p>It's going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.</p>
137
2009-08-12T16:05:28Z
[ "python", "string", "integer" ]
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
4,894,182
<p>The proper RegEx solution would combine the ideas of Greg Hewgill and Nowell, but not use a global variable. You can accomplish this by attaching an attribute to the method. Also, I know that it is frowned upon to put imports in a method, but what I'm going for is a "lazy module" effect like <a href="http://peak.telecommunity.com/DevCenter/Importing#lazy-imports">http://peak.telecommunity.com/DevCenter/Importing#lazy-imports</a></p> <p><strong>edit:</strong> My favorite test so far is use exclusively methods of the String object.</p> <pre><code>#!/usr/bin/env python def isInteger(i): i = str(i) return i=='0' or (i if i.find('..') &gt; -1 else i.lstrip('-+').rstrip('0').rstrip('.')).isdigit() def isIntegre(i): import re if not hasattr(isIntegre, '_re'): print "I compile only once. Remove this line when you are confedent in that." isIntegre._re = re.compile(r"[-+]?\d+(\.0*)?$") return isIntegre._re.match(str(i)) is not None # When executed directly run Unit Tests if __name__ == '__main__': for o in [ # integers 0, 1, -1, 1.0, -1.0, '0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0', # non-integers 1.1, -1.1, '1.1', '-1.1', '+1.1', '1.1.1', '1.1.0', '1.0.1', '1.0.0', '1.0.', '1..0', '1..', '0.0.', '0..0', '0..', 'one', object(), (1,2,3), [1,2,3], {'one':'two'} ]: # Notice the integre uses 're' (intended to be humorous) integer = ('an integer' if isInteger(o) else 'NOT an integer') integre = ('an integre' if isIntegre(o) else 'NOT an integre') if isinstance(o, str): print "%s is %s is %s" % (("'%s'" % (o,)), integer, integre) else: print "%s is %s is %s" % (o, integer, integre) </code></pre> <p>And for the less adventurous member of the class, here is the output:</p> <pre><code>I compile only once. Remove this line when you are confedent in that. 0 is an integer is an integre 1 is an integer is an integre -1 is an integer is an integre 1.0 is an integer is an integre -1.0 is an integer is an integre '0' is an integer is an integre '0.' is an integer is an integre '0.0' is an integer is an integre '1' is an integer is an integre '-1' is an integer is an integre '+1' is an integer is an integre '1.0' is an integer is an integre '-1.0' is an integer is an integre '+1.0' is an integer is an integre 1.1 is NOT an integer is NOT an integre -1.1 is NOT an integer is NOT an integre '1.1' is NOT an integer is NOT an integre '-1.1' is NOT an integer is NOT an integre '+1.1' is NOT an integer is NOT an integre '1.1.1' is NOT an integer is NOT an integre '1.1.0' is NOT an integer is NOT an integre '1.0.1' is NOT an integer is NOT an integre '1.0.0' is NOT an integer is NOT an integre '1.0.' is NOT an integer is NOT an integre '1..0' is NOT an integer is NOT an integre '1..' is NOT an integer is NOT an integre '0.0.' is NOT an integer is NOT an integre '0..0' is NOT an integer is NOT an integre '0..' is NOT an integer is NOT an integre 'one' is NOT an integer is NOT an integre &lt;object object at 0xb786c4b8&gt; is NOT an integer is NOT an integre (1, 2, 3) is NOT an integer is NOT an integre [1, 2, 3] is NOT an integer is NOT an integre {'one': 'two'} is NOT an integer is NOT an integre </code></pre>
7
2011-02-04T03:07:14Z
[ "python", "string", "integer" ]
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
9,654,638
<p>Uh.. Try this: </p> <pre><code>def int_check(a): if int(a) == a: return True else: return False </code></pre> <p>This works if you don't put a string that's not a number.</p> <p>And also (I forgot to put the number check part. ), there is a function checking if the string is a number or not. It is str.isdigit(). Here's an example: </p> <pre><code>a = 2 a.isdigit() </code></pre> <p>If you call a.isdigit(), it will return True. </p>
-3
2012-03-11T11:48:12Z
[ "python", "string", "integer" ]
Python: Check if a string represents an int, Without using Try/Except?
1,265,665
<p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre><code>is_int('3.14') = False is_int('-7') = True </code></pre>
138
2009-08-12T11:46:13Z
9,859,202
<p>You know, I've found (and I've tested this over and over) that try/except does not perform all that well, for whatever reason. I frequently try several ways of doing things, and I don't think I've ever found a method that uses try/except to perform the best of those tested, in fact it seems to me those methods have usually come out close to the worst, if not the worst. Not in every case, but in many cases. I know a lot of people say it's the "Pythonic" way, but that's one area where I part ways with them. To me, it's neither very performant nor very elegant, so, I tend to only use it for error trapping and reporting.</p> <p>I was going to gripe that PHP, perl, ruby, C, and even the freaking shell have simple functions for testing a string for integer-hood, but due diligence in verifying those assumptions tripped me up! Apparently this lack is a common sickness. </p> <p>Here's a quick and dirty edit of Richard's post:</p> <pre><code>import sys, time, re g_intRegex = re.compile(r"[-+]?\d+(\.0*)?$") testvals = [ # integers 0, 1, -1, 1.0, -1.0, '0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0', '06', # non-integers 1.1, -1.1, '1.1', '-1.1', '+1.1', '1.1.1', '1.1.0', '1.0.1', '1.0.0', '1.0.', '1..0', '1..', '0.0.', '0..0', '0..', 'one', object(), (1,2,3), [1,2,3], {'one':'two'}, # with spaces ' 0 ', ' 0.', ' .0','.01 ' ] def isInt_try(v): try: i = int(v) except: return False return True def isInt_str(v): v = str(v).strip() return v=='0' or (v if v.find('..') &gt; -1 else v.lstrip('-+').rstrip('0').rstrip('.')).isdigit() def isInt_re(v): import re if not hasattr(isInt_re, 'intRegex'): isInt_re.intRegex = re.compile(r"[-+]?\d+(\.0*)?$") return isInt_re.intRegex.match(str(v).strip()) is not None def isInt_re2(v): return g_intRegex.match(str(v).strip()) is not None def timeFunc(func, times): t1 = time.time() for n in xrange(times): for v in testvals: r = func(v) t2 = time.time() return t2 - t1 def testFuncs(funcs): for func in funcs: sys.stdout.write( "\t%s\t|" % func.__name__) print for v in testvals: sys.stdout.write("%s" % str(v)) for func in funcs: sys.stdout.write( "\t\t%s\t|" % func(v)) print if __name__ == '__main__': print print "tests.." testFuncs((isInt_try, isInt_str, isInt_re, isInt_re2)) print print "timings.." print "isInt_try: %6.4f" % timeFunc(isInt_try, 10000) print "isInt_str: %6.4f" % timeFunc(isInt_str, 10000) print "isInt_re: %6.4f" % timeFunc(isInt_re, 10000) print "isInt_re2: %6.4f" % timeFunc(isInt_re2, 10000) </code></pre> <p>Here's the interesting part of the output:</p> <pre><code>timings.. isInt_try: 1.2454 isInt_str: 0.7878 isInt_re: 1.5731 isInt_re2: 0.8087 </code></pre> <p>As you can see, the string method is the fastest. It is almost twice as fast as the regex method that avoids relying on any globals, and more than half again faster than the try:except method. The regex method that relies on some globals (or, well, module attributes) is a close second.</p> <p>I think of these, my choice would be</p> <pre><code>isInt = isInt_str </code></pre> <p>But eh.. this is copying and recopying and recopying the entire string! (And yet it's the fastest method!?) A C method could scan it Once Through, and be done. A C method that scans the string once through would be the Right Thing to do, I think? I guess there might be some string encoding issues to deal with.. Anyway, I'd try and work one out now, but I'm out of time for this. =( Maybe I'll come back to it later. </p>
40
2012-03-25T09:41:13Z
[ "python", "string", "integer" ]