title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
Python: Lock directory access under windows | 394,439 | <p>I'd like to be able to lock directory access under windows.
The following code work greatly with file or directory under POSIX system:</p>
<pre><code>def flock(fd, blocking=False, exclusive=False):
if exclusive:
flags = fcntl.LOCK_EX
else:
flags = fcntl.LOCK_SH
if not blocking:
flags |= fcntl.LOCK_NB
fcntl.flock(fd, flags)
</code></pre>
<p>But I only find a way to perform lock access for file, not directory with the following code:</p>
<pre><code>def flock(fd, blocking=False, exclusive=False):
if blocking:
flags = msvcrt.LK_NBLCK
else:
flags = msvcrt.LK_LOCK
msvcrt.locking(fd.fileno(), flags, os.path.getsize(fd.name))
</code></pre>
<p>Have you got any idea how to improve this code and be able to lock directory access ?</p>
<p>Bertrand</p>
| 3 | 2008-12-26T23:16:23Z | 395,212 | <p>I don't believe it's possible to use flock() on directories in windows. <a href="http://us2.php.net/flock" rel="nofollow">PHPs docs</a> on flock() indicate that it won't even work on FAT32 filesystems.</p>
<p>On the other hand, Windows already tends to not allow you to delete files/directories if any files are still open. This, plus maybe using ACLs intelligently, might get you a 95% equivalent solution.</p>
| 1 | 2008-12-27T17:53:45Z | [
"python",
"windows",
"directory",
"locking"
] |
Python POST data using mod_wsgi | 394,465 | <p>This must be a very simple question, but I don't seem to be able to figure out.</p>
<p>I'm using apache + mod_wsgi to host my python application, and I'd like to get the post content submitted in one of the forms -however, neither the environment values, nor sys.stdin contains any of this data. Mind giving me a quick hand?</p>
<p>Edit:
Tried already: </p>
<ul>
<li>environ["CONTENT_TYPE"] = 'application/x-www-form-urlencoded' (no data)</li>
<li>environ["wsgi.input"] seems a plausible way, however, both environ["wsgi.input"].read(), and environ["wsgi.input"].read(-1) returns an empty string (yes, content has been posted, and environ["request_method"] = "post"</li>
</ul>
| 14 | 2008-12-26T23:35:59Z | 394,543 | <p><a href="http://www.python.org/dev/peps/pep-0333/">PEP 333</a> says <a href="http://www.python.org/dev/peps/pep-0333/#input-and-error-streams">you must read environ['wsgi.input']</a>.</p>
<p>I just saved the following code and made apache's mod_wsgi run it. It works.</p>
<p>You must be doing something wrong.</p>
<pre><code>from pprint import pformat
def application(environ, start_response):
# show the environment:
output = ['<pre>']
output.append(pformat(environ))
output.append('</pre>')
#create a simple form:
output.append('<form method="post">')
output.append('<input type="text" name="test">')
output.append('<input type="submit">')
output.append('</form>')
if environ['REQUEST_METHOD'] == 'POST':
# show form data as received by POST:
output.append('<h1>FORM DATA</h1>')
output.append(pformat(environ['wsgi.input'].read()))
# send results
output_len = sum(len(line) for line in output)
start_response('200 OK', [('Content-type', 'text/html'),
('Content-Length', str(output_len))])
return output
</code></pre>
| 21 | 2008-12-27T01:22:33Z | [
"python",
"mod-wsgi"
] |
Python POST data using mod_wsgi | 394,465 | <p>This must be a very simple question, but I don't seem to be able to figure out.</p>
<p>I'm using apache + mod_wsgi to host my python application, and I'd like to get the post content submitted in one of the forms -however, neither the environment values, nor sys.stdin contains any of this data. Mind giving me a quick hand?</p>
<p>Edit:
Tried already: </p>
<ul>
<li>environ["CONTENT_TYPE"] = 'application/x-www-form-urlencoded' (no data)</li>
<li>environ["wsgi.input"] seems a plausible way, however, both environ["wsgi.input"].read(), and environ["wsgi.input"].read(-1) returns an empty string (yes, content has been posted, and environ["request_method"] = "post"</li>
</ul>
| 14 | 2008-12-26T23:35:59Z | 1,038,071 | <p>Be aware that technically speaking calling read() or read(-1) on wsgi.input is a violation of the WSGI specification even though Apache/mod_wsgi allows it. This is because the WSGI specification requires that a valid length argument be supplied. The WSGI specification also says you shouldn't read more data than is specified by the CONTENT_LENGTH.</p>
<p>So, the code above may work in Apache/mod_wsgi but it isn't portable WSGI code and will fail on some other WSGI implementations. To be correct, determine request content length and supply that value to read().</p>
| 13 | 2009-06-24T12:31:53Z | [
"python",
"mod-wsgi"
] |
Is there a simple way in Python to create a file which can be written to in one thread and read in a different one? | 394,500 | <p>In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second?</p>
<p>Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file.</p>
<p>Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together.</p>
| 2 | 2008-12-27T00:25:16Z | 394,503 | <p>You should use the <a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue</a> module for sharing sequential data across threads. You would have to make a file-like Queue subclass, where .read and .write mutually block each other, with a buffer in-between.</p>
<p>OTOH, I wonder why the first thread can't write to the real file in the first place.</p>
| 4 | 2008-12-27T00:32:30Z | [
"python"
] |
Is there a simple way in Python to create a file which can be written to in one thread and read in a different one? | 394,500 | <p>In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second?</p>
<p>Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file.</p>
<p>Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together.</p>
| 2 | 2008-12-27T00:25:16Z | 394,508 | <p>I'm not clear what you're trying to do ehre. This sounds like a job for a regular old pipe, which is a file-like object. I'm guessing, however, that you mean you're got a stream of some other sort.</p>
<p>It also sounds a lot like what you want is a python <a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue</a>, or maybe a <a href="http://docs.python.org/library/tempfile.html#module-tempfile" rel="nofollow">tempfile</a>.</p>
| 0 | 2008-12-27T00:36:28Z | [
"python"
] |
Is there a simple way in Python to create a file which can be written to in one thread and read in a different one? | 394,500 | <p>In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second?</p>
<p>Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file.</p>
<p>Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together.</p>
| 2 | 2008-12-27T00:25:16Z | 394,548 | <p>I think there is something wrong in the design if you already have a file-like object if you want your data to end up in the subprocess. You should then arrange that they get written into the subprocess in the first place, rather than having them written into something else file-like first. Whoever is writing the data should allow the flexibility to specify the output stream, and that should be the subprocess pipe.</p>
<p>Alternatively, if the writer insists on creating its own stream object, you should let it complete writing, and only then start the subprocess, feeding it from the result of first write. E.g. if it is a StringIO object, take its value after writing, and write it into the pipe; no need for thread synchronization here.</p>
| 1 | 2008-12-27T01:32:40Z | [
"python"
] |
Is there a simple way in Python to create a file which can be written to in one thread and read in a different one? | 394,500 | <p>In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second?</p>
<p>Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file.</p>
<p>Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together.</p>
| 2 | 2008-12-27T00:25:16Z | 394,549 | <p>Use <a href="http://docs.python.org/library/shutil.html#shutil.copyfileobj" rel="nofollow"><code>shutil</code>'s <code>copyfileobj()</code></a> function:</p>
<pre><code>import shutil
import subprocess
proc = subprocess.Popen([...], stdin=subprocess.PIPE)
my_input = get_filelike_object('from a place not given in the question')
shutil.copyfileobj(my_input, proc.stdin)
</code></pre>
<p>No need to use threads.</p>
| 2 | 2008-12-27T01:33:04Z | [
"python"
] |
SDL or PyGame international input | 394,618 | <p>So basically, how is non-western input handled in SDL or OpenGL games or applications? Googling for it reveals <a href="http://sdl-im.csie.net/" rel="nofollow">http://sdl-im.csie.net/</a> but that doesn't seem to be maintained or available anymore. Just to view the page I had to use the <a href="http://74.125.95.132/search?q=cache:PYYdG1HpzZ0J:sdl-im.csie.net/+sdl+input&hl=en&ct=clnk&cd=6&gl=us&client=firefox-a" rel="nofollow">Google cache</a>. </p>
<p>To clarify, I'm not having any kind of issue in terms of the application displaying text in non-western languages to users. This is a solved problem. There are many unicode fonts available, and many different ways to process text into glyphs and then into display surfaces. </p>
<p>I run a-foul in the opposite direction. Even if my program could safely handle text data in any arbitrary encoding, there's no way for users to actually type their name if it happens to include a character that requires more than one keystroke to produce. </p>
| 5 | 2008-12-27T03:23:33Z | 400,158 | <p>Usually everybody just ends up using unicode for the text to internationalize their apps.</p>
<p>I don't remember SDL or neither OpenGL implemented anything that'd prevent you from implementing international input/output, except they are neither helping at that.</p>
<p>There's utilities over OpenGL you can use to render with .ttf fonts.</p>
| 1 | 2008-12-30T12:32:25Z | [
"python",
"internationalization",
"sdl"
] |
SDL or PyGame international input | 394,618 | <p>So basically, how is non-western input handled in SDL or OpenGL games or applications? Googling for it reveals <a href="http://sdl-im.csie.net/" rel="nofollow">http://sdl-im.csie.net/</a> but that doesn't seem to be maintained or available anymore. Just to view the page I had to use the <a href="http://74.125.95.132/search?q=cache:PYYdG1HpzZ0J:sdl-im.csie.net/+sdl+input&hl=en&ct=clnk&cd=6&gl=us&client=firefox-a" rel="nofollow">Google cache</a>. </p>
<p>To clarify, I'm not having any kind of issue in terms of the application displaying text in non-western languages to users. This is a solved problem. There are many unicode fonts available, and many different ways to process text into glyphs and then into display surfaces. </p>
<p>I run a-foul in the opposite direction. Even if my program could safely handle text data in any arbitrary encoding, there's no way for users to actually type their name if it happens to include a character that requires more than one keystroke to produce. </p>
| 5 | 2008-12-27T03:23:33Z | 685,280 | <p>You are interested in <a href="http://www.libsdl.org/docs/html/sdlenableunicode.html" rel="nofollow"><code>SDL_EnableUNICODE()</code></a>. When you enable unicode translation, you can use the <code>unicode</code> field of <code>SDL_keysym</code> structure to get the unicode character based on the key user typed.</p>
<p>Generally I think whenever you do text input (e.g. user focuses on a textbox) you should use the unicode field and not attempt to do translation yourself.</p>
<p><a href="https://opentibia.svn.sf.net/svnroot/opentibia/yatc/trunk/main.cpp" rel="nofollow">Here's</a> something we did in YATC. Not really a shining example of how things should be done, but demonstrates the use of the <code>unicode</code> field.</p>
| 3 | 2009-03-26T10:56:18Z | [
"python",
"internationalization",
"sdl"
] |
SDL or PyGame international input | 394,618 | <p>So basically, how is non-western input handled in SDL or OpenGL games or applications? Googling for it reveals <a href="http://sdl-im.csie.net/" rel="nofollow">http://sdl-im.csie.net/</a> but that doesn't seem to be maintained or available anymore. Just to view the page I had to use the <a href="http://74.125.95.132/search?q=cache:PYYdG1HpzZ0J:sdl-im.csie.net/+sdl+input&hl=en&ct=clnk&cd=6&gl=us&client=firefox-a" rel="nofollow">Google cache</a>. </p>
<p>To clarify, I'm not having any kind of issue in terms of the application displaying text in non-western languages to users. This is a solved problem. There are many unicode fonts available, and many different ways to process text into glyphs and then into display surfaces. </p>
<p>I run a-foul in the opposite direction. Even if my program could safely handle text data in any arbitrary encoding, there's no way for users to actually type their name if it happens to include a character that requires more than one keystroke to produce. </p>
| 5 | 2008-12-27T03:23:33Z | 930,794 | <p>It appears there is now a Google summer of code project on this topic, for both <a href="http://ocghop.appspot.com/student%5Fproject/show/google/gsoc2009/sdl/t124024854219" rel="nofollow">X11</a> and for <a href="http://socghop.appspot.com/student%5Fproject/show/google/gsoc2009/sdl/t124024853848" rel="nofollow">MacOS X</a></p>
| 0 | 2009-05-30T22:40:57Z | [
"python",
"internationalization",
"sdl"
] |
Override a method at instance level | 394,770 | <p>Is there a way in Python to override a class method at instance level?
For example:</p>
<pre><code>class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!
</code></pre>
| 33 | 2008-12-27T07:12:07Z | 394,779 | <p>Yes, it's possible:</p>
<pre><code>class Dog:
def bark(self):
print "Woof"
def new_bark(self):
print "Woof Woof"
foo = Dog()
funcType = type(Dog.bark)
# "Woof"
foo.bark()
# replace bark with new_bark for this object only
foo.bark = funcType(new_bark, foo, Dog)
foo.bark()
# "Woof Woof"
</code></pre>
| 80 | 2008-12-27T07:35:02Z | [
"python"
] |
Override a method at instance level | 394,770 | <p>Is there a way in Python to override a class method at instance level?
For example:</p>
<pre><code>class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!
</code></pre>
| 33 | 2008-12-27T07:12:07Z | 394,788 | <pre><code>class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
def new_bark():
print "WoOoOoF!!"
boby.bark = new_bark
boby.bark() # WoOoOoF!!
</code></pre>
<p>You can use the <code>boby</code> variable inside the function if you need. Since you are overriding the method just for this one instance object, this way is simpler and has exactly the same effect as using <code>self</code>.</p>
| 20 | 2008-12-27T07:46:45Z | [
"python"
] |
Override a method at instance level | 394,770 | <p>Is there a way in Python to override a class method at instance level?
For example:</p>
<pre><code>class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!
</code></pre>
| 33 | 2008-12-27T07:12:07Z | 394,939 | <p>Since functions are first class objects in Python you can pass them while initializing your class object or override it anytime for a given class instance:</p>
<pre><code>class Dog:
def __init__(self, barkmethod=None):
self.bark=self.barkp
if barkmethod:
self.bark=barkmethod
def barkp(self):
print "woof"
d=Dog()
print "calling original bark"
d.bark()
def barknew():
print "wooOOOoof"
d1=Dog(barknew)
print "calling the new bark"
d1.bark()
def barknew1():
print "nowoof"
d1.bark=barknew1
print "calling another new"
d1.bark()
</code></pre>
<p>and the results are </p>
<pre><code>calling original bark
woof
calling the new bark
wooOOOoof
calling another new
nowoof
</code></pre>
| 0 | 2008-12-27T12:06:04Z | [
"python"
] |
Override a method at instance level | 394,770 | <p>Is there a way in Python to override a class method at instance level?
For example:</p>
<pre><code>class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!
</code></pre>
| 33 | 2008-12-27T07:12:07Z | 395,006 | <p>Please do not do this as shown. You code becomes unreadable when you monkeypatch an instance to be different from the class.</p>
<p>You cannot debug monkeypatched code.</p>
<p>When you find a bug in <code>boby</code> and <code>print type(boby)</code>, you'll see that (a) it's a Dog, but (b) for some obscure reason it doesn't bark correctly. This is a nightmare. Do not do it.</p>
<p>Please do this instead.</p>
<pre><code>class Dog:
def bark(self):
print "WOOF"
class BobyDog( Dog ):
def bark( self ):
print "WoOoOoF!!"
otherDog= Dog()
otherDog.bark() # WOOF
boby = BobyDog()
boby.bark() # WoOoOoF!!
</code></pre>
| 23 | 2008-12-27T13:44:45Z | [
"python"
] |
Override a method at instance level | 394,770 | <p>Is there a way in Python to override a class method at instance level?
For example:</p>
<pre><code>class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!
</code></pre>
| 33 | 2008-12-27T07:12:07Z | 395,031 | <p>Though I liked the inheritance idea from S. Lott and agree with the 'type(a)' thing, but since functions too have accessible attributes, I think the it can be managed this way:</p>
<pre><code>class Dog:
def __init__(self, barkmethod=None):
self.bark=self.barkp
if barkmethod:
self.bark=barkmethod
def barkp(self):
"""original bark"""
print "woof"
d=Dog()
print "calling original bark"
d.bark()
print "that was %s\n" % d.bark.__doc__
def barknew():
"""a new type of bark"""
print "wooOOOoof"
d1=Dog(barknew)
print "calling the new bark"
d1.bark()
print "that was %s\n" % d1.bark.__doc__
def barknew1():
"""another type of new bark"""
print "nowoof"
d1.bark=barknew1
print "another new"
d1.bark()
print "that was %s\n" % d1.bark.__doc__
</code></pre>
<p>and the output is :</p>
<pre><code>calling original bark
woof
that was original bark
calling the new bark
wooOOOoof
that was a new type of bark
another new
nowoof
that was another type of new bark
</code></pre>
| -2 | 2008-12-27T14:10:24Z | [
"python"
] |
Override a method at instance level | 394,770 | <p>Is there a way in Python to override a class method at instance level?
For example:</p>
<pre><code>class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!
</code></pre>
| 33 | 2008-12-27T07:12:07Z | 16,977,672 | <p>Dear this is not overriding you are just calling the same function twice with the object. Basically overriding is related to more than one class. when same signature method exist in different classes then which function your are calling this decide the object who calls this. Overriding is possible in python when you make more than one classes are writes the same functions and one thing more to share that overloading is not allowed in python</p>
| -2 | 2013-06-07T06:30:39Z | [
"python"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 394,814 | <p>Yes, it was <a href="https://mail.python.org/pipermail/python-dev/2005-September/056846.html">added</a> in version 2.5.<br>
The syntax is:</p>
<pre><code>a if condition else b
</code></pre>
<p>First <code>condition</code> is evaluated, then either <code>a</code> or <code>b</code> is returned based on the <a href="https://en.wikipedia.org/wiki/Boolean_data_type">Boolean</a> value of <code>condition</code><br>
If <code>condition</code> evaluates to <em>True</em> <code>a</code> is returned, else <code>b</code> is returned. </p>
<p>For example:</p>
<pre><code>>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
</code></pre>
<p>Keep in mind that it's frowned upon by some Pythonistas for several reasons:</p>
<ul>
<li>The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the order).</li>
<li>Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).</li>
<li>Stylistic reasons.</li>
</ul>
<p>If you're having trouble remembering the order, then remember that if you read it out loud, you (almost) say what you mean. For example, <code>x = 4 if b > 8 else 9</code> is read aloud as <code>x will be 4 if b is greater than 8 otherwise 9</code>.</p>
<p>Official documentation:</p>
<ul>
<li><a href="https://docs.python.org/3/reference/expressions.html#conditional-expressions">Conditional expressions</a></li>
<li><a href="https://docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator">Is there an equivalent of Câs â?:â ternary operator?</a></li>
</ul>
| 3,110 | 2008-12-27T08:44:19Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 394,815 | <p>From <a href="https://docs.python.org/3/reference/expressions.html#conditional-expressions">the documentation</a>:</p>
<blockquote>
<p>Conditional expressions (sometimes called a âternary operatorâ) have the lowest priority of all Python operations.</p>
<p>The expression <code>x if C else y</code> first evaluates the condition, <em>C</em> (<em>not x</em>); if <em>C</em> is true, <em>x</em> is evaluated and its value is returned; otherwise, <em>y</em> is evaluated and its value is returned.</p>
<p>See <a href="https://www.python.org/dev/peps/pep-0308/">PEP 308</a> for more details about conditional expressions.</p>
</blockquote>
<p>New since version 2.5.</p>
| 70 | 2008-12-27T08:44:23Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 394,887 | <p>For versions prior to 2.5, there's the trick:</p>
<pre><code>[expression] and [on_true] or [on_false]
</code></pre>
<p>It can give wrong results when <code>on_true</code>
has a false boolean value.<sup>1</sup><br>
Although it does have the benefit of evaluating expressions left to right, which is clearer in my opinion.</p>
<p><sub>1. <a href="http://docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator">Is there an equivalent of Câs â?:â ternary operator?</a></sub></p>
| 152 | 2008-12-27T10:48:27Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 470,376 | <p>You can index into a tuple:</p>
<pre><code>(falseValue, trueValue)[test]
</code></pre>
<p><code>test</code> needs to return <em>True</em> or <em>False</em>.<br>
It might be safer to always implement it as:</p>
<pre><code>(falseValue, trueValue)[test == True]
</code></pre>
<p>or you can use the built-in <a href="https://docs.python.org/3.3/library/functions.html#bool"><code>bool()</code></a> to assure a <a href="https://en.wikipedia.org/wiki/Boolean_data_type">Boolean</a> value:</p>
<pre><code>(falseValue, trueValue)[bool(<expression>)]
</code></pre>
| 359 | 2009-01-22T18:58:09Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 1,855,173 | <p>@up:</p>
<p>Unfortunately, the</p>
<pre><code>(falseValue, trueValue)[test]
</code></pre>
<p>solution doesn't have short-circuit behaviour; thus both falseValue and trueValue are evaluated regardless of the condition. This could be suboptimal or even buggy (i.e. both trueValue and falseValue could be methods and have side-effects).</p>
<p>One solution to this would be</p>
<pre><code>(falseValue, trueValue)[test]()
</code></pre>
<p>(execution delayed until the winner is known ;)), but it introduces inconsistency between callable and non-callable objects. In addition, it doesn't solve the case when using properties.</p>
<p>And so the story goes - choosing between 3 mentioned solutions is a trade-off between having the short-circuit feature, using at least python 2.5 (IMHO not a problem anymore) and not being prone to "trueValue-evaluates-to-false" errors.</p>
| 40 | 2009-12-06T11:51:50Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 2,919,360 | <p><em>expression1</em> if <em>condition</em> else <em>expression2</em></p>
<pre><code>>>> a = 1
>>> b = 2
>>> 1 if a > b else -1
-1
>>> 1 if a > b else -1 if a < b else 0
-1
</code></pre>
| 79 | 2010-05-27T07:56:06Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 10,314,837 | <p>For Python 2.5 and newer there is a specific syntax:</p>
<pre><code>[on_true] if [cond] else [on_false]
</code></pre>
<p>In older Pythons a ternary operator is not implemented but it's possible to simulate it.</p>
<pre><code>cond and on_true or on_false
</code></pre>
<p>Though, there is a potential problem, which if <code>cond</code> evaluates to <code>True</code> and <code>on_true</code> evaluates to <code>False</code> then <code>on_false</code> is returned instead of <code>on_true</code>. If you want this behavior the method is OK, otherwise use this:</p>
<pre><code>{True: on_true, False: on_false}[cond is True] # is True, not == True
</code></pre>
<p>which can be wrapped by:</p>
<pre><code>def q(cond, on_true, on_false)
return {True: on_true, False: on_false}[cond is True]
</code></pre>
<p>and used this way:</p>
<pre><code>q(cond, on_true, on_false)
</code></pre>
<p>It is compatible with all Python versions.</p>
| 30 | 2012-04-25T11:40:11Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 14,321,907 | <p>You might often find</p>
<pre><code>cond and on_true or on_false
</code></pre>
<p>but this lead to problem when on_true == 0</p>
<pre><code>>>> x = 0
>>> print x == 0 and 0 or 1
1
>>> x = 1
>>> print x == 0 and 0 or 1
1
</code></pre>
<p>where you would expect for a normal ternary operator this result</p>
<pre><code>>>> x = 0
>>> print 0 if x == 0 else 1
0
>>> x = 1
>>> print 0 if x == 0 else 1
1
</code></pre>
| 19 | 2013-01-14T15:56:09Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 20,093,702 | <p>Simulating the python ternary operator.</p>
<p>For example</p>
<pre><code>a, b, x, y = 1, 2, 'a greather than b', 'b greater than a'
result = (lambda:y, lambda:x)[a > b]()
</code></pre>
<p>output:</p>
<pre><code>'b greater than a'
</code></pre>
| 10 | 2013-11-20T10:44:12Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 23,518,594 | <pre><code>In [1]: a = 1 if False else 0
In [2]: a
Out[2]: 0
In [3]: b = 1 if True else 0
In [4]: b
Out[4]: 1
</code></pre>
| 6 | 2014-05-07T13:02:06Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 30,052,371 | <p>An operator for a conditional expression in Python was added in 2006 as part of <a href="https://www.python.org/dev/peps/pep-0308/">Python Enhancement Proposal 308</a>. Its form differ from common <code>?:</code> operator and it's:</p>
<pre><code><expression1> if <condition> else <expression2>
</code></pre>
<p>which is equivalent to:</p>
<pre><code>if <condition>: <expression1> else: <expression2>
</code></pre>
<p>Here is example:</p>
<pre><code>result = x if a > b else y
</code></pre>
<p>Another syntax which can be used (compatible with versions before 2.5):</p>
<pre><code>result = (lambda:y, lambda:x)[a > b]()
</code></pre>
<p>where operands are <a href="https://en.wikipedia.org/wiki/Lazy_evaluation">lazily evaluated</a>.</p>
<p>Another way is by indexing a tuple (which isn't consistent with the conditional operator of most other languages):</p>
<pre><code>result = (y, x)[a > b]
</code></pre>
<p>or explicitly constructed dictionary:</p>
<pre><code>result = {True: x, False: y}[a > b]
</code></pre>
<p>Another (less reliable), but simpler method is to use <code>and</code> and <code>or</code> operators:</p>
<pre><code>result = (a > b) and x or y
</code></pre>
<p>however this won't work if <code>x</code> would be <code>False</code>.</p>
<p>As possible workaround is to make <code>x</code> and <code>y</code> lists or tuples as in the following:</p>
<pre><code>result = ((a > b) and [x] or [y])[0]
</code></pre>
<p>or:</p>
<pre><code>result = ((a > b) and (x,) or (y,))[0]
</code></pre>
<p>If you're working with dictionaries, instead of using a ternary conditional, you can take advantage of <a href="https://docs.python.org/3/library/stdtypes.html#dict.get"><code>get(key, default)</code></a>, for example:</p>
<pre><code>shell = os.environ.get('SHELL', "/bin/sh")
</code></pre>
<p><sup>Source: <a href="https://en.wikipedia.org/wiki/%3F:#Python">?: in Python at Wikipedia</a></sup></p>
| 33 | 2015-05-05T12:00:09Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 31,429,254 | <p>Absolutely, and it is incredibly easy to understand. </p>
<pre><code>general syntax : first_expression if bool_expression== true else second_expression
Example: x= 3 if 3 > 2 else 4
# assigns 3 to x if the boolean expression evaluates to true or 4 if it is false
</code></pre>
| 11 | 2015-07-15T11:33:41Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 33,765,206 | <blockquote>
<h1>Does Python have a ternary conditional operator?</h1>
</blockquote>
<p>Yes. From the <a href="https://docs.python.org/reference/grammar.html" rel="nofollow">grammar file</a>:</p>
<pre><code>test: or_test ['if' or_test 'else' test] | lambdef
</code></pre>
<p>The part of interest is:</p>
<pre><code>or_test ['if' or_test 'else' test]
</code></pre>
<p>So, a ternary conditional operation is of the form:</p>
<pre><code>expression1 if expression2 else expression3
</code></pre>
<p><code>expression3</code> will be lazily evaluated (that is, evaluated only if <code>expression2</code> is false in a boolean context). And because of the recursive definition, you can chain them indefinitely (though it may considered bad style.)</p>
<pre><code>expression1 if expression2 else expression3 if expression4 else expression5 # and so on
</code></pre>
<h3>A note on usage:</h3>
<p>Note that every <code>if</code> must be followed with an <code>else</code>. People learning list comprehensions and generator expressions may find this to be a difficult lesson to learn - the following will not work, as Python expects a third expression for an else:</p>
<pre><code>[expression1 if expression2 for element in iterable]
# ^-- need an else here
</code></pre>
<p>which raises a <code>SyntaxError: invalid syntax</code>.
So the above is either an incomplete piece of logic (perhaps the user expects a no-op in the false condition) or what may be intended is to use expression2 as a filter - notes that the following is legal Python:</p>
<pre><code>[expression1 for element in iterable if expression2]
</code></pre>
<p><code>expression2</code> works as a filter for the list comprehension, and is <em>not</em> a ternary conditional operator.</p>
<h3>Alternative syntax for a more narrow case:</h3>
<p>You may find it somewhat painful to write the following:</p>
<pre><code>expression1 if expression1 else expression2
</code></pre>
<p><code>expression1</code> will have to be evaluated twice with the above usage. It can limit redundancy if it is simply a local variable. However, a common and performant Pythonic idiom for this use-case is to use <code>or</code>'s shortcutting behavior:</p>
<pre><code>expression1 or expression2
</code></pre>
<p>which is equivalent in semantics. Note that some style-guides may limit this usage on the grounds of clarity - it does pack a lot of meaning into very little syntax.</p>
| 12 | 2015-11-17T19:14:33Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 36,041,689 | <p>Yes.</p>
<pre><code>>>> b = (True if 5 > 4 else False)
>>> print b
True
</code></pre>
| 2 | 2016-03-16T16:36:22Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 37,155,553 | <p>More a tip than an answer (don't need to repeat the obvious for the hundreth time), but I sometimes use it as a oneliner shortcut in such constructs:</p>
<pre><code>if conditionX:
print('yes')
else:
print('nah')
</code></pre>
<p>, becomes:</p>
<pre><code>print('yes') if conditionX else print('nah')
</code></pre>
<p>Some (many :) may frown upon it as unpythonic (even, ruby-ish :), but I personally find it more natural - i.e. how you'd express it normally, plus a bit more visually appealing in large blocks of code.</p>
| 5 | 2016-05-11T07:13:31Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Does Python have a ternary conditional operator? | 394,809 | <p>If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?</p>
| 2,655 | 2008-12-27T08:32:18Z | 39,067,220 | <h2><strong>Ternary Operator in different programming Languages</strong></h2>
<p>Here I just try to show some important difference in <code>ternary operator</code> between a couple of programming languages.</p>
<blockquote>
<p><em>Ternary Operator in Javascript</em></p>
</blockquote>
<pre><code>var a = true ? 1 : 0;
# 1
var b = false ? 1 : 0;
# 0
</code></pre>
<blockquote>
<p><em>Ternary Operator in Ruby</em></p>
</blockquote>
<pre><code>a = if true then 1 else 0 end
# 1
b = if false then 1 else 0 end
# 0
</code></pre>
<blockquote>
<p><em>Ternary operator in Scala</em></p>
</blockquote>
<pre><code>val a = true ? 1 | 0
# 1
val b = false ? 1 | 0
# 0
</code></pre>
<blockquote>
<p><em>Ternary operator in R programming</em></p>
</blockquote>
<pre><code>a <- if (TRUE) 1 else 0
# 1
b <- if (FALSE) 1 else 0
# 0
</code></pre>
<blockquote>
<p><em>Ternary operator in Python</em></p>
</blockquote>
<pre><code>a = 1 if True else 0
# 1
b = 1 if False else 0
# 0
</code></pre>
<p>Now you can see the beauty of python language. its highly readable and maintainable.</p>
| 3 | 2016-08-21T17:56:26Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] |
Python threads stack_size and segfaults | 394,895 | <p>A web crawler script that spawns at most 500 threads and each thread basically requests for certain data served from the remote server, which each server's reply is different in content and size from others.</p>
<p>i'm setting stack_size as 756K's for threads</p>
<pre><code>threading.stack_size(756*1024)
</code></pre>
<p>which enables me to have the sufficient number of threads required and complete most of the jobs and requests. But as some servers' responses are bigger than others, and when a thread gets that kind of response, script dies with SIGSEGV. </p>
<p>stack_sizes more than 756K makes it impossible to have the required number of threads at the same time. </p>
<p>any suggestions on how can i continue with given stack_size without crashes?
and how can i get the current used stack_size of any given thread? </p>
| 2 | 2008-12-27T11:03:00Z | 394,916 | <p><strong>Why</strong> on earth are you spawning 500 threads? That seems like a terrible idea! </p>
<p>Remove threading completely, use an event loop to do the crawling. Your program will be faster, simpler, and easier to maintain.</p>
<p>Lots of threads waiting for network won't make your program <em>wait faster</em>. Instead, collect all open sockets in a list and run a loop where you check if any of them has data available.</p>
<p>I recommend using <a href="http://twistedmatrix.com">Twisted</a> - It is an event-driven networking engine. It is very flexile, secure, scalable and very stable (no segfaults).</p>
<p>You could also take a look at <a href="http://scrapy.org/">Scrapy</a> - It is a web crawling and screen scraping framework written in Python/Twisted. It is still under heavy development, but maybe you can take some ideas.</p>
| 9 | 2008-12-27T11:28:29Z | [
"python",
"multithreading",
"segmentation-fault",
"stack-size"
] |
Download from EXPLOSM.net Comics Script [Python] | 394,978 | <p>So I wrote this short script (correct word?) to download the comic images from explosm.net comics because I somewhat-recently found out about it and I want to...put it on my iPhone...3G.</p>
<p>It works fine and all. urllib2 for getting webpage html and urllib for image.retrieve()</p>
<p><strong><em>Why I posted this on SO: how do I optimize this code? Would REGEX (regular expressions) make it faster? Is it an internet limitation? Poor algorithm...?</em></strong></p>
<p>Any improvements in speed or <strong><em>general code aesthetics</em></strong> would be greatly appreciated "answers".</p>
<p><i>Thank you.</i></p>
<p><i>--------------------------------CODE----------------------------------</i></p>
<pre><code>import urllib, urllib2
def LinkConvert(string_link):
for eachLetter in string_link:
if eachLetter == " ":
string_link = string_link[:string_link.find(eachLetter)] + "%20" + string_link[string_link.find(eachLetter)+1:]
return string_link
start = 82
end = 1506
matchingStart = """<img alt="Cyanide and Happiness, a daily webcomic" src="http://www.explosm.net/db/files/Comics/"""
matchingEnd = """></"""
link = "http://www.explosm.net/comics/"
for pageNum in range(start,start+7):
req = urllib2.Request(link+`pageNum`)
response = urllib2.urlopen(req)
page = response.read()
istart1 = page.find(matchingStart)
iend1 = page.find(matchingEnd, istart1)
newString1 = page[istart1 : iend1]
istart2 = newString1.find("src=")+4
iend2 = len(newString1)
final = newString1[istart2 +1 : iend2 -1]
final = LinkConvert(final)
try:
image = urllib.URLopener()
image.retrieve(final, `pageNum` + ".jpg")
except:
print "Uh-oh! " + `pageNum` + " was not downloaded!"
print `pageNum` + " completed..."
</code></pre>
<p><i>By the way, this is Python 2.5 code, not 3.0 but you bet I have all the features of PYthon 3.0 greatly studied and played around with before or right after New Year (after College Apps - YAY! ^-^)</i></p>
| 1 | 2008-12-27T13:09:10Z | 395,014 | <p>I suggest using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> to do the parsing, it would simplifly your code a lot.</p>
<p>But since you already got it working this way maybe you won't want to touch it until it breaks (page format changes).</p>
| 0 | 2008-12-27T13:54:56Z | [
"python",
"scripting",
"download",
"urllib"
] |
Download from EXPLOSM.net Comics Script [Python] | 394,978 | <p>So I wrote this short script (correct word?) to download the comic images from explosm.net comics because I somewhat-recently found out about it and I want to...put it on my iPhone...3G.</p>
<p>It works fine and all. urllib2 for getting webpage html and urllib for image.retrieve()</p>
<p><strong><em>Why I posted this on SO: how do I optimize this code? Would REGEX (regular expressions) make it faster? Is it an internet limitation? Poor algorithm...?</em></strong></p>
<p>Any improvements in speed or <strong><em>general code aesthetics</em></strong> would be greatly appreciated "answers".</p>
<p><i>Thank you.</i></p>
<p><i>--------------------------------CODE----------------------------------</i></p>
<pre><code>import urllib, urllib2
def LinkConvert(string_link):
for eachLetter in string_link:
if eachLetter == " ":
string_link = string_link[:string_link.find(eachLetter)] + "%20" + string_link[string_link.find(eachLetter)+1:]
return string_link
start = 82
end = 1506
matchingStart = """<img alt="Cyanide and Happiness, a daily webcomic" src="http://www.explosm.net/db/files/Comics/"""
matchingEnd = """></"""
link = "http://www.explosm.net/comics/"
for pageNum in range(start,start+7):
req = urllib2.Request(link+`pageNum`)
response = urllib2.urlopen(req)
page = response.read()
istart1 = page.find(matchingStart)
iend1 = page.find(matchingEnd, istart1)
newString1 = page[istart1 : iend1]
istart2 = newString1.find("src=")+4
iend2 = len(newString1)
final = newString1[istart2 +1 : iend2 -1]
final = LinkConvert(final)
try:
image = urllib.URLopener()
image.retrieve(final, `pageNum` + ".jpg")
except:
print "Uh-oh! " + `pageNum` + " was not downloaded!"
print `pageNum` + " completed..."
</code></pre>
<p><i>By the way, this is Python 2.5 code, not 3.0 but you bet I have all the features of PYthon 3.0 greatly studied and played around with before or right after New Year (after College Apps - YAY! ^-^)</i></p>
| 1 | 2008-12-27T13:09:10Z | 395,026 | <p>I would suggest using <a href="http://scrapy.org/" rel="nofollow">Scrapy</a> for your page fetching and <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> for the parsing. This would make your code a lot simpler.</p>
<p>Whether you want to change your existing code that works to these alternatives is up to you. If not, then regular expressions would probably simplify your code somewhat. I'm not sure what effect it would have on performance.</p>
| 7 | 2008-12-27T14:04:48Z | [
"python",
"scripting",
"download",
"urllib"
] |
Download from EXPLOSM.net Comics Script [Python] | 394,978 | <p>So I wrote this short script (correct word?) to download the comic images from explosm.net comics because I somewhat-recently found out about it and I want to...put it on my iPhone...3G.</p>
<p>It works fine and all. urllib2 for getting webpage html and urllib for image.retrieve()</p>
<p><strong><em>Why I posted this on SO: how do I optimize this code? Would REGEX (regular expressions) make it faster? Is it an internet limitation? Poor algorithm...?</em></strong></p>
<p>Any improvements in speed or <strong><em>general code aesthetics</em></strong> would be greatly appreciated "answers".</p>
<p><i>Thank you.</i></p>
<p><i>--------------------------------CODE----------------------------------</i></p>
<pre><code>import urllib, urllib2
def LinkConvert(string_link):
for eachLetter in string_link:
if eachLetter == " ":
string_link = string_link[:string_link.find(eachLetter)] + "%20" + string_link[string_link.find(eachLetter)+1:]
return string_link
start = 82
end = 1506
matchingStart = """<img alt="Cyanide and Happiness, a daily webcomic" src="http://www.explosm.net/db/files/Comics/"""
matchingEnd = """></"""
link = "http://www.explosm.net/comics/"
for pageNum in range(start,start+7):
req = urllib2.Request(link+`pageNum`)
response = urllib2.urlopen(req)
page = response.read()
istart1 = page.find(matchingStart)
iend1 = page.find(matchingEnd, istart1)
newString1 = page[istart1 : iend1]
istart2 = newString1.find("src=")+4
iend2 = len(newString1)
final = newString1[istart2 +1 : iend2 -1]
final = LinkConvert(final)
try:
image = urllib.URLopener()
image.retrieve(final, `pageNum` + ".jpg")
except:
print "Uh-oh! " + `pageNum` + " was not downloaded!"
print `pageNum` + " completed..."
</code></pre>
<p><i>By the way, this is Python 2.5 code, not 3.0 but you bet I have all the features of PYthon 3.0 greatly studied and played around with before or right after New Year (after College Apps - YAY! ^-^)</i></p>
| 1 | 2008-12-27T13:09:10Z | 395,066 | <p><a href="http://refactormycode.com/" rel="nofollow">refactormycode</a> may be a more appropriate web site for these "let's improve this code" type of discussions.</p>
| 3 | 2008-12-27T14:53:42Z | [
"python",
"scripting",
"download",
"urllib"
] |
Download from EXPLOSM.net Comics Script [Python] | 394,978 | <p>So I wrote this short script (correct word?) to download the comic images from explosm.net comics because I somewhat-recently found out about it and I want to...put it on my iPhone...3G.</p>
<p>It works fine and all. urllib2 for getting webpage html and urllib for image.retrieve()</p>
<p><strong><em>Why I posted this on SO: how do I optimize this code? Would REGEX (regular expressions) make it faster? Is it an internet limitation? Poor algorithm...?</em></strong></p>
<p>Any improvements in speed or <strong><em>general code aesthetics</em></strong> would be greatly appreciated "answers".</p>
<p><i>Thank you.</i></p>
<p><i>--------------------------------CODE----------------------------------</i></p>
<pre><code>import urllib, urllib2
def LinkConvert(string_link):
for eachLetter in string_link:
if eachLetter == " ":
string_link = string_link[:string_link.find(eachLetter)] + "%20" + string_link[string_link.find(eachLetter)+1:]
return string_link
start = 82
end = 1506
matchingStart = """<img alt="Cyanide and Happiness, a daily webcomic" src="http://www.explosm.net/db/files/Comics/"""
matchingEnd = """></"""
link = "http://www.explosm.net/comics/"
for pageNum in range(start,start+7):
req = urllib2.Request(link+`pageNum`)
response = urllib2.urlopen(req)
page = response.read()
istart1 = page.find(matchingStart)
iend1 = page.find(matchingEnd, istart1)
newString1 = page[istart1 : iend1]
istart2 = newString1.find("src=")+4
iend2 = len(newString1)
final = newString1[istart2 +1 : iend2 -1]
final = LinkConvert(final)
try:
image = urllib.URLopener()
image.retrieve(final, `pageNum` + ".jpg")
except:
print "Uh-oh! " + `pageNum` + " was not downloaded!"
print `pageNum` + " completed..."
</code></pre>
<p><i>By the way, this is Python 2.5 code, not 3.0 but you bet I have all the features of PYthon 3.0 greatly studied and played around with before or right after New Year (after College Apps - YAY! ^-^)</i></p>
| 1 | 2008-12-27T13:09:10Z | 395,469 | <p>urllib2 uses blocking calls, and that's the main reason for performance.
You should use a non-blocking library (like scrapy) or use multiple threads for the retrieval. I have never used scrapy (so I can't tell on that option), but threading in python is really easy and straightforward.</p>
| 0 | 2008-12-27T21:56:24Z | [
"python",
"scripting",
"download",
"urllib"
] |
templatetags don't refresh | 395,053 | <p>I have two templatetags in my app which contain forms which show entries in db. When I alter data or add new entry to db, the forms show the old data. While in admin panel everything is correct (updated). When I restart the server (I mean <code>manage.py runserver</code>) forms show updated db entries. How to make the forms show updated data?<br /><br />
regards<br />
chriss<br /><br />
<b>EDIT:</b><br />
file: <code>templatetags/oceny_tags.py</code>:<br /></p>
<pre><code>from django import template
from oceny.formularze import StudentFormularz, PrzeniesStudentaFormularz
def dodajStudenta(req):
formularz = StudentFormularz(req)
return {'formularz': formularz}
def przeniesStudenta(req):
formularz = PrzeniesStudentaFormularz(req)
return {'formularz': formularz}
register = template.Library()
register.inclusion_tag('oceny/formularz_studenta.html', takes_context = False)(dodajStudenta)
register.inclusion_tag('oceny/formularz_przenies_studenta.html', takes_context = False)(przeniesStudenta)
</code></pre>
<p>file: <code>views.py</code> view responsible for handling forms:</p>
<pre><code>def zarzadzajStudentami(request):
formularze = ['dodaj_studenta', 'przenies_studenta']
req = {}
for e in formularze:
req[e] = None
if request.POST:
req[request.POST['formularz']] = request.POST
if request.POST['formularz'] == 'dodaj_studenta':
formularz = StudentFormularz(request.POST)
if formularz.is_valid():
formularz.save()
return HttpResponseRedirect(reverse('zarzadzaj_studentami'))
elif request.POST['formularz'] == 'przenies_studenta':
formularz = PrzeniesStudentaFormularz(request.POST)
if formularz.is_valid():
student = Student.objects.get(id = request.POST['student'])
grupa = Grupa.objects.get(id = request.POST['grupa'])
student.grupa = grupa
student.save()
return HttpResponseRedirect(reverse('zarzadzaj_studentami'))
return render_to_response('oceny/zarzadzaj_studentami.html', {'req': req}, context_instance = RequestContext(request))
</code></pre>
<p>I realize that the code may be lame in some cases. I would appreciate any other hints how to write things better.</p>
| 0 | 2008-12-27T14:43:10Z | 395,087 | <p>Are you using some kind of cache system? It could be that.</p>
| 0 | 2008-12-27T15:24:04Z | [
"python",
"django",
"django-templates",
"templatetags"
] |
templatetags don't refresh | 395,053 | <p>I have two templatetags in my app which contain forms which show entries in db. When I alter data or add new entry to db, the forms show the old data. While in admin panel everything is correct (updated). When I restart the server (I mean <code>manage.py runserver</code>) forms show updated db entries. How to make the forms show updated data?<br /><br />
regards<br />
chriss<br /><br />
<b>EDIT:</b><br />
file: <code>templatetags/oceny_tags.py</code>:<br /></p>
<pre><code>from django import template
from oceny.formularze import StudentFormularz, PrzeniesStudentaFormularz
def dodajStudenta(req):
formularz = StudentFormularz(req)
return {'formularz': formularz}
def przeniesStudenta(req):
formularz = PrzeniesStudentaFormularz(req)
return {'formularz': formularz}
register = template.Library()
register.inclusion_tag('oceny/formularz_studenta.html', takes_context = False)(dodajStudenta)
register.inclusion_tag('oceny/formularz_przenies_studenta.html', takes_context = False)(przeniesStudenta)
</code></pre>
<p>file: <code>views.py</code> view responsible for handling forms:</p>
<pre><code>def zarzadzajStudentami(request):
formularze = ['dodaj_studenta', 'przenies_studenta']
req = {}
for e in formularze:
req[e] = None
if request.POST:
req[request.POST['formularz']] = request.POST
if request.POST['formularz'] == 'dodaj_studenta':
formularz = StudentFormularz(request.POST)
if formularz.is_valid():
formularz.save()
return HttpResponseRedirect(reverse('zarzadzaj_studentami'))
elif request.POST['formularz'] == 'przenies_studenta':
formularz = PrzeniesStudentaFormularz(request.POST)
if formularz.is_valid():
student = Student.objects.get(id = request.POST['student'])
grupa = Grupa.objects.get(id = request.POST['grupa'])
student.grupa = grupa
student.save()
return HttpResponseRedirect(reverse('zarzadzaj_studentami'))
return render_to_response('oceny/zarzadzaj_studentami.html', {'req': req}, context_instance = RequestContext(request))
</code></pre>
<p>I realize that the code may be lame in some cases. I would appreciate any other hints how to write things better.</p>
| 0 | 2008-12-27T14:43:10Z | 397,219 | <p>Look for "CACHE_BACKEND= ????" in your settings.py file. The value will change as a function of which caching mechanism you are using. Comment this out and restart the server. If your values are now showing correctly, then it was a caching problem.</p>
| 0 | 2008-12-29T06:10:09Z | [
"python",
"django",
"django-templates",
"templatetags"
] |
templatetags don't refresh | 395,053 | <p>I have two templatetags in my app which contain forms which show entries in db. When I alter data or add new entry to db, the forms show the old data. While in admin panel everything is correct (updated). When I restart the server (I mean <code>manage.py runserver</code>) forms show updated db entries. How to make the forms show updated data?<br /><br />
regards<br />
chriss<br /><br />
<b>EDIT:</b><br />
file: <code>templatetags/oceny_tags.py</code>:<br /></p>
<pre><code>from django import template
from oceny.formularze import StudentFormularz, PrzeniesStudentaFormularz
def dodajStudenta(req):
formularz = StudentFormularz(req)
return {'formularz': formularz}
def przeniesStudenta(req):
formularz = PrzeniesStudentaFormularz(req)
return {'formularz': formularz}
register = template.Library()
register.inclusion_tag('oceny/formularz_studenta.html', takes_context = False)(dodajStudenta)
register.inclusion_tag('oceny/formularz_przenies_studenta.html', takes_context = False)(przeniesStudenta)
</code></pre>
<p>file: <code>views.py</code> view responsible for handling forms:</p>
<pre><code>def zarzadzajStudentami(request):
formularze = ['dodaj_studenta', 'przenies_studenta']
req = {}
for e in formularze:
req[e] = None
if request.POST:
req[request.POST['formularz']] = request.POST
if request.POST['formularz'] == 'dodaj_studenta':
formularz = StudentFormularz(request.POST)
if formularz.is_valid():
formularz.save()
return HttpResponseRedirect(reverse('zarzadzaj_studentami'))
elif request.POST['formularz'] == 'przenies_studenta':
formularz = PrzeniesStudentaFormularz(request.POST)
if formularz.is_valid():
student = Student.objects.get(id = request.POST['student'])
grupa = Grupa.objects.get(id = request.POST['grupa'])
student.grupa = grupa
student.save()
return HttpResponseRedirect(reverse('zarzadzaj_studentami'))
return render_to_response('oceny/zarzadzaj_studentami.html', {'req': req}, context_instance = RequestContext(request))
</code></pre>
<p>I realize that the code may be lame in some cases. I would appreciate any other hints how to write things better.</p>
| 0 | 2008-12-27T14:43:10Z | 30,299,070 | <p>I have too low rep to comment, but <code>takes_context</code> defaults to False, making your assignment redundant. Also, but now I am guessing, but it might be related to your problem.</p>
| 0 | 2015-05-18T09:06:38Z | [
"python",
"django",
"django-templates",
"templatetags"
] |
Can I use a ForeignKey in __unicode__ return? | 395,340 | <p>I have the following classes: Ingredients, Recipe and RecipeContent...</p>
<pre><code>class Ingredient(models.Model):
name = models.CharField(max_length=30, primary_key=True)
qty_on_stock = models.IntegerField()
def __unicode__(self):
return self.name
class Recipe(models.Model):
name = models.CharField(max_length=30, primary_key=True)
comments = models.TextField(blank=True)
ingredient = models.ManyToManyField(Ingredient)
def __unicode__(self):
return self.name
class RecipeContent(models.Model):
recipe = models.ForeignKey(Recipe)
ingredients = models.ForeignKey(Ingredient)
qty_used = models.IntegerField()
</code></pre>
<p>but for __unicode__() in RecipeContent I would like to use the Recipe name to which this RecipeContent belongs to... is there a way to do it?</p>
| 11 | 2008-12-27T19:58:22Z | 395,347 | <pre><code>class RecipeContent(models.Model):
...
def __unicode__(self):
# You can access ForeignKey properties through the field name!
return self.recipe.name
</code></pre>
| 24 | 2008-12-27T20:02:38Z | [
"python",
"django",
"django-models"
] |
Can I use a ForeignKey in __unicode__ return? | 395,340 | <p>I have the following classes: Ingredients, Recipe and RecipeContent...</p>
<pre><code>class Ingredient(models.Model):
name = models.CharField(max_length=30, primary_key=True)
qty_on_stock = models.IntegerField()
def __unicode__(self):
return self.name
class Recipe(models.Model):
name = models.CharField(max_length=30, primary_key=True)
comments = models.TextField(blank=True)
ingredient = models.ManyToManyField(Ingredient)
def __unicode__(self):
return self.name
class RecipeContent(models.Model):
recipe = models.ForeignKey(Recipe)
ingredients = models.ForeignKey(Ingredient)
qty_used = models.IntegerField()
</code></pre>
<p>but for __unicode__() in RecipeContent I would like to use the Recipe name to which this RecipeContent belongs to... is there a way to do it?</p>
| 11 | 2008-12-27T19:58:22Z | 403,724 | <p>Yes, you can (as bishanty points), but be prepared for situation when <code>__unicode__()</code> is called but FK is not set yet. I came into this few times.</p>
| 0 | 2008-12-31T18:31:53Z | [
"python",
"django",
"django-models"
] |
Can I use a ForeignKey in __unicode__ return? | 395,340 | <p>I have the following classes: Ingredients, Recipe and RecipeContent...</p>
<pre><code>class Ingredient(models.Model):
name = models.CharField(max_length=30, primary_key=True)
qty_on_stock = models.IntegerField()
def __unicode__(self):
return self.name
class Recipe(models.Model):
name = models.CharField(max_length=30, primary_key=True)
comments = models.TextField(blank=True)
ingredient = models.ManyToManyField(Ingredient)
def __unicode__(self):
return self.name
class RecipeContent(models.Model):
recipe = models.ForeignKey(Recipe)
ingredients = models.ForeignKey(Ingredient)
qty_used = models.IntegerField()
</code></pre>
<p>but for __unicode__() in RecipeContent I would like to use the Recipe name to which this RecipeContent belongs to... is there a way to do it?</p>
| 11 | 2008-12-27T19:58:22Z | 6,714,575 | <p>If you only care about the name part of the Recipe, you can do:</p>
<pre><code>class Recipe(models.Model):
name = models.CharField(max_length=30, primary_key=True)
comments = models.TextField(blank=True)
...
def __unicode__(self):
return self.name
class RecipeContent(models.Model):
recipe = models.ForeignKey(Recipe)
...
def __unicode__(self):
return str(self.recipe)
</code></pre>
| 1 | 2011-07-16T01:01:29Z | [
"python",
"django",
"django-models"
] |
How to download a file over http with authorization in python 3.0, working around bugs? | 395,451 | <p>I have a script that I'd like to continue using, but it looks like I either have to find some workaround for a bug in Python 3, or downgrade back to 2.6, and thus having to downgrade other scripts as well...</p>
<p>Hopefully someone here have already managed to find a workaround.</p>
<p>The problem is that due to the new changes in Python 3.0 regarding bytes and strings, not all the library code is apparently tested.</p>
<p>I have a script that downloades a page from a web server. This script passed a username and password as part of the url in python 2.6, but in Python 3.0, this doesn't work any more.</p>
<p>For instance, this:</p>
<pre><code>import urllib.request;
url = "http://username:password@server/file";
urllib.request.urlretrieve(url, "temp.dat");
</code></pre>
<p>fails with this exception:</p>
<pre><code>Traceback (most recent call last):
File "C:\Temp\test.py", line 5, in <module>
urllib.request.urlretrieve(url, "test.html");
File "C:\Python30\lib\urllib\request.py", line 134, in urlretrieve
return _urlopener.retrieve(url, filename, reporthook, data)
File "C:\Python30\lib\urllib\request.py", line 1476, in retrieve
fp = self.open(url, data)
File "C:\Python30\lib\urllib\request.py", line 1444, in open
return getattr(self, name)(url)
File "C:\Python30\lib\urllib\request.py", line 1618, in open_http
return self._open_generic_http(http.client.HTTPConnection, url, data)
File "C:\Python30\lib\urllib\request.py", line 1576, in _open_generic_http
auth = base64.b64encode(user_passwd).strip()
File "C:\Python30\lib\base64.py", line 56, in b64encode
raise TypeError("expected bytes, not %s" % s.__class__.__name__)
TypeError: expected bytes, not str
</code></pre>
<p>Apparently, base64-encoding now needs bytes in and outputs a string, and thus urlretrieve (or some code therein) which builds up a string of username:password, and tries to base64-encode this for simple authorization, fails.</p>
<p>If I instead try to use urlopen, like this:</p>
<pre><code>import urllib.request;
url = "http://username:password@server/file";
f = urllib.request.urlopen(url);
contents = f.read();
</code></pre>
<p>Then it fails with this exception:</p>
<pre><code>Traceback (most recent call last):
File "C:\Temp\test.py", line 5, in <module>
f = urllib.request.urlopen(url);
File "C:\Python30\lib\urllib\request.py", line 122, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python30\lib\urllib\request.py", line 359, in open
response = self._open(req, data)
File "C:\Python30\lib\urllib\request.py", line 377, in _open
'_open', req)
File "C:\Python30\lib\urllib\request.py", line 337, in _call_chain
result = func(*args)
File "C:\Python30\lib\urllib\request.py", line 1082, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "C:\Python30\lib\urllib\request.py", line 1051, in do_open
h = http_class(host, timeout=req.timeout) # will parse host:port
File "C:\Python30\lib\http\client.py", line 620, in __init__
self._set_hostport(host, port)
File "C:\Python30\lib\http\client.py", line 632, in _set_hostport
raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
http.client.InvalidURL: nonnumeric port: 'password@server'
</code></pre>
<p>Apparently the url parsing in this "next gen url retrieval library" doesn't know what to do with username and passwords in the url.</p>
<p>What other choices do I have?</p>
| 6 | 2008-12-27T21:45:47Z | 395,481 | <p>Direct from the Py3k docs: <a href="http://docs.python.org/dev/py3k/library/urllib.request.html#examples">http://docs.python.org/dev/py3k/library/urllib.request.html#examples</a></p>
<pre><code>import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
uri='https://mahler:8092/site-updates.py',
user='klem',
passwd='kadidd!ehopper')
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
urllib.request.urlopen('http://www.example.com/login.html')
</code></pre>
| 19 | 2008-12-27T22:04:53Z | [
"python",
"python-3.x",
"urllib"
] |
How to download a file over http with authorization in python 3.0, working around bugs? | 395,451 | <p>I have a script that I'd like to continue using, but it looks like I either have to find some workaround for a bug in Python 3, or downgrade back to 2.6, and thus having to downgrade other scripts as well...</p>
<p>Hopefully someone here have already managed to find a workaround.</p>
<p>The problem is that due to the new changes in Python 3.0 regarding bytes and strings, not all the library code is apparently tested.</p>
<p>I have a script that downloades a page from a web server. This script passed a username and password as part of the url in python 2.6, but in Python 3.0, this doesn't work any more.</p>
<p>For instance, this:</p>
<pre><code>import urllib.request;
url = "http://username:password@server/file";
urllib.request.urlretrieve(url, "temp.dat");
</code></pre>
<p>fails with this exception:</p>
<pre><code>Traceback (most recent call last):
File "C:\Temp\test.py", line 5, in <module>
urllib.request.urlretrieve(url, "test.html");
File "C:\Python30\lib\urllib\request.py", line 134, in urlretrieve
return _urlopener.retrieve(url, filename, reporthook, data)
File "C:\Python30\lib\urllib\request.py", line 1476, in retrieve
fp = self.open(url, data)
File "C:\Python30\lib\urllib\request.py", line 1444, in open
return getattr(self, name)(url)
File "C:\Python30\lib\urllib\request.py", line 1618, in open_http
return self._open_generic_http(http.client.HTTPConnection, url, data)
File "C:\Python30\lib\urllib\request.py", line 1576, in _open_generic_http
auth = base64.b64encode(user_passwd).strip()
File "C:\Python30\lib\base64.py", line 56, in b64encode
raise TypeError("expected bytes, not %s" % s.__class__.__name__)
TypeError: expected bytes, not str
</code></pre>
<p>Apparently, base64-encoding now needs bytes in and outputs a string, and thus urlretrieve (or some code therein) which builds up a string of username:password, and tries to base64-encode this for simple authorization, fails.</p>
<p>If I instead try to use urlopen, like this:</p>
<pre><code>import urllib.request;
url = "http://username:password@server/file";
f = urllib.request.urlopen(url);
contents = f.read();
</code></pre>
<p>Then it fails with this exception:</p>
<pre><code>Traceback (most recent call last):
File "C:\Temp\test.py", line 5, in <module>
f = urllib.request.urlopen(url);
File "C:\Python30\lib\urllib\request.py", line 122, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python30\lib\urllib\request.py", line 359, in open
response = self._open(req, data)
File "C:\Python30\lib\urllib\request.py", line 377, in _open
'_open', req)
File "C:\Python30\lib\urllib\request.py", line 337, in _call_chain
result = func(*args)
File "C:\Python30\lib\urllib\request.py", line 1082, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "C:\Python30\lib\urllib\request.py", line 1051, in do_open
h = http_class(host, timeout=req.timeout) # will parse host:port
File "C:\Python30\lib\http\client.py", line 620, in __init__
self._set_hostport(host, port)
File "C:\Python30\lib\http\client.py", line 632, in _set_hostport
raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
http.client.InvalidURL: nonnumeric port: 'password@server'
</code></pre>
<p>Apparently the url parsing in this "next gen url retrieval library" doesn't know what to do with username and passwords in the url.</p>
<p>What other choices do I have?</p>
| 6 | 2008-12-27T21:45:47Z | 395,665 | <p>My advice would be to maintain your 2.* branch as your production branch until you can get the 3.0 stuff sorted.</p>
<p>I am going to wait a while before moving over to Python 3.0. There seems a lot of people in a rush, but I just want everything sorted out, and a decent selection of third-party libraries. This may take a year, it may take 18 months, but the pressure to "upgrade" is really low for me.</p>
| 0 | 2008-12-28T01:21:20Z | [
"python",
"python-3.x",
"urllib"
] |
How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X? | 395,509 | <p>I'm new to the Mac OS X, and I'm just about ready to throw my brand new <a href="http://en.wikipedia.org/wiki/MacBook_Pro" rel="nofollow">MacBook Pro</a> out the window. Every tutorial on setting up a Django development environment on <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac OS X Leopard</a> is insidiously wrong. They are all skipping over one step, or assuming you have setup something one way, or are just assuming that I know one thing that I must not.</p>
<p>I'm very familiar with how to setup the environment on Ubuntu/Linux, and the only part I'm getting stuck on with <a href="https://en.wikipedia.org/wiki/OS_X" rel="nofollow">OS X</a> is how to install MySQL, autostart it, and install the Python MySQL bindings. I think my mistake was using a hodgepodge of tools I don't fully understand; I used fink to install MySQL and its development libraries and then tried to build the Python-MySQL bindings from source (but they won't build.)</p>
<p>UPDATE:
I installed the binary MySQL package from <a href="http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg" rel="nofollow">http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg</a>, and I got MySQL server running (can access with admin.)
The MySQL version I got from port was rubbish, I could not get it to run at all.</p>
<p>I modified the source for the Python-MySQL package as per the answer I chose, but I still got compilation errors that I listed in the comments. I was able to fix these by adding /usr/local/mysql/bin/ to my path in my "~/.profile" file.
"
PATH=/usr/local/mysql/bin:$PATH
"</p>
<p>Thanks for the help, I was very wary about editing the source code since this operation had been so easy on Ubuntu, but I'll be more willing to try that in the future. I'm really missing Ubuntu's "apt-get" command; it makes life very easy and simple sometimes. I already have an Ubuntu <a href="http://en.wikipedia.org/wiki/VMware" rel="nofollow">VMware</a> image running on my Mac, so I can always use that as a fallback (plus it more closely matches my production machines so should be a good test environment for debugging production problems.)</p>
| 6 | 2008-12-27T22:23:48Z | 395,546 | <p>You can use the BSD-alike(?) <a href="http://macports.org" rel="nofollow">http://macports.org</a>, which provides gentoo-like build-it-yourself installations of a wide swath of software you'd expect to find in a Linux distro.</p>
<p>Alternatively you could just run Ubuntu in a virtual machine as your test stage.</p>
<p>It's honestly a simple </p>
<p><code># port install <pkgname></code></p>
| 2 | 2008-12-27T22:53:35Z | [
"python",
"mysql",
"django",
"osx",
"sysadmin"
] |
How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X? | 395,509 | <p>I'm new to the Mac OS X, and I'm just about ready to throw my brand new <a href="http://en.wikipedia.org/wiki/MacBook_Pro" rel="nofollow">MacBook Pro</a> out the window. Every tutorial on setting up a Django development environment on <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac OS X Leopard</a> is insidiously wrong. They are all skipping over one step, or assuming you have setup something one way, or are just assuming that I know one thing that I must not.</p>
<p>I'm very familiar with how to setup the environment on Ubuntu/Linux, and the only part I'm getting stuck on with <a href="https://en.wikipedia.org/wiki/OS_X" rel="nofollow">OS X</a> is how to install MySQL, autostart it, and install the Python MySQL bindings. I think my mistake was using a hodgepodge of tools I don't fully understand; I used fink to install MySQL and its development libraries and then tried to build the Python-MySQL bindings from source (but they won't build.)</p>
<p>UPDATE:
I installed the binary MySQL package from <a href="http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg" rel="nofollow">http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg</a>, and I got MySQL server running (can access with admin.)
The MySQL version I got from port was rubbish, I could not get it to run at all.</p>
<p>I modified the source for the Python-MySQL package as per the answer I chose, but I still got compilation errors that I listed in the comments. I was able to fix these by adding /usr/local/mysql/bin/ to my path in my "~/.profile" file.
"
PATH=/usr/local/mysql/bin:$PATH
"</p>
<p>Thanks for the help, I was very wary about editing the source code since this operation had been so easy on Ubuntu, but I'll be more willing to try that in the future. I'm really missing Ubuntu's "apt-get" command; it makes life very easy and simple sometimes. I already have an Ubuntu <a href="http://en.wikipedia.org/wiki/VMware" rel="nofollow">VMware</a> image running on my Mac, so I can always use that as a fallback (plus it more closely matches my production machines so should be a good test environment for debugging production problems.)</p>
| 6 | 2008-12-27T22:23:48Z | 395,547 | <p>The <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow">Python</a> mysqldb packge <a href="http://pdb.finkproject.org/pdb/package.php/mysql-python-py25" rel="nofollow">is in fink</a>, but it's in the unstable tree. Just <a href="http://www.finkproject.org/faq/usage-fink.php#unstable" rel="nofollow">enable the unstable tree</a>, and you will be able to install it.</p>
<p>Or, if you're up for having two alternate package managers, it's also in <a href="http://en.wikipedia.org/wiki/MacPorts" rel="nofollow">MacPorts</a>.</p>
<p>I also had problems last time I had to do this and ended up going with the fink version and saving a lot of headache.</p>
| 0 | 2008-12-27T22:54:23Z | [
"python",
"mysql",
"django",
"osx",
"sysadmin"
] |
How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X? | 395,509 | <p>I'm new to the Mac OS X, and I'm just about ready to throw my brand new <a href="http://en.wikipedia.org/wiki/MacBook_Pro" rel="nofollow">MacBook Pro</a> out the window. Every tutorial on setting up a Django development environment on <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac OS X Leopard</a> is insidiously wrong. They are all skipping over one step, or assuming you have setup something one way, or are just assuming that I know one thing that I must not.</p>
<p>I'm very familiar with how to setup the environment on Ubuntu/Linux, and the only part I'm getting stuck on with <a href="https://en.wikipedia.org/wiki/OS_X" rel="nofollow">OS X</a> is how to install MySQL, autostart it, and install the Python MySQL bindings. I think my mistake was using a hodgepodge of tools I don't fully understand; I used fink to install MySQL and its development libraries and then tried to build the Python-MySQL bindings from source (but they won't build.)</p>
<p>UPDATE:
I installed the binary MySQL package from <a href="http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg" rel="nofollow">http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg</a>, and I got MySQL server running (can access with admin.)
The MySQL version I got from port was rubbish, I could not get it to run at all.</p>
<p>I modified the source for the Python-MySQL package as per the answer I chose, but I still got compilation errors that I listed in the comments. I was able to fix these by adding /usr/local/mysql/bin/ to my path in my "~/.profile" file.
"
PATH=/usr/local/mysql/bin:$PATH
"</p>
<p>Thanks for the help, I was very wary about editing the source code since this operation had been so easy on Ubuntu, but I'll be more willing to try that in the future. I'm really missing Ubuntu's "apt-get" command; it makes life very easy and simple sometimes. I already have an Ubuntu <a href="http://en.wikipedia.org/wiki/VMware" rel="nofollow">VMware</a> image running on my Mac, so I can always use that as a fallback (plus it more closely matches my production machines so should be a good test environment for debugging production problems.)</p>
| 6 | 2008-12-27T22:23:48Z | 395,568 | <p>Did the MySQL and MySQL-dev installations go smoothly? Can you run MySQL, connect to it and so on? Does <code>/usr/local/mysql/include</code> contain lots of header files? (I've got 46 header files there, for reference).</p>
<p>If so, MySQL should be good to go. There are still a few manual steps required to compile MySQL-python, however.</p>
<p><a href="http://www.keningle.com/?p=11" rel="nofollow">This</a> is a decent guide: I've included the salient steps below.</p>
<p><hr /></p>
<ol>
<li><p>Download the <a href="https://sourceforge.net/projects/mysql-python" rel="nofollow">MySQL-python source</a> (v1.2.2 at time of writing: all subsequent instructions are for this version)</p>
<pre><code>$ tar xzf MySQL-python-1.2.2.tar.gz && cd MySQL-python-1.2.2
</code></pre></li>
<li><p>Edit <code>_mysql.c</code>: remove lines 37-39 and change lines 481-482. Here's the diff:</p>
<pre><code>37,39d36
< #ifndef uint
< #define uint unsigned int
< #endif
484,485c481,482
< uint port = MYSQL_PORT;
< uint client_flag = 0;
---
> unsigned int port = MYSQL_PORT;
> unsigned int client_flag = 0;
</code></pre></li>
<li><p>Symlink the libs to where MySQL-python expects them:</p>
<pre><code>$ sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql
</code></pre></li>
<li><p>In your MySQL-python-1.2.2 directory, rebuild your package:</p>
<pre><code>$ sudo python setup.py build
</code></pre>
<p><strong>Note:</strong> You will receive a warning, ignore it.</p></li>
<li><p>Install the package:</p>
<pre><code>$ sudo python setup.py install
</code></pre></li>
</ol>
<p><hr /></p>
<p>As for starting MySQL, there are instructions <a href="http://dev.mysql.com/doc/refman/5.0/en/mac-os-x-installation.html" rel="nofollow">here</a> on starting it as a service. Personally, I just run</p>
<pre><code>sudo mysqld_safe
</code></pre>
<p>manually, backgrounding it with <code>^Z</code> and <code>bg</code> once I've put in my password.</p>
| 12 | 2008-12-27T23:09:42Z | [
"python",
"mysql",
"django",
"osx",
"sysadmin"
] |
How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X? | 395,509 | <p>I'm new to the Mac OS X, and I'm just about ready to throw my brand new <a href="http://en.wikipedia.org/wiki/MacBook_Pro" rel="nofollow">MacBook Pro</a> out the window. Every tutorial on setting up a Django development environment on <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac OS X Leopard</a> is insidiously wrong. They are all skipping over one step, or assuming you have setup something one way, or are just assuming that I know one thing that I must not.</p>
<p>I'm very familiar with how to setup the environment on Ubuntu/Linux, and the only part I'm getting stuck on with <a href="https://en.wikipedia.org/wiki/OS_X" rel="nofollow">OS X</a> is how to install MySQL, autostart it, and install the Python MySQL bindings. I think my mistake was using a hodgepodge of tools I don't fully understand; I used fink to install MySQL and its development libraries and then tried to build the Python-MySQL bindings from source (but they won't build.)</p>
<p>UPDATE:
I installed the binary MySQL package from <a href="http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg" rel="nofollow">http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg</a>, and I got MySQL server running (can access with admin.)
The MySQL version I got from port was rubbish, I could not get it to run at all.</p>
<p>I modified the source for the Python-MySQL package as per the answer I chose, but I still got compilation errors that I listed in the comments. I was able to fix these by adding /usr/local/mysql/bin/ to my path in my "~/.profile" file.
"
PATH=/usr/local/mysql/bin:$PATH
"</p>
<p>Thanks for the help, I was very wary about editing the source code since this operation had been so easy on Ubuntu, but I'll be more willing to try that in the future. I'm really missing Ubuntu's "apt-get" command; it makes life very easy and simple sometimes. I already have an Ubuntu <a href="http://en.wikipedia.org/wiki/VMware" rel="nofollow">VMware</a> image running on my Mac, so I can always use that as a fallback (plus it more closely matches my production machines so should be a good test environment for debugging production problems.)</p>
| 6 | 2008-12-27T22:23:48Z | 395,574 | <p>Assuming this is just a development environment, you could try using <a href="http://en.wikipedia.org/wiki/SQLite" rel="nofollow">SQLite</a> 3 as your database. Mileage may vary depending on how low-level you need to get with the database for your specific application.</p>
| 2 | 2008-12-27T23:15:34Z | [
"python",
"mysql",
"django",
"osx",
"sysadmin"
] |
How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X? | 395,509 | <p>I'm new to the Mac OS X, and I'm just about ready to throw my brand new <a href="http://en.wikipedia.org/wiki/MacBook_Pro" rel="nofollow">MacBook Pro</a> out the window. Every tutorial on setting up a Django development environment on <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac OS X Leopard</a> is insidiously wrong. They are all skipping over one step, or assuming you have setup something one way, or are just assuming that I know one thing that I must not.</p>
<p>I'm very familiar with how to setup the environment on Ubuntu/Linux, and the only part I'm getting stuck on with <a href="https://en.wikipedia.org/wiki/OS_X" rel="nofollow">OS X</a> is how to install MySQL, autostart it, and install the Python MySQL bindings. I think my mistake was using a hodgepodge of tools I don't fully understand; I used fink to install MySQL and its development libraries and then tried to build the Python-MySQL bindings from source (but they won't build.)</p>
<p>UPDATE:
I installed the binary MySQL package from <a href="http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg" rel="nofollow">http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg</a>, and I got MySQL server running (can access with admin.)
The MySQL version I got from port was rubbish, I could not get it to run at all.</p>
<p>I modified the source for the Python-MySQL package as per the answer I chose, but I still got compilation errors that I listed in the comments. I was able to fix these by adding /usr/local/mysql/bin/ to my path in my "~/.profile" file.
"
PATH=/usr/local/mysql/bin:$PATH
"</p>
<p>Thanks for the help, I was very wary about editing the source code since this operation had been so easy on Ubuntu, but I'll be more willing to try that in the future. I'm really missing Ubuntu's "apt-get" command; it makes life very easy and simple sometimes. I already have an Ubuntu <a href="http://en.wikipedia.org/wiki/VMware" rel="nofollow">VMware</a> image running on my Mac, so I can always use that as a fallback (plus it more closely matches my production machines so should be a good test environment for debugging production problems.)</p>
| 6 | 2008-12-27T22:23:48Z | 395,669 | <p>I put a step-by-step guide in a blog post that might help: <em><a href="http://www.djangrrl.com/view/installing-django-with-mysql-on-mac-os-x/" rel="nofollow">Installing Django with MySQL on Mac OS X</a></em>.</p>
| 0 | 2008-12-28T01:30:00Z | [
"python",
"mysql",
"django",
"osx",
"sysadmin"
] |
How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X? | 395,509 | <p>I'm new to the Mac OS X, and I'm just about ready to throw my brand new <a href="http://en.wikipedia.org/wiki/MacBook_Pro" rel="nofollow">MacBook Pro</a> out the window. Every tutorial on setting up a Django development environment on <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac OS X Leopard</a> is insidiously wrong. They are all skipping over one step, or assuming you have setup something one way, or are just assuming that I know one thing that I must not.</p>
<p>I'm very familiar with how to setup the environment on Ubuntu/Linux, and the only part I'm getting stuck on with <a href="https://en.wikipedia.org/wiki/OS_X" rel="nofollow">OS X</a> is how to install MySQL, autostart it, and install the Python MySQL bindings. I think my mistake was using a hodgepodge of tools I don't fully understand; I used fink to install MySQL and its development libraries and then tried to build the Python-MySQL bindings from source (but they won't build.)</p>
<p>UPDATE:
I installed the binary MySQL package from <a href="http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg" rel="nofollow">http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg</a>, and I got MySQL server running (can access with admin.)
The MySQL version I got from port was rubbish, I could not get it to run at all.</p>
<p>I modified the source for the Python-MySQL package as per the answer I chose, but I still got compilation errors that I listed in the comments. I was able to fix these by adding /usr/local/mysql/bin/ to my path in my "~/.profile" file.
"
PATH=/usr/local/mysql/bin:$PATH
"</p>
<p>Thanks for the help, I was very wary about editing the source code since this operation had been so easy on Ubuntu, but I'll be more willing to try that in the future. I'm really missing Ubuntu's "apt-get" command; it makes life very easy and simple sometimes. I already have an Ubuntu <a href="http://en.wikipedia.org/wiki/VMware" rel="nofollow">VMware</a> image running on my Mac, so I can always use that as a fallback (plus it more closely matches my production machines so should be a good test environment for debugging production problems.)</p>
| 6 | 2008-12-27T22:23:48Z | 395,680 | <p>If you are a Mac user, install <a href="http://www.macports.org/" rel="nofollow">MacPorts</a>. Almost any Linux/Unix application is available through "port". It is simple and easy to manage.</p>
| 0 | 2008-12-28T01:48:04Z | [
"python",
"mysql",
"django",
"osx",
"sysadmin"
] |
How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X? | 395,509 | <p>I'm new to the Mac OS X, and I'm just about ready to throw my brand new <a href="http://en.wikipedia.org/wiki/MacBook_Pro" rel="nofollow">MacBook Pro</a> out the window. Every tutorial on setting up a Django development environment on <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Leopard" rel="nofollow">Mac OS X Leopard</a> is insidiously wrong. They are all skipping over one step, or assuming you have setup something one way, or are just assuming that I know one thing that I must not.</p>
<p>I'm very familiar with how to setup the environment on Ubuntu/Linux, and the only part I'm getting stuck on with <a href="https://en.wikipedia.org/wiki/OS_X" rel="nofollow">OS X</a> is how to install MySQL, autostart it, and install the Python MySQL bindings. I think my mistake was using a hodgepodge of tools I don't fully understand; I used fink to install MySQL and its development libraries and then tried to build the Python-MySQL bindings from source (but they won't build.)</p>
<p>UPDATE:
I installed the binary MySQL package from <a href="http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg" rel="nofollow">http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg</a>, and I got MySQL server running (can access with admin.)
The MySQL version I got from port was rubbish, I could not get it to run at all.</p>
<p>I modified the source for the Python-MySQL package as per the answer I chose, but I still got compilation errors that I listed in the comments. I was able to fix these by adding /usr/local/mysql/bin/ to my path in my "~/.profile" file.
"
PATH=/usr/local/mysql/bin:$PATH
"</p>
<p>Thanks for the help, I was very wary about editing the source code since this operation had been so easy on Ubuntu, but I'll be more willing to try that in the future. I'm really missing Ubuntu's "apt-get" command; it makes life very easy and simple sometimes. I already have an Ubuntu <a href="http://en.wikipedia.org/wiki/VMware" rel="nofollow">VMware</a> image running on my Mac, so I can always use that as a fallback (plus it more closely matches my production machines so should be a good test environment for debugging production problems.)</p>
| 6 | 2008-12-27T22:23:48Z | 396,736 | <p>Install <a href="http://en.wikipedia.org/wiki/MacPorts" rel="nofollow">MacPorts</a>. Run <code>port install mysql</code>. It worked for me!</p>
| 0 | 2008-12-28T21:54:09Z | [
"python",
"mysql",
"django",
"osx",
"sysadmin"
] |
Threads in Python | 395,704 | <p>General tutorial or good resource on how to use threads in Python?</p>
<p>When to use threads, how they are effective, and some general background on threads [specific to Python]?</p>
| 6 | 2008-12-28T02:22:38Z | 395,716 | <p>Threads should be used when you want two things to run at once, or want something to run in the background without slowing down the main process.<br />
My recommendation is to only use threads if you have to. They generally add complexity to a program.<br />
The main documentation for threading is here: <a href="http://docs.python.org/library/threading.html" rel="nofollow">http://docs.python.org/library/threading.html</a><br />
Some examples are here:<br />
<a href="http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/" rel="nofollow">http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/</a><br />
<a href="http://linuxgazette.net/107/pai.html" rel="nofollow">http://linuxgazette.net/107/pai.html</a><br />
<a href="http://www.wellho.net/solutions/python-python-threads-a-first-example.html" rel="nofollow">http://www.wellho.net/solutions/python-python-threads-a-first-example.html</a></p>
| 13 | 2008-12-28T02:40:43Z | [
"python",
"multithreading"
] |
Threads in Python | 395,704 | <p>General tutorial or good resource on how to use threads in Python?</p>
<p>When to use threads, how they are effective, and some general background on threads [specific to Python]?</p>
| 6 | 2008-12-28T02:22:38Z | 395,726 | <p>There are several tutorials <a href="http://python.objectis.net/index_html#thread" rel="nofollow">here</a>. </p>
| 1 | 2008-12-28T02:54:25Z | [
"python",
"multithreading"
] |
Threads in Python | 395,704 | <p>General tutorial or good resource on how to use threads in Python?</p>
<p>When to use threads, how they are effective, and some general background on threads [specific to Python]?</p>
| 6 | 2008-12-28T02:22:38Z | 395,728 | <p>There is a fantastic pdf, <a href="http://heather.cs.ucdavis.edu/~matloff/158/PLN/ParProcBook.pdf" rel="nofollow">Tutorial on Threads Programming with Python</a> by
Norman Matloff and Francis Hsu, of University of California, Davis.</p>
<p>Threads should be avoided whenever possible. They add much in complexity, synchronization issues and hard to debug issues. However some problems require them (i.e. GUI programming), but I would encourage you to look for a single-threaded solution if you can.</p>
| 3 | 2008-12-28T02:54:56Z | [
"python",
"multithreading"
] |
Threads in Python | 395,704 | <p>General tutorial or good resource on how to use threads in Python?</p>
<p>When to use threads, how they are effective, and some general background on threads [specific to Python]?</p>
| 6 | 2008-12-28T02:22:38Z | 396,055 | <p>One thing to remember before spending time and effort in writing a multi-threaded Python application is that there is a <a href="http://en.wikipedia.org/wiki/Global_Interpreter_Lock">Global Interpreter Lock</a> (GIL), so you won't actually be running more than one thread at a time.</p>
<p>This makes threading unsuitable for trying to take advantage of multiple cores or CPUs. You may get some speedup from multiplexing other resources (network, disk, ...), but it's never been particularly noticeable in my experience.</p>
<p>In general, I only use threads when there are several logically separate tasks happening at once, and yet I want them all in the same VM. A thread pulling data from the web and putting it on a Queue, while another thread pops from the Queue and writes to a database, something like that.</p>
<p>With Python 2.6, there is the new <code>multiprocessing</code> module which is pretty cool - it's got a very similar interface to the <code>threading</code> module, but actually spawns new OS processes, sidestepping the GIL.</p>
| 8 | 2008-12-28T10:22:05Z | [
"python",
"multithreading"
] |
How to check whether a variable is a class or not? | 395,735 | <p>I was wondering how to check whether a variable is a class (not an instance!) or not.</p>
<p>I've tried to use the function <code>isinstance(object, class_or_type_or_tuple)</code> to do this, but I don't know what type would a class will have.</p>
<p>For example, in the following code</p>
<pre><code>class Foo: pass
isinstance(Foo, **???**) # i want to make this return True.
</code></pre>
<p>I tried to substitute "<code>class</code>" with <strong>???</strong>, but I realized that <code>class</code> is a keyword in python.</p>
| 119 | 2008-12-28T03:08:05Z | 395,741 | <pre><code>>>> class X(object):
... pass
...
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
</code></pre>
| 17 | 2008-12-28T03:11:54Z | [
"python",
"reflection"
] |
How to check whether a variable is a class or not? | 395,735 | <p>I was wondering how to check whether a variable is a class (not an instance!) or not.</p>
<p>I've tried to use the function <code>isinstance(object, class_or_type_or_tuple)</code> to do this, but I don't know what type would a class will have.</p>
<p>For example, in the following code</p>
<pre><code>class Foo: pass
isinstance(Foo, **???**) # i want to make this return True.
</code></pre>
<p>I tried to substitute "<code>class</code>" with <strong>???</strong>, but I realized that <code>class</code> is a keyword in python.</p>
| 119 | 2008-12-28T03:08:05Z | 395,782 | <p>Even better: use the <a href="https://docs.python.org/library/inspect.html#inspect.isclass"><code>inspect.isclass</code></a> function.</p>
<pre><code>>>> import inspect
>>> class X(object):
... pass
...
>>> inspect.isclass(X)
True
>>> x = X()
>>> isinstance(x, X)
True
>>> y = 25
>>> isinstance(y, X)
False
</code></pre>
| 178 | 2008-12-28T03:47:00Z | [
"python",
"reflection"
] |
How to check whether a variable is a class or not? | 395,735 | <p>I was wondering how to check whether a variable is a class (not an instance!) or not.</p>
<p>I've tried to use the function <code>isinstance(object, class_or_type_or_tuple)</code> to do this, but I don't know what type would a class will have.</p>
<p>For example, in the following code</p>
<pre><code>class Foo: pass
isinstance(Foo, **???**) # i want to make this return True.
</code></pre>
<p>I tried to substitute "<code>class</code>" with <strong>???</strong>, but I realized that <code>class</code> is a keyword in python.</p>
| 119 | 2008-12-28T03:08:05Z | 395,784 | <p>class Foo: is called old style class and class X(object): is called new style class. </p>
<p>Check this <a href="http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python">http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python</a> . New style is recommended. Read about "<a href="http://www.python.org/download/releases/2.2.3/descrintro/" rel="nofollow">unifying types and classes</a>"</p>
| 1 | 2008-12-28T03:48:43Z | [
"python",
"reflection"
] |
How to check whether a variable is a class or not? | 395,735 | <p>I was wondering how to check whether a variable is a class (not an instance!) or not.</p>
<p>I've tried to use the function <code>isinstance(object, class_or_type_or_tuple)</code> to do this, but I don't know what type would a class will have.</p>
<p>For example, in the following code</p>
<pre><code>class Foo: pass
isinstance(Foo, **???**) # i want to make this return True.
</code></pre>
<p>I tried to substitute "<code>class</code>" with <strong>???</strong>, but I realized that <code>class</code> is a keyword in python.</p>
| 119 | 2008-12-28T03:08:05Z | 10,045,680 | <pre><code>isinstance(X, type)
</code></pre>
<p>Return <code>True</code> if <code>X</code> is class and <code>False</code> if not.</p>
| 4 | 2012-04-06T15:34:35Z | [
"python",
"reflection"
] |
How to check whether a variable is a class or not? | 395,735 | <p>I was wondering how to check whether a variable is a class (not an instance!) or not.</p>
<p>I've tried to use the function <code>isinstance(object, class_or_type_or_tuple)</code> to do this, but I don't know what type would a class will have.</p>
<p>For example, in the following code</p>
<pre><code>class Foo: pass
isinstance(Foo, **???**) # i want to make this return True.
</code></pre>
<p>I tried to substitute "<code>class</code>" with <strong>???</strong>, but I realized that <code>class</code> is a keyword in python.</p>
| 119 | 2008-12-28T03:08:05Z | 10,123,520 | <p>The inspect.isclass is probably the best solution, and it's really easy to see how it's actually implemented</p>
<pre><code>def isclass(object):
"""Return true if the object is a class.
Class objects provide these attributes:
__doc__ documentation string
__module__ name of module in which this class was defined"""
return isinstance(object, (type, types.ClassType))
</code></pre>
| 29 | 2012-04-12T12:24:08Z | [
"python",
"reflection"
] |
How to check whether a variable is a class or not? | 395,735 | <p>I was wondering how to check whether a variable is a class (not an instance!) or not.</p>
<p>I've tried to use the function <code>isinstance(object, class_or_type_or_tuple)</code> to do this, but I don't know what type would a class will have.</p>
<p>For example, in the following code</p>
<pre><code>class Foo: pass
isinstance(Foo, **???**) # i want to make this return True.
</code></pre>
<p>I tried to substitute "<code>class</code>" with <strong>???</strong>, but I realized that <code>class</code> is a keyword in python.</p>
| 119 | 2008-12-28T03:08:05Z | 11,179,404 | <p>There are some working solutions here already, but here's another one:</p>
<pre><code>>>> import types
>>> class Dummy: pass
>>> type(Dummy) is types.ClassType
True
</code></pre>
| 0 | 2012-06-24T17:00:17Z | [
"python",
"reflection"
] |
How to check whether a variable is a class or not? | 395,735 | <p>I was wondering how to check whether a variable is a class (not an instance!) or not.</p>
<p>I've tried to use the function <code>isinstance(object, class_or_type_or_tuple)</code> to do this, but I don't know what type would a class will have.</p>
<p>For example, in the following code</p>
<pre><code>class Foo: pass
isinstance(Foo, **???**) # i want to make this return True.
</code></pre>
<p>I tried to substitute "<code>class</code>" with <strong>???</strong>, but I realized that <code>class</code> is a keyword in python.</p>
| 119 | 2008-12-28T03:08:05Z | 34,406,582 | <p>That's a little hackish, but an option if you don't want to avoid imports:</p>
<pre><code>def isclass(obj):
try:
issubclass(obj, object)
except TypeError:
return False
else:
return True
</code></pre>
| 0 | 2015-12-22T00:18:59Z | [
"python",
"reflection"
] |
How do I send an ARP packet through python on windows without needing winpcap? | 395,846 | <p>Is there any way to send ARP packet on Windows without the use of another library such as winpcap?</p>
<p>I have heard that Windows XP SP2 blocks raw ethernet sockets, but I have also heard that raw sockets are only blocked for administrators. Any clarification here?</p>
| 3 | 2008-12-28T04:52:54Z | 395,921 | <p>There is no way to do that in the general case without the use of an external library.</p>
<p>If there are no requirements on what the packet should contain (i.e., if any ARP packet will do) then you <em>can</em> obviously send an ARP request if you're on an Ethernet network simply by trying to send something to any IP on your own subnet (ensuring beforehand that the destination IP is not in the ARP cache by running an external <code>arp -d tar.get.ip.address</code> command), but this will probably not be what you want.</p>
<p>For more information about raw socket support see the <a href="http://msdn.microsoft.com/en-us/library/ms740548.aspx" rel="nofollow">TCP/IP Raw Sockets MSDN page</a>, specifically the <a href="http://msdn.microsoft.com/en-us/library/ms740548.aspx#limitations_on_raw_sockets" rel="nofollow">Limitations on Raw Sockets</a> section.</p>
| 3 | 2008-12-28T06:36:50Z | [
"python",
"sockets",
"ethernet",
"arp"
] |
How do I send an ARP packet through python on windows without needing winpcap? | 395,846 | <p>Is there any way to send ARP packet on Windows without the use of another library such as winpcap?</p>
<p>I have heard that Windows XP SP2 blocks raw ethernet sockets, but I have also heard that raw sockets are only blocked for administrators. Any clarification here?</p>
| 3 | 2008-12-28T04:52:54Z | 503,144 | <p>You could use the OpenVPN tap to send arbitrary packets as if you where using raw sockets.</p>
| 0 | 2009-02-02T13:10:46Z | [
"python",
"sockets",
"ethernet",
"arp"
] |
"MetaClass", "__new__", "cls" and "super" - what is the mechanism exactly? | 395,982 | <p>I have read posts like these:</p>
<ol>
<li><a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">What is a metaclass in Python?</a> </li>
<li><a href="http://stackoverflow.com/questions/392160/what-are-your-concrete-use-cases-for-metaclasses-in-python">What are your (concrete) use-cases for metaclasses in Python?</a></li>
<li><a href="http://fuhm.net/super-harmful/" rel="nofollow">Python's Super is nifty, but you can't use it</a></li>
</ol>
<p>But somehow I got confused. Many confusions like:</p>
<p>When and why would I have to do something like the following?</p>
<pre><code># Refer link1
return super(MyType, cls).__new__(cls, name, bases, newattrs)
</code></pre>
<p>or</p>
<pre><code># Refer link2
return super(MetaSingleton, cls).__call__(*args, **kw)
</code></pre>
<p>or</p>
<pre><code># Refer link2
return type(self.__name__ + other.__name__, (self, other), {})
</code></pre>
<p>How does super work exactly?</p>
<p>What is class registry and unregistry in link1 and how exactly does it work? (I thought it has something to do with <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow">singleton</a>. I may be wrong, being from C background. My coding style is still a mix of functional and OO).</p>
<p>What is the flow of class instantiation (subclass, metaclass, super, type) and method invocation (</p>
<pre><code>metaclass->__new__, metaclass->__init__, super->__new__, subclass->__init__ inherited from metaclass
</code></pre>
<p>) with well-commented working code (though the first link is quite close, but it does not talk about cls keyword and super(..) and registry). Preferably an example with multiple inheritance.</p>
<p>P.S.: I made the last part as code because Stack Overflow formatting was converting the text <code>metaclass->__new__</code>
to metaclass-><strong>new</strong></p>
| 23 | 2008-12-28T08:41:45Z | 396,109 | <p>OK, you've thrown quite a few concepts into the mix here! I'm going to pull out a few of the specific questions you have.</p>
<p>In general, understanding super, the MRO and metclasses is made much more complicated because there have been lots of changes in this tricky area over the last few versions of Python.</p>
<p><a href="http://docs.python.org/reference/datamodel.html" rel="nofollow">Python's own documentation</a> is a very good reference, and completely up to date. There is an <a href="http://www.ibm.com/developerworks/linux/library/l-pymeta.html" rel="nofollow">IBM developerWorks article</a> which is fine as an introduction and takes a more tutorial-based approach, but note that it's five years old, and spends a lot of time talking about the older-style approaches to meta-classes.</p>
<p><strong><code>super</code></strong> is how you access an object's super-classes. It's more complex than (for example) Java's <code>super</code> keyword, mainly because of multiple inheritance in Python. As <a href="http://fuhm.net/super-harmful/" rel="nofollow">Super Considered Harmful</a> explains, using <code>super()</code> can result in you implicitly using a chain of super-classes, the order of which is defined by the <a href="http://www.python.org/download/releases/2.3/mro/" rel="nofollow">Method Resolution Order</a> (MRO).</p>
<p>You can see the MRO for a class easily by invoking <code>mro()</code> on the class (not on an instance). Note that meta-classes are not in an object's super-class hierarchy.</p>
<p><a href="http://stackoverflow.com/users/17624/thomas-wouters">Thomas</a>' description of meta-classes <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">here</a> is excellent:</p>
<blockquote>
<p>A metaclass is the class of a class.
Like a class defines how an instance
of the class behaves, a metaclass
defines how a class behaves. A class
is an instance of a metaclass.</p>
</blockquote>
<p>In the examples you give, here's what's going on:</p>
<ol>
<li><p>The call to <code>__new__</code> is being
bubbled up to the next thing in the
MRO. In this case, <code>super(MyType,
cls)</code> would resolve to <code>type</code>;
calling <code>type.__new__</code> lets Python
complete it's normal instance
creation steps.</p></li>
<li><p>This example is using meta-classes
to enforce a singleton. He's
overriding <code>__call__</code> in the
metaclass so that whenever a class
instance is created, he intercepts
that, and can bypass instance
creation if there already is one
(stored in <code>cls.instance</code>). Note
that overriding <code>__new__</code> in the
metaclass won't be good enough,
because that's only called when
creating the <em>class</em>. Overriding
<code>__new__</code> on the class would work,
however.</p></li>
<li><p>This shows a way to dynamically
create a class. Here's he's
appending the supplied class's name
to the created class name, and
adding it to the class hierarchy
too.</p></li>
</ol>
<p>I'm not exactly sure what sort of code example you're looking for, but here's a brief one showing meta-classes, inheritance and method resolution:</p>
<pre><code>class MyMeta(type):
def __new__(cls, name, bases, dct):
print "meta: creating %s %s" % (name, bases)
return type.__new__(cls, name, bases, dct)
def meta_meth(cls):
print "MyMeta.meta_meth"
__repr__ = lambda c: c.__name__
class A(object):
__metaclass__ = MyMeta
def __init__(self):
super(A, self).__init__()
print "A init"
def meth(self):
print "A.meth"
class B(object):
__metaclass__ = MyMeta
def __init__(self):
super(B, self).__init__()
print "B init"
def meth(self):
print "B.meth"
class C(A, B):
__metaclass__ = MyMeta
def __init__(self):
super(C, self).__init__()
print "C init"
>>> c_obj = C()
meta: creating A (<type 'object'>,)
meta: creating B (<type 'object'>,)
meta: creating C (A, B)
B init
A init
C init
>>> c_obj.meth()
A.meth
>>> C.meta_meth()
MyMeta.meta_meth
>>> c_obj.meta_meth()
Traceback (most recent call last):
File "mro.py", line 38, in <module>
c_obj.meta_meth()
AttributeError: 'C' object has no attribute 'meta_meth'
</code></pre>
| 14 | 2008-12-28T11:36:08Z | [
"python",
"types",
"metaclass",
"super"
] |
"MetaClass", "__new__", "cls" and "super" - what is the mechanism exactly? | 395,982 | <p>I have read posts like these:</p>
<ol>
<li><a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">What is a metaclass in Python?</a> </li>
<li><a href="http://stackoverflow.com/questions/392160/what-are-your-concrete-use-cases-for-metaclasses-in-python">What are your (concrete) use-cases for metaclasses in Python?</a></li>
<li><a href="http://fuhm.net/super-harmful/" rel="nofollow">Python's Super is nifty, but you can't use it</a></li>
</ol>
<p>But somehow I got confused. Many confusions like:</p>
<p>When and why would I have to do something like the following?</p>
<pre><code># Refer link1
return super(MyType, cls).__new__(cls, name, bases, newattrs)
</code></pre>
<p>or</p>
<pre><code># Refer link2
return super(MetaSingleton, cls).__call__(*args, **kw)
</code></pre>
<p>or</p>
<pre><code># Refer link2
return type(self.__name__ + other.__name__, (self, other), {})
</code></pre>
<p>How does super work exactly?</p>
<p>What is class registry and unregistry in link1 and how exactly does it work? (I thought it has something to do with <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow">singleton</a>. I may be wrong, being from C background. My coding style is still a mix of functional and OO).</p>
<p>What is the flow of class instantiation (subclass, metaclass, super, type) and method invocation (</p>
<pre><code>metaclass->__new__, metaclass->__init__, super->__new__, subclass->__init__ inherited from metaclass
</code></pre>
<p>) with well-commented working code (though the first link is quite close, but it does not talk about cls keyword and super(..) and registry). Preferably an example with multiple inheritance.</p>
<p>P.S.: I made the last part as code because Stack Overflow formatting was converting the text <code>metaclass->__new__</code>
to metaclass-><strong>new</strong></p>
| 23 | 2008-12-28T08:41:45Z | 396,192 | <p>Here's the more pragmatic answer.</p>
<p><strong>It rarely matters</strong></p>
<ol>
<li><p>"<a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">What is a metaclass in Python</a>". Bottom line, <code>type</code> is the metaclass of all classes. You have almost no practical use for this. </p>
<pre><code>class X(object):
pass
type(X) == type
</code></pre></li>
<li><p>"<a href="http://stackoverflow.com/questions/392160/what-are-your-concrete-use-cases-for-metaclasses-in-python">What are your (concrete) use cases for metaclasses in Python?</a>". Bottom line. None.</p></li>
<li><p>"<a href="http://fuhm.net/super-harmful/">Python's Super is nifty, but you can't use it</a>". Interesting note, but little practical value. You'll never have a need for resolving complex multiple inheritance networks. It's easy to prevent this problem from arising by using an explicity <strong>Strategy</strong> design instead of multiple inheritance. </p></li>
</ol>
<p>Here's my experience over the last 7 years of Python programming.</p>
<ol>
<li><p>A class has 1 or more superclasses forming a simple chain from my class to <code>object</code>.</p></li>
<li><p>The concept of "class" is defined by a metaclass named <code>type</code>. I might want to extend the concept of "class", but so far, it's never come up in practice. Not once. <code>type</code> always does the right thing.</p></li>
<li><p>Using <code>super</code> works out really well in practice. It allows a subclass to defer to it's superclass. It happens to show up in these metaclass examples because they're extending the built-in metaclass, <code>type</code>. </p>
<p>However, in all subclass situations, you'll make use of <code>super</code> to extend a superclass.</p></li>
</ol>
<p><strong>Metaclasses</strong></p>
<p>The metaclass issue is this: </p>
<ul>
<li><p>Every object has a reference to it's type definition, or "class".</p></li>
<li><p>A <code>class</code> is, itself, also an object.</p></li>
<li><p>Therefore a object of type <code>class</code> has a reference to it's type or "class". The "class" of a "class" is a metaclass.</p></li>
</ul>
<p>Since a "class" isn't a C++ run-time object, this doesn't happen in C++. It does happen in Java, Smalltalk and Python.</p>
<p>A metaclass defines the behavior of a class object.</p>
<ul>
<li><p>90% of your interaction with a class is to ask the class to create a new object.</p></li>
<li><p>10% of the time, you'll be using class methods or class variables ("static" in C++ or Java parlance.)</p></li>
</ul>
<p>I have found a few use cases for class-level methods. I have almost no use cases for class variables. I've never had a situation to change the way object construction works.</p>
| 9 | 2008-12-28T14:11:03Z | [
"python",
"types",
"metaclass",
"super"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 396,430 | <p>I think the first one is the "obvious" way. It is shorter, clearer, and likely to be faster in many cases because Python's built-in sort is highly optimized.</p>
| 7 | 2008-12-28T17:33:11Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 396,436 | <p>Your second example won't actually work:</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>will only work if b does not contain extra characters not in a. It also does duplicate work if the characters in string a repeat.</p>
<p>If you want to know whether two strings are permutations of the same <em>unique</em> characters, just do:</p>
<pre><code>set(a) == set(b)
</code></pre>
<p>To correct your second example:</p>
<pre><code>all(str1.count(char) == str2.count(char) for char in set(a) | set(b))
</code></pre>
<p>set() objects overload the bitwise OR operator so that it will evaluate to the union of both sets. This will make sure that you will loop over all the characters of both strings once for each character only.</p>
<p>That said, the sorted() method is much simpler and more intuitive, and would be what I would use.</p>
| 5 | 2008-12-28T17:39:08Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 396,438 | <p>Here is a way which is O(n), asymptotically better than the two ways you suggest. </p>
<pre><code>import collections
def same_permutation(a, b):
d = collections.defaultdict(int)
for x in a:
d[x] += 1
for x in b:
d[x] -= 1
return not any(d.itervalues())
## same_permutation([1,2,3],[2,3,1])
#. True
## same_permutation([1,2,3],[2,3,1,1])
#. False
</code></pre>
| 14 | 2008-12-28T17:40:03Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 396,445 | <p>Go with the first one - it's much more straightforward and easier to understand. If you're actually dealing with incredibly large strings and performance is a real issue, then don't use Python, use something like C.</p>
<p>As far as the Zen of Python is concerned, that there should only be one obvious way to do things refers to small, simple things. Obviously for any sufficiently complicated task, there will always be zillions of small variations on ways to do it.</p>
| 1 | 2008-12-28T17:43:14Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 396,460 | <p>Here are some timed executions on very small strings, using two different methods:<br>
1. sorting<br>
2. counting (specifically the original method by @namin).</p>
<pre><code>a, b, c = 'confused', 'unfocused', 'foncused'
sort_method = lambda x,y: sorted(x) == sorted(y)
def count_method(a, b):
d = {}
for x in a:
d[x] = d.get(x, 0) + 1
for x in b:
d[x] = d.get(x, 0) - 1
for v in d.itervalues():
if v != 0:
return False
return True
</code></pre>
<p>Average run times of the 2 methods over 100,000 loops are:</p>
<p>non-match (string a and b)</p>
<pre><code>$ python -m timeit -s 'import temp' 'temp.sort_method(temp.a, temp.b)'
100000 loops, best of 3: 9.72 usec per loop
$ python -m timeit -s 'import temp' 'temp.count_method(temp.a, temp.b)'
10000 loops, best of 3: 28.1 usec per loop
</code></pre>
<p>match (string a and c)</p>
<pre><code>$ python -m timeit -s 'import temp' 'temp.sort_method(temp.a, temp.c)'
100000 loops, best of 3: 9.47 usec per loop
$ python -m timeit -s 'import temp' 'temp.count_method(temp.a, temp.c)'
100000 loops, best of 3: 24.6 usec per loop
</code></pre>
<p>Keep in mind that the strings used are very small. The time complexity of the methods are different, so you'll see different results with very large strings. Choose according to your data, you may even use a combination of the two.</p>
| 2 | 2008-12-28T17:54:00Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 396,523 | <p>"but the first one is slower when (for example) the first char of a is nowhere in b".</p>
<p>This kind of degenerate-case performance analysis is not a good idea. It's a rat-hole of lost time thinking up all kinds of obscure special cases. </p>
<p>Only do the <strong>O</strong>-style "overall" analysis.</p>
<p>Overall, the sorts are <strong>O</strong>( <em>n</em> log( <em>n</em> ) ).</p>
<p>The <code>a.count(char) for char in a</code> solution is <strong>O</strong>( <em>n</em> <sup>2</sup> ). Each count pass is a full examination of the string.</p>
<p>If some obscure special case happens to be faster -- or slower, that's possibly interesting. But it only matters when you know the frequency of your obscure special cases. When analyzing sort algorithms, it's important to note that a fair number of sorts involve data that's already in the proper order (either by luck or by a clever design), so sort performance on pre-sorted data matters.</p>
<p>In your obscure special case ("the first char of a is nowhere in b") is this frequent enough to matter? If it's just a special case you thought of, set it aside. If it's a fact about your data, then consider it.</p>
| 14 | 2008-12-28T18:55:35Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 396,570 | <p>heuristically you're probably better to split them off based on string size.</p>
<p>Pseudocode:</p>
<pre><code>returnvalue = false
if len(a) == len(b)
if len(a) < threshold
returnvalue = (sorted(a) == sorted(b))
else
returnvalue = naminsmethod(a, b)
return returnvalue
</code></pre>
<p>If performance is critical, and string size can be large or small then this is what I'd do.</p>
<p>It's pretty common to split things like this based on input size or type. Algorithms have different strengths or weaknesses and it would be foolish to use one where another would be better... In this case Namin's method is O(n), but has a larger constant factor than the O(n log n) sorted method. </p>
| 7 | 2008-12-28T19:36:38Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 397,055 | <p>This is a PHP function I wrote about a week ago which checks if two words are anagrams. How would this compare (if implemented the same in python) to the other methods suggested? Comments?</p>
<pre><code>public function is_anagram($word1, $word2) {
$letters1 = str_split($word1);
$letters2 = str_split($word2);
if (count($letters1) == count($letters2)) {
foreach ($letters1 as $letter) {
$index = array_search($letter, $letters2);
if ($index !== false) {
unset($letters2[$index]);
}
else { return false; }
}
return true;
}
return false;
}
</code></pre>
<p><hr /></p>
<p>Here's a <em>literal</em> translation to Python of the PHP version (by JFS):</p>
<pre><code>def is_anagram(word1, word2):
letters2 = list(word2)
if len(word1) == len(word2):
for letter in word1:
try:
del letters2[letters2.index(letter)]
except ValueError:
return False
return True
return False
</code></pre>
<p>Comments: </p>
<pre>
1. The algorithm is O(N**2). Compare it to @namin's version (it is O(N)).
2. The multiple returns in the function look horrible.
</pre>
| 0 | 2008-12-29T03:02:50Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 397,334 | <p>This version is faster than any examples presented so far except it is 20% slower than <code>sorted(x) == sorted(y)</code> for short strings. It depends on use cases but generally 20% performance gain is insufficient to justify a complication of the code by using different version for short and long strings (as in @patros's answer).</p>
<p>It doesn't use <code>len</code> so it accepts any iterable therefore it works even for data that do not fit in memory e.g., given two big text files with many repeated lines it answers whether the files have the same lines (lines can be in any order).</p>
<pre><code>def isanagram(iterable1, iterable2):
d = {}
get = d.get
for c in iterable1:
d[c] = get(c, 0) + 1
try:
for c in iterable2:
d[c] -= 1
return not any(d.itervalues())
except KeyError:
return False
</code></pre>
<p>It is unclear why this version is faster then <code>defaultdict</code> (@namin's) one for large <code>iterable1</code> (tested on 25MB thesaurus).</p>
<p>If we replace <code>get</code> in the loop by <code>try: ... except KeyError</code> then it performs 2 times slower for short strings i.e. when there are few duplicates.</p>
| 0 | 2008-12-29T08:34:26Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 408,151 | <p>Sorry that my code is not in Python, I have never used it, but I am sure this can be easily translated into python. I believe this is faster than all the other examples already posted. It is also O(n), but stops as soon as possible:</p>
<pre><code>public boolean isPermutation(String a, String b) {
if (a.length() != b.length()) {
return false;
}
int[] charCount = new int[256];
for (int i = 0; i < a.length(); ++i) {
++charCount[a.charAt(i)];
}
for (int i = 0; i < b.length(); ++i) {
if (--charCount[b.charAt(i)] < 0) {
return false;
}
}
return true;
}
</code></pre>
<p>First I don't use a dictionary but an array of size 256 for all the characters. Accessing the index should be much faster. Then when the second string is iterated, I immediately return false when the count gets below 0. When the second loop has finished, you can be sure that the strings are a permutation, because the strings have equal length and no character was used more often in b compared to a.</p>
| 1 | 2009-01-02T22:11:40Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 408,162 | <p>Here's martinus code in python. It only works for ascii strings:</p>
<pre><code>def is_permutation(a, b):
if len(a) != len(b):
return False
char_count = [0] * 256
for c in a:
char_count[ord(c)] += 1
for c in b:
char_count[ord(c)] -= 1
if char_count[ord(c)] < 0:
return False
return True
</code></pre>
| 1 | 2009-01-02T22:17:38Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 426,629 | <p>I did a pretty thorough comparison in Java with all words in a book I had. The counting method beats the sorting method in every way. The results:</p>
<pre><code>Testing against 9227 words.
Permutation testing by sorting ... done. 18.582 s
Permutation testing by counting ... done. 14.949 s
</code></pre>
<p>If anyone wants the algorithm and test data set, comment away.</p>
| 1 | 2009-01-09T00:26:04Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 2,021,817 | <p>In Python 3.1/2.7 you can just use <code>collections.Counter(a) == collections.Counter(b)</code>.</p>
<p>But <code>sorted(a) == sorted(b)</code> is still the most obvious IMHO. You are talking about permutations - changing order - so sorting is the obvious operation to erase that difference.</p>
| 1 | 2010-01-07T16:23:02Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 19,896,549 | <p>This is derived from <a href="http://stackoverflow.com/a/396570/72321">@patros' answer</a>.</p>
<pre><code>from collections import Counter
def is_anagram(a, b, threshold=1000000):
"""Returns true if one sequence is a permutation of the other.
Ignores whitespace and character case.
Compares sorted sequences if the length is below the threshold,
otherwise compares dictionaries that contain the frequency of the
elements.
"""
a, b = a.strip().lower(), b.strip().lower()
length_a, length_b = len(a), len(b)
if length_a != length_b:
return False
if length_a < threshold:
return sorted(a) == sorted(b)
return Counter(a) == Counter(b) # Or use @namin's method if you don't want to create two dictionaries and don't mind the extra typing.
</code></pre>
| 0 | 2013-11-10T23:24:08Z | [
"algorithm",
"python"
] |
Checking if two strings are permutations of each other in Python | 396,421 | <p>I'm checking if two strings <code>a</code> and <code>b</code> are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:</p>
<pre><code>sorted(a) == sorted(b)
</code></pre>
<p>and</p>
<pre><code>all(a.count(char) == b.count(char) for char in a)
</code></pre>
<p>but the first one is slower when (for example) the first char of <code>a</code> is nowhere in <code>b</code>, and the second is slower when they are actually permutations.</p>
<p>Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?</p>
| 15 | 2008-12-28T17:25:17Z | 35,800,655 | <p>In Swift (or another languages implementation), you could look at the encoded values ( in this case Unicode) and see if they match. </p>
<p>Something like:</p>
<pre><code>let string1EncodedValues = "Hello".unicodeScalars.map() {
//each encoded value
$0
//Now add the values
}.reduce(0){ total, value in
total + value.value
}
let string2EncodedValues = "oellH".unicodeScalars.map() {
$0
}.reduce(0) { total, value in
total + value.value
}
let equalStrings = string1EncodedValues == string2EncodedValues ? true : false
</code></pre>
<p>You will need to handle spaces and cases as needed. </p>
| 0 | 2016-03-04T16:07:49Z | [
"algorithm",
"python"
] |
Python-PostgreSQL psycopg2 interface --> executemany | 396,455 | <p>I am currently analyzing a wikipedia dump file; I am extracting a bunch of data from it using python and persisting it into a PostgreSQL db. I am always trying to make things go faster for this file is huge (18GB). In order to interface with PostgreSQL, I am using psycopg2, but this module seems to mimic many other such DBAPIs.</p>
<p>Anyway, I have a question concerning cursor.executemany(command, values); it seems to me like executing an executemany once every 1000 values or so is better than calling cursor.execute(command % value) for each of these 5 million values (please confirm or correct me!).</p>
<p>But, you see, I am using an executemany to INSERT 1000 rows into a table which has a UNIQUE integrity constraint; this constraint is not verified in python beforehand, for this would either require me to SELECT all the time (this seems counter productive) or require me to get more than 3 GB of RAM. All this to say that I count on Postgres to warn me when my script tried to INSERT an already existing row via catching the psycopg2.DatabaseError. </p>
<p>When my script detects such a non-UNIQUE INSERT, it connection.rollback() (which makes ups to 1000 rows everytime, and kind of makes the executemany worthless) and then INSERTs all values one by one.</p>
<p>Since psycopg2 is so poorly documented (as are so many great modules...), I cannot find an efficient and effective workaround. I have reduced the number of values INSERTed per executemany from 1000 to 100 in order to reduce the likeliness of a non-UNIQUE INSERT per executemany, but I am pretty certain their is a way to just tell psycopg2 to ignore these execeptions or to tell the cursor to continue the executemany. </p>
<p>Basically, this seems like the kind of problem which has a solution so easy and popular, that all I can do is ask in order to learn about it.</p>
<p>Thanks again!</p>
| 6 | 2008-12-28T17:51:48Z | 396,824 | <p>"When my script detects such a non-UNIQUE INSERT, it connection.rollback() (which makes ups to 1000 rows everytime, and kind of makes the executemany worthless) and then INSERTs all values one by one."</p>
<p>The question doesn't really make a lot of sense.</p>
<p>Does EVERY block of 1,000 rows fail due to non-unique rows? </p>
<p>Does 1 block of 1,000 rows fail (out 5,000 such blocks)? If so, then the execute many helps for 4,999 out of 5,000 and is far from "worthless".</p>
<p>Are you worried about this non-Unique insert? Or do you have actual statistics on the number of times this happens?</p>
<p>If you've switched from 1,000 row blocks to 100 row blocks, you can -- obviously -- determine if there's a performance advantage for 1,000 row blocks, 100 row blocks and 1 row blocks.</p>
<p>Please actually run the actual program with actual database and different size blocks and post the numbers.</p>
| 0 | 2008-12-28T23:06:15Z | [
"python",
"postgresql",
"database",
"psycopg"
] |
Python-PostgreSQL psycopg2 interface --> executemany | 396,455 | <p>I am currently analyzing a wikipedia dump file; I am extracting a bunch of data from it using python and persisting it into a PostgreSQL db. I am always trying to make things go faster for this file is huge (18GB). In order to interface with PostgreSQL, I am using psycopg2, but this module seems to mimic many other such DBAPIs.</p>
<p>Anyway, I have a question concerning cursor.executemany(command, values); it seems to me like executing an executemany once every 1000 values or so is better than calling cursor.execute(command % value) for each of these 5 million values (please confirm or correct me!).</p>
<p>But, you see, I am using an executemany to INSERT 1000 rows into a table which has a UNIQUE integrity constraint; this constraint is not verified in python beforehand, for this would either require me to SELECT all the time (this seems counter productive) or require me to get more than 3 GB of RAM. All this to say that I count on Postgres to warn me when my script tried to INSERT an already existing row via catching the psycopg2.DatabaseError. </p>
<p>When my script detects such a non-UNIQUE INSERT, it connection.rollback() (which makes ups to 1000 rows everytime, and kind of makes the executemany worthless) and then INSERTs all values one by one.</p>
<p>Since psycopg2 is so poorly documented (as are so many great modules...), I cannot find an efficient and effective workaround. I have reduced the number of values INSERTed per executemany from 1000 to 100 in order to reduce the likeliness of a non-UNIQUE INSERT per executemany, but I am pretty certain their is a way to just tell psycopg2 to ignore these execeptions or to tell the cursor to continue the executemany. </p>
<p>Basically, this seems like the kind of problem which has a solution so easy and popular, that all I can do is ask in order to learn about it.</p>
<p>Thanks again!</p>
| 6 | 2008-12-28T17:51:48Z | 550,849 | <p>just copy all the data into a scratch table with the psql \copy command, or use the psycopg cursor.copy_in() method. Then:</p>
<pre><code>insert into mytable
select * from (
select distinct *
from scratch
) uniq
where not exists (
select 1
from mytable
where mytable.mykey = uniq.mykey
);
</code></pre>
<p>This will dedup and runs much faster than any combination of inserts.</p>
<p>-dg</p>
| 8 | 2009-02-15T13:13:40Z | [
"python",
"postgresql",
"database",
"psycopg"
] |
Python-PostgreSQL psycopg2 interface --> executemany | 396,455 | <p>I am currently analyzing a wikipedia dump file; I am extracting a bunch of data from it using python and persisting it into a PostgreSQL db. I am always trying to make things go faster for this file is huge (18GB). In order to interface with PostgreSQL, I am using psycopg2, but this module seems to mimic many other such DBAPIs.</p>
<p>Anyway, I have a question concerning cursor.executemany(command, values); it seems to me like executing an executemany once every 1000 values or so is better than calling cursor.execute(command % value) for each of these 5 million values (please confirm or correct me!).</p>
<p>But, you see, I am using an executemany to INSERT 1000 rows into a table which has a UNIQUE integrity constraint; this constraint is not verified in python beforehand, for this would either require me to SELECT all the time (this seems counter productive) or require me to get more than 3 GB of RAM. All this to say that I count on Postgres to warn me when my script tried to INSERT an already existing row via catching the psycopg2.DatabaseError. </p>
<p>When my script detects such a non-UNIQUE INSERT, it connection.rollback() (which makes ups to 1000 rows everytime, and kind of makes the executemany worthless) and then INSERTs all values one by one.</p>
<p>Since psycopg2 is so poorly documented (as are so many great modules...), I cannot find an efficient and effective workaround. I have reduced the number of values INSERTed per executemany from 1000 to 100 in order to reduce the likeliness of a non-UNIQUE INSERT per executemany, but I am pretty certain their is a way to just tell psycopg2 to ignore these execeptions or to tell the cursor to continue the executemany. </p>
<p>Basically, this seems like the kind of problem which has a solution so easy and popular, that all I can do is ask in order to learn about it.</p>
<p>Thanks again!</p>
| 6 | 2008-12-28T17:51:48Z | 675,865 | <p>using a MERGE statement instead of an INSERT one would solve your problem.</p>
| -1 | 2009-03-24T01:32:07Z | [
"python",
"postgresql",
"database",
"psycopg"
] |
Python-PostgreSQL psycopg2 interface --> executemany | 396,455 | <p>I am currently analyzing a wikipedia dump file; I am extracting a bunch of data from it using python and persisting it into a PostgreSQL db. I am always trying to make things go faster for this file is huge (18GB). In order to interface with PostgreSQL, I am using psycopg2, but this module seems to mimic many other such DBAPIs.</p>
<p>Anyway, I have a question concerning cursor.executemany(command, values); it seems to me like executing an executemany once every 1000 values or so is better than calling cursor.execute(command % value) for each of these 5 million values (please confirm or correct me!).</p>
<p>But, you see, I am using an executemany to INSERT 1000 rows into a table which has a UNIQUE integrity constraint; this constraint is not verified in python beforehand, for this would either require me to SELECT all the time (this seems counter productive) or require me to get more than 3 GB of RAM. All this to say that I count on Postgres to warn me when my script tried to INSERT an already existing row via catching the psycopg2.DatabaseError. </p>
<p>When my script detects such a non-UNIQUE INSERT, it connection.rollback() (which makes ups to 1000 rows everytime, and kind of makes the executemany worthless) and then INSERTs all values one by one.</p>
<p>Since psycopg2 is so poorly documented (as are so many great modules...), I cannot find an efficient and effective workaround. I have reduced the number of values INSERTed per executemany from 1000 to 100 in order to reduce the likeliness of a non-UNIQUE INSERT per executemany, but I am pretty certain their is a way to just tell psycopg2 to ignore these execeptions or to tell the cursor to continue the executemany. </p>
<p>Basically, this seems like the kind of problem which has a solution so easy and popular, that all I can do is ask in order to learn about it.</p>
<p>Thanks again!</p>
| 6 | 2008-12-28T17:51:48Z | 11,059,350 | <p>I had the same problem and searched here for many days to collect a lot of hints to form a complete solution. Even if the question outdated, I hope this will be useful to others.</p>
<p>1) Forget things about removing indexes/constraints & recreating them later, benefits are marginal or worse.</p>
<p>2) executemany is better than execute as it makes for you the prepare statement. You can get the same results yourself with a command like the following to gain 300% speed:</p>
<pre><code># To run only once:
sqlCmd = """PREPARE myInsert (int, timestamp, real, text) AS
INSERT INTO myBigTable (idNumber, date_obs, result, user)
SELECT $1, $2, $3, $4 WHERE NOT EXISTS
(SELECT 1 FROM myBigTable WHERE (idNumber, date_obs, user)=($1, $2, $4));"""
curPG.execute(sqlCmd)
cptInsert = 0 # To let you commit from time to time
#... inside the big loop:
curPG.execute("EXECUTE myInsert(%s,%s,%s,%s);", myNewRecord)
allreadyExists = (curPG.rowcount < 1)
if not allreadyExists:
cptInsert += 1
if cptInsert % 10000 == 0:
conPG.commit()
</code></pre>
<p>This dummy table example has an unique constraint on (idNumber, date_obs, user).</p>
<p>3) The best solution is to use COPY_FROM and a TRIGGER to manage the unique key BEFORE INSERT. This gave me 36x more speed. I started with normal inserts at 500 records/sec. and with "copy", I got over 18,000 records/sec. Sample code in Python with Psycopg2:</p>
<pre><code>ioResult = StringIO.StringIO() #To use a virtual file as a buffer
cptInsert = 0 # To let you commit from time to time - Memory has limitations
#... inside the big loop:
print >> ioResult, "\t".join(map(str, myNewRecord))
cptInsert += 1
if cptInsert % 10000 == 0:
ioResult = flushCopyBuffer(ioResult, curPG)
#... after the loop:
ioResult = flushCopyBuffer(ioResult, curPG)
def flushCopyBuffer(bufferFile, cursorObj):
bufferFile.seek(0) # Little detail where lures the deamon...
cursorObj.copy_from(bufferFile, 'myBigTable',
columns=('idNumber', 'date_obs', 'value', 'user'))
cursorObj.connection.commit()
bufferFile.close()
bufferFile = StringIO.StringIO()
return bufferFile
</code></pre>
<p>That's it for the Python part. Now the Postgresql trigger to not have exception psycopg2.IntegrityError and then all the COPY command's records rejected:</p>
<pre><code>CREATE OR REPLACE FUNCTION chk_exists()
RETURNS trigger AS $BODY$
DECLARE
curRec RECORD;
BEGIN
-- Check if record's key already exists or is empty (file's last line is)
IF NEW.idNumber IS NULL THEN
RETURN NULL;
END IF;
SELECT INTO curRec * FROM myBigTable
WHERE (idNumber, date_obs, user) = (NEW.idNumber, NEW.date_obs, NEW.user);
IF NOT FOUND THEN -- OK keep it
RETURN NEW;
ELSE
RETURN NULL; -- Oups throw it or update the current record
END IF;
END;
$BODY$ LANGUAGE plpgsql;
</code></pre>
<p>Now link this function to the trigger of your table:</p>
<pre><code>CREATE TRIGGER chk_exists_before_insert
BEFORE INSERT ON myBigTable FOR EACH ROW EXECUTE PROCEDURE chk_exists();
</code></pre>
<p>This seems like a lot of work but Postgresql is a very fast beast when it doesn't have to interpret SQL over and over. Have fun.</p>
| 3 | 2012-06-15T23:24:35Z | [
"python",
"postgresql",
"database",
"psycopg"
] |
Desktop graphics - or "skinned" windows | 396,791 | <p>I'm looking for a way to draw animations right on the desktop. No window frames and with transparent background.</p>
<p>I'm using Python in windows XP for it, but it doesn't have to be cross platform, although it'd be a nice bonus.</p>
<p>Does anyone know about a python library that can do this?</p>
| 3 | 2008-12-28T22:41:47Z | 396,900 | <p>If you want a frameless window, there are several options. For example, pygame can be initialized with the following flag:</p>
<pre><code>pygame.init()
screen = pygame.display.set_mode(size=(640,480), pygame.NOFRAME)
</code></pre>
<p>Your question doesn't make it clear if you're looking for a transparent surface, though.</p>
| 2 | 2008-12-29T00:25:56Z | [
"python",
"graphics",
"desktop",
"skinning",
"shaped-window"
] |
Desktop graphics - or "skinned" windows | 396,791 | <p>I'm looking for a way to draw animations right on the desktop. No window frames and with transparent background.</p>
<p>I'm using Python in windows XP for it, but it doesn't have to be cross platform, although it'd be a nice bonus.</p>
<p>Does anyone know about a python library that can do this?</p>
| 3 | 2008-12-28T22:41:47Z | 455,878 | <p>I found that wxPython was able to do this after all. You always find things when you've stopped looking for some reason. I stumbled upon the shaped window setting when I was looking through the demo file for wxPython.</p>
<p>I haven't been able to find any good tutorials for it on the net, but the code in the demo should be enough to get started. It should even be platform independent.</p>
<p><a href="http://wxpython.org" rel="nofollow">wxPython official site</a></p>
<p><a href="http://sourceforge.net/project/showfiles.php?group_id=10718" rel="nofollow">wxPython downloads (including demo files)</a></p>
| 1 | 2009-01-18T20:57:58Z | [
"python",
"graphics",
"desktop",
"skinning",
"shaped-window"
] |
How to instantiate a class in python | 396,856 | <p>So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class.</p>
<pre><code>class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
#now use the function average from the mystuff class
print mystuff.average(9,18,27)
File "class.py", line 7, in <module>
print mystuff.average(9,18,27)
TypeError: unbound method average() must be called with mystuff instance as first argument (got int instance instead)
</code></pre>
<p>What's wrong?</p>
| 41 | 2008-12-28T23:36:46Z | 396,871 | <p>You can instantiate the class by declaring a variable and calling the class as if it were a function:</p>
<pre><code>x = mystuff()
print x.average(9,18,27)
</code></pre>
<p>However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter when it calls the function. So if you run your code right now, you'll see this error message:</p>
<pre><code>TypeError: average() takes exactly 3 arguments (4 given)
</code></pre>
<p>To fix this, you'll need to modify the definition of the average method to take four parameters. The first parameter is an object reference, and the remaining 3 parameters would be for the 3 numbers.</p>
| 46 | 2008-12-28T23:48:05Z | [
"python",
"python-3.x"
] |
How to instantiate a class in python | 396,856 | <p>So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class.</p>
<pre><code>class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
#now use the function average from the mystuff class
print mystuff.average(9,18,27)
File "class.py", line 7, in <module>
print mystuff.average(9,18,27)
TypeError: unbound method average() must be called with mystuff instance as first argument (got int instance instead)
</code></pre>
<p>What's wrong?</p>
| 41 | 2008-12-28T23:36:46Z | 396,875 | <p>In python member function of a class need explicit <code>self</code> argument. Same as implicit <code>this</code> pointer in C++. For more details please check out <a href="http://diveintopython.net/object_oriented_framework/defining_classes.html" rel="nofollow">this</a> page.</p>
| 1 | 2008-12-28T23:50:42Z | [
"python",
"python-3.x"
] |
How to instantiate a class in python | 396,856 | <p>So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class.</p>
<pre><code>class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
#now use the function average from the mystuff class
print mystuff.average(9,18,27)
File "class.py", line 7, in <module>
print mystuff.average(9,18,27)
TypeError: unbound method average() must be called with mystuff instance as first argument (got int instance instead)
</code></pre>
<p>What's wrong?</p>
| 41 | 2008-12-28T23:36:46Z | 396,876 | <p>From your example, it seems to me you want to use a static method.</p>
<pre><code>class mystuff:
@staticmethod
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
print mystuff.average(9,18,27)
</code></pre>
<p>Please note that an heavy usage of static methods in python is usually a symptom of some bad smell - if you really need functions, then declare them directly on module level.</p>
| 30 | 2008-12-28T23:51:21Z | [
"python",
"python-3.x"
] |
How to instantiate a class in python | 396,856 | <p>So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class.</p>
<pre><code>class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
#now use the function average from the mystuff class
print mystuff.average(9,18,27)
File "class.py", line 7, in <module>
print mystuff.average(9,18,27)
TypeError: unbound method average() must be called with mystuff instance as first argument (got int instance instead)
</code></pre>
<p>What's wrong?</p>
| 41 | 2008-12-28T23:36:46Z | 396,884 | <p>You never created an instance.</p>
<p>You've defined average as an instance method, thus, in order to use average you need to create an instance first.</p>
| -1 | 2008-12-29T00:03:20Z | [
"python",
"python-3.x"
] |
How to instantiate a class in python | 396,856 | <p>So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class.</p>
<pre><code>class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
#now use the function average from the mystuff class
print mystuff.average(9,18,27)
File "class.py", line 7, in <module>
print mystuff.average(9,18,27)
TypeError: unbound method average() must be called with mystuff instance as first argument (got int instance instead)
</code></pre>
<p>What's wrong?</p>
| 41 | 2008-12-28T23:36:46Z | 396,968 | <p>You need to spend a little more time on some fundamentals of object-oriented programming.</p>
<p>This sounds harsh, but it's important.</p>
<ul>
<li><p>Your class definition is incorrect -- although the syntax happens to be acceptable. The definition is simply wrong. </p></li>
<li><p>Your use of the class to create an object is entirely missing.</p></li>
<li><p>Your use of a class to do a calculation is inappropriate. This kind of thing can be done, but it requires the advanced concept of a <code>@staticmehod</code>.</p></li>
</ul>
<p>Since your example code is wrong in so many ways, you can't get a tidy "fix this" answer. There are too many things to fix.</p>
<p>You'll need to look at better examples of class definitions. It's not clear what source material you're using to learn from, but whatever book you're reading is either wrong or incomplete.</p>
<p>Please discard whatever book or source you're using and find a better book. Seriously. They've mislead you on how a class definition looks and how it's used.</p>
<p>You might want to look at <a href="http://homepage.mac.com/s_lott/books/nonprog/htmlchunks/pt11.html" rel="nofollow">http://homepage.mac.com/s_lott/books/nonprog/htmlchunks/pt11.html</a> for a better introduction to classes, objects and Python.</p>
| 1 | 2008-12-29T01:46:17Z | [
"python",
"python-3.x"
] |
How to instantiate a class in python | 396,856 | <p>So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class.</p>
<pre><code>class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
#now use the function average from the mystuff class
print mystuff.average(9,18,27)
File "class.py", line 7, in <module>
print mystuff.average(9,18,27)
TypeError: unbound method average() must be called with mystuff instance as first argument (got int instance instead)
</code></pre>
<p>What's wrong?</p>
| 41 | 2008-12-28T23:36:46Z | 397,076 | <p>Every function inside a class, and every class variable must take the <em>self</em> argument as pointed.</p>
<pre><code>class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
def sum(self,a,b):
return a+b
print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok
</code></pre>
<p>If class variables are involved:</p>
<pre><code> class mystuff:
def setVariables(self,a,b):
self.x = a
self.y = b
return a+b
def mult(self):
return x * y # This line will raise an error
def sum(self):
return self.x + self.y
print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
print mystuff.mult() # should raise error
print mystuff.sum() # should be ok
</code></pre>
| 4 | 2008-12-29T03:23:37Z | [
"python",
"python-3.x"
] |
How to instantiate a class in python | 396,856 | <p>So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class.</p>
<pre><code>class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
#now use the function average from the mystuff class
print mystuff.average(9,18,27)
File "class.py", line 7, in <module>
print mystuff.average(9,18,27)
TypeError: unbound method average() must be called with mystuff instance as first argument (got int instance instead)
</code></pre>
<p>What's wrong?</p>
| 41 | 2008-12-28T23:36:46Z | 23,840,853 | <p>To minimally modify your example, you could amend the code to:</p>
<pre><code>class myclass(object):
def __init__(self): # this method creates the class object.
pass
def average(self,a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
mystuff=myclass() # by default the __init__ method is then called.
print mystuff.average(a,b,c)
</code></pre>
<p>Or to expand it more fully, allowing you to add other methods.</p>
<pre><code>#!/usr/bin/env python
import sys
class myclass(object):
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def average(self): #get the average of three numbers
result=self.a+self.b+self.c
result=result/3
return result
a=9
b=18
c=27
mystuff=myclass(a, b, c)
print mystuff.average()
</code></pre>
| 7 | 2014-05-24T02:51:04Z | [
"python",
"python-3.x"
] |
In Python, how do I find the date of the first Monday of a given week? | 396,913 | <p>If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?</p>
<p>Many thanks</p>
| 26 | 2008-12-29T00:42:56Z | 396,926 | <pre><code>>>> import time
>>> time.asctime(time.strptime('2008 50 1', '%Y %W %w'))
'Mon Dec 15 00:00:00 2008'
</code></pre>
<p>Assuming the first day of your week is Monday, use <code>%U</code> instead of <code>%W</code> if the first day of your week is Sunday. See the documentation for <a href="http://docs.python.org/library/time.html#time.strptime">strptime</a> for details.</p>
<p><strong>Update:</strong> Fixed week number. The <code>%W</code> directive is 0-based so week 51 would be entered as 50, not 51.</p>
| 33 | 2008-12-29T01:05:22Z | [
"python",
"datetime"
] |
In Python, how do I find the date of the first Monday of a given week? | 396,913 | <p>If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?</p>
<p>Many thanks</p>
| 26 | 2008-12-29T00:42:56Z | 396,927 | <p>This seems to work, assuming week one can have a Monday falling on a day in the last year. </p>
<pre><code>from datetime import date, timedelta
def get_first_dow(year, week):
d = date(year, 1, 1)
d = d - timedelta(d.weekday())
dlt = timedelta(days = (week - 1) * 7)
return d + dlt
</code></pre>
| 8 | 2008-12-29T01:05:54Z | [
"python",
"datetime"
] |
In Python, how do I find the date of the first Monday of a given week? | 396,913 | <p>If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?</p>
<p>Many thanks</p>
| 26 | 2008-12-29T00:42:56Z | 396,928 | <p>Use the string formatting found in the time module. <a href="http://www.python.org/doc/current/library/time.html#time.strftime" rel="nofollow">Detailed explanation of the formats used</a></p>
<pre><code>>>> import time
>>> time.strptime("51 08 1","%U %y %w")
(2008, 12, 22, 0, 0, 0, 0, 357, -1)
</code></pre>
<p>The date returned is off by one week according to the calendar on my computer, maybe that is because weeks are indexed from 0?</p>
| 0 | 2008-12-29T01:06:16Z | [
"python",
"datetime"
] |
In Python, how do I find the date of the first Monday of a given week? | 396,913 | <p>If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?</p>
<p>Many thanks</p>
| 26 | 2008-12-29T00:42:56Z | 1,287,862 | <p>PEZ's and Gerald Kaszuba's solutions work under assumption that January 1st will always be in the first week of a given year. This assumption is not correct for ISO calendar, see <a href="http://docs.python.org/library/datetime.html#datetime.date.isocalendar">Python's docs</a> for reference. For example, in ISO calendar, week 1 of 2010 actually starts on Jan 4, and Jan 1 of 2010 is in week 53 of 2009. An ISO calendar-compatible solution:</p>
<pre><code>from datetime import date, timedelta
def week_start_date(year, week):
d = date(year, 1, 1)
delta_days = d.isoweekday() - 1
delta_weeks = week
if year == d.isocalendar()[0]:
delta_weeks -= 1
delta = timedelta(days=-delta_days, weeks=delta_weeks)
return d + delta
</code></pre>
| 28 | 2009-08-17T13:07:00Z | [
"python",
"datetime"
] |
In Python, how do I find the date of the first Monday of a given week? | 396,913 | <p>If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?</p>
<p>Many thanks</p>
| 26 | 2008-12-29T00:42:56Z | 1,983,884 | <p>I have slightly modified the script of Vaidas K. in a way that it will return the beginning of the week and the end day of the week.</p>
<pre><code>from datetime import datetime, date, timedelta
def weekbegend(year, week):
"""
Calcul du premier et du dernier jour de la semaine ISO
"""
d = date(year, 1, 1)
delta_days = d.isoweekday() - 1
delta_weeks = week
if year == d.isocalendar()[0]:
delta_weeks -= 1
# delta for the beginning of the week
delta = timedelta(days=-delta_days, weeks=delta_weeks)
weekbeg = d + delta
# delta2 for the end of the week
delta2 = timedelta(days=6-delta_days, weeks=delta_weeks)
weekend = d + delta2
return weekbeg, weekend
</code></pre>
<p>Soyou can use it that way.</p>
<pre><code>weekbeg, weekend = weekbegend(2009, 1)
begweek = weekbeg.strftime("%A %d %B %Y")
endweek = weekend.strftime("%A %d %B %Y")
</code></pre>
| 4 | 2009-12-31T04:10:29Z | [
"python",
"datetime"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.