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 f... | 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 f... | 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')]
</c... | 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 f... | 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 f... | 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>... | 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 bind... | 0 | 2009-08-11T15:50:17Z | 1,278,998 | <pre><code>import py_streamhtmlparser
parser = py_streamhtmlparser.HtmlParser()
html = """<html><body><a href='http://google.com' id=100>
link</a><p><a href=heise.de/></body></html>"""
cur_attr = cur_value = None
for index, character in enumerate(html):
parser.... | 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] = a... | 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>... | 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] = a... | 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] = a... | 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] = a... | 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()).saf... | 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 tr... | 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 d... | 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 tr... | 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>
... | 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, val... | 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, val... | 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 exce... | 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, val... | 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>sy... | 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 <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
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.
>&g... | 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 t... | 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 <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
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.
>&g... | 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 <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
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.
>&g... | 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 vari... | 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><... | 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 specif... | 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... | 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 variab... | 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 depende... | 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 suppor... | 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.... | 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 c... | 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 li... | 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 c... | 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... | 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 c... | 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://free... | 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 u... | 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</cod... | 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 u... | 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 = Te... | 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 u... | 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>... | 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 u... | 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):
... | 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 u... | 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
... | 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 u... | 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 u... | 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]
... | 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()
... | 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()
... | 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 a... | 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... | 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_rev... | 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... | 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... | 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:
+------+ ... | 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%5Fpytho... | 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... | 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 n... | 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 n... | 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, i... | 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 n... | 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 a... | 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 n... | 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 ... | 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 sol... | 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>unic... | 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 sim... | 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>>>> 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¼"... | 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 ... | 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('<div/>');
$doc['div']->append('<ul></ul>');
$doc['div ul'] = '<li>1</li><li>2</li&g... | 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:
d... | 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></p... | 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:
d... | 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 conditi... | 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 requ... | 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 a... | 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 c... | 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... | 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 c... | 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 ... | 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 c... | 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 c... | 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>He... | 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 c... | 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 HT... | 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?... | 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):
... | 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?... | 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?... | 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... | 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. ... | 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 ... | 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" ... | 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. ... | 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... | 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>>>... | 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_FIXEDFILE... | 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 back... | 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. T... | 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 back... | 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 handle... | 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 back... | 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 ... | 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 #<struct Person forname="John", surname="Doe">
</code></pre>
<p>Which raised a few Python questions for me. I have written... | 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>>>> from collections import namedtuple
>>> Person = namedtuple("Person", ("forename", "surname"))
>>> john = Person("John", "Doe")
>>> john.f... | 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 #<struct Person forname="John", surname="Doe">
</code></pre>
<p>Which raised a few Python questions for me. I have written... | 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>>>> from collections import namedtuple
>>> Person = namedtuple('Person', ('forename', 'surname'))
>>> person1 = Person... | 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 #<struct Person forname="John", surname="Doe">
</code></pre>
<p>Which raised a few Python questions for me. I have written... | 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 mispelling... | 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 #<struct Person forname="John", surname="Doe">
</code></pre>
<p>Which raised a few Python questions for me. I have written... | 9 | 2009-08-12T07:57:57Z | 1,264,975 | <p>If you're running python <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>_... | 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 #<struct Person forname="John", surname="Doe">
</code></pre>
<p>Which raised a few Python questions for me. I have written... | 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>>>> MS =... | 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 #<struct Person forname="John", surname="Doe">
</code></pre>
<p>Which raised a few Python questions for me. I have written... | 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():
setat... | 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 (fo... | 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 scrip... | 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 pr... | 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 ... | 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, '... | 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 valida... | 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>... | 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 trie... | 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... | 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 trie... | 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>>>> '16'.isdigit()
True
</code></pre>
<p>it doesn't work with negative integers though. suppose you could try the following:</p>
<pre><code>>>> s = '-... | 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 performa... | 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 no... | 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
>>> print RepresentsInt("+123")
True
>>> print Rep... | 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.tel... | 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 no... | -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... | 40 | 2012-03-25T09:41:13Z | [
"python",
"string",
"integer"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.