title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
os.walk without digging into directories below
229,186
<p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p> <pre><code>def _dir_list(self, dir_name, whitelist): outputList = [] for root, dirs, files in os.walk(dir_name): for f in files: if os.path.splitext(f)[1] in whitelist: outputList....
50
2008-10-23T10:03:59Z
32,747,111
<p>There is a catch when using listdir. The os.path.isdir(identifier) must be an absolute path. To pick subdirectories you do:</p> <pre><code>for dirname in os.listdir(rootdir): if os.path.isdir(os.path.join(rootdir, dirname)): print("I got a subdirectory: %s" % dirname) </code></pre> <p>The alternative is t...
0
2015-09-23T18:42:26Z
[ "python", "file", "os.walk" ]
os.walk without digging into directories below
229,186
<p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p> <pre><code>def _dir_list(self, dir_name, whitelist): outputList = [] for root, dirs, files in os.walk(dir_name): for f in files: if os.path.splitext(f)[1] in whitelist: outputList....
50
2008-10-23T10:03:59Z
36,358,596
<p>In Python 3, I was able to do this:</p> <pre><code>import os dir = "/path/to/files/" #List all files immediately under this folder: print ( next( os.walk(dir) )[2] ) #List all folders immediately under this folder: print ( next( os.walk(dir) )[1] ) </code></pre>
1
2016-04-01T14:13:41Z
[ "python", "file", "os.walk" ]
os.walk without digging into directories below
229,186
<p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p> <pre><code>def _dir_list(self, dir_name, whitelist): outputList = [] for root, dirs, files in os.walk(dir_name): for f in files: if os.path.splitext(f)[1] in whitelist: outputList....
50
2008-10-23T10:03:59Z
37,008,598
<pre><code>for path, dirs, files in os.walk('.'): print path, dirs, files del dirs[:] # go only one level deep </code></pre>
3
2016-05-03T15:43:13Z
[ "python", "file", "os.walk" ]
os.walk without digging into directories below
229,186
<p>How do I limit <code>os.walk</code> to only return files in the directory I provide it?</p> <pre><code>def _dir_list(self, dir_name, whitelist): outputList = [] for root, dirs, files in os.walk(dir_name): for f in files: if os.path.splitext(f)[1] in whitelist: outputList....
50
2008-10-23T10:03:59Z
39,118,773
<p>You can use this snippet</p> <pre><code>for root, dirs, files in os.walk(directory): if level &gt; 0: # do some stuff else: break level-=1 </code></pre>
0
2016-08-24T08:56:51Z
[ "python", "file", "os.walk" ]
Python Find Question
229,352
<p>I am using Python to extract the filename from a link using rfind like below:</p> <pre><code>url = "http://www.google.com/test.php" print url[url.rfind("/") +1 : ] </code></pre> <p>This works ok with links without a / at the end of them and returns "test.php". I have encountered links with / at the end like so "...
2
2008-10-23T11:15:42Z
229,386
<p>You could use</p> <pre><code>print url[url.rstrip("/").rfind("/") +1 : ] </code></pre>
-1
2008-10-23T11:28:54Z
[ "python", "url" ]
Python Find Question
229,352
<p>I am using Python to extract the filename from a link using rfind like below:</p> <pre><code>url = "http://www.google.com/test.php" print url[url.rfind("/") +1 : ] </code></pre> <p>This works ok with links without a / at the end of them and returns "test.php". I have encountered links with / at the end like so "...
2
2008-10-23T11:15:42Z
229,394
<p>Filenames with a slash at the end are technically still path definitions and indicate that the index file is to be read. If you actually have one that' ends in <code>test.php/</code>, I would consider that an error. In any case, you can strip the / from the end before running your code as follows:</p> <pre><code>...
1
2008-10-23T11:31:12Z
[ "python", "url" ]
Python Find Question
229,352
<p>I am using Python to extract the filename from a link using rfind like below:</p> <pre><code>url = "http://www.google.com/test.php" print url[url.rfind("/") +1 : ] </code></pre> <p>This works ok with links without a / at the end of them and returns "test.php". I have encountered links with / at the end like so "...
2
2008-10-23T11:15:42Z
229,399
<p>There is a library called <a href="http://www.python.org/doc/2.4/lib/module-urlparse.html" rel="nofollow">urlparse</a> that will parse the url for you, but still doesn't remove the / at the end so one of the above will be the best option</p>
0
2008-10-23T11:32:14Z
[ "python", "url" ]
Python Find Question
229,352
<p>I am using Python to extract the filename from a link using rfind like below:</p> <pre><code>url = "http://www.google.com/test.php" print url[url.rfind("/") +1 : ] </code></pre> <p>This works ok with links without a / at the end of them and returns "test.php". I have encountered links with / at the end like so "...
2
2008-10-23T11:15:42Z
229,401
<p>Just removing the slash at the end won't work, as you can probably have a URL that looks like this:</p> <pre><code>http://www.google.com/test.php?filepath=tests/hey.xml </code></pre> <p>...in which case you'll get back "hey.xml". Instead of manually checking for this, you can use <b>urlparse</b> to get rid of the ...
9
2008-10-23T11:32:46Z
[ "python", "url" ]
Python Find Question
229,352
<p>I am using Python to extract the filename from a link using rfind like below:</p> <pre><code>url = "http://www.google.com/test.php" print url[url.rfind("/") +1 : ] </code></pre> <p>This works ok with links without a / at the end of them and returns "test.php". I have encountered links with / at the end like so "...
2
2008-10-23T11:15:42Z
229,417
<p>Just for fun, you can use a Regexp:</p> <pre><code>import re print re.search('/([^/]+)/?$', url).group(1) </code></pre>
0
2008-10-23T11:38:13Z
[ "python", "url" ]
Python Find Question
229,352
<p>I am using Python to extract the filename from a link using rfind like below:</p> <pre><code>url = "http://www.google.com/test.php" print url[url.rfind("/") +1 : ] </code></pre> <p>This works ok with links without a / at the end of them and returns "test.php". I have encountered links with / at the end like so "...
2
2008-10-23T11:15:42Z
229,430
<p>Use [r]strip to remove trailing slashes:</p> <pre><code>url.rstrip('/').rsplit('/', 1)[-1] </code></pre> <p>If a wider range of possible URLs is possible, including URLs with ?queries, #anchors or without a path, do it properly with urlparse:</p> <pre><code>path= urlparse.urlparse(url).path return path.rstrip('/'...
4
2008-10-23T11:42:52Z
[ "python", "url" ]
Python Find Question
229,352
<p>I am using Python to extract the filename from a link using rfind like below:</p> <pre><code>url = "http://www.google.com/test.php" print url[url.rfind("/") +1 : ] </code></pre> <p>This works ok with links without a / at the end of them and returns "test.php". I have encountered links with / at the end like so "...
2
2008-10-23T11:15:42Z
229,650
<pre><code>filter(None, url.split('/'))[-1] </code></pre> <p>(But urlparse is probably more readable, even if more verbose.)</p>
-1
2008-10-23T13:10:34Z
[ "python", "url" ]
Python - Library Problems
229,756
<p>I'm relatively new to Python and am having problems programming with Scapy, the Python network manipulation tool. However, I can't tell if it's as much a Scapy problem as it is a being-a-Python-newbie problem. On the <a href="http://www.secdev.org/projects/scapy/build_your_own_tools.html">scapy site</a>, they give a...
6
2008-10-23T13:41:31Z
229,819
<p>With the caveat from Federico Ramponi "You should use scapy as an interpreter by its own, not as a library", I want to answer the non-scapy-specific parts of the question.</p> <p><strong>Q:</strong> when installing Python libraries, do I need to change my path or anything similar?</p> <p><strong>A:</strong> I thin...
6
2008-10-23T13:59:23Z
[ "python", "networking", "scapy" ]
Python - Library Problems
229,756
<p>I'm relatively new to Python and am having problems programming with Scapy, the Python network manipulation tool. However, I can't tell if it's as much a Scapy problem as it is a being-a-Python-newbie problem. On the <a href="http://www.secdev.org/projects/scapy/build_your_own_tools.html">scapy site</a>, they give a...
6
2008-10-23T13:41:31Z
229,842
<p>It tells you that it can't find sr1 in scapy. Not sure just how newbite you are, but the interpreter is always your friend. Fire up the interpreter (just type "python" on the commandline), and at the prompt (>>>) type (but don't type the >'s, they'll show up by themselves):</p> <pre><code>&gt;&gt;&gt; import scapy ...
3
2008-10-23T14:05:46Z
[ "python", "networking", "scapy" ]
Python - Library Problems
229,756
<p>I'm relatively new to Python and am having problems programming with Scapy, the Python network manipulation tool. However, I can't tell if it's as much a Scapy problem as it is a being-a-Python-newbie problem. On the <a href="http://www.secdev.org/projects/scapy/build_your_own_tools.html">scapy site</a>, they give a...
6
2008-10-23T13:41:31Z
230,333
<p>The <a href="http://www.secdev.org/projects/scapy/index.html" rel="nofollow">scapy</a> package is a tool for network manipulation and monitoring. I'm curious as to what you're trying to do with it. It's rude to spy on your friends. :-)</p> <pre><code>coventry@metta:~/src$ wget -q http://www.secdev.org/projects/sc...
1
2008-10-23T16:04:30Z
[ "python", "networking", "scapy" ]
Python - Library Problems
229,756
<p>I'm relatively new to Python and am having problems programming with Scapy, the Python network manipulation tool. However, I can't tell if it's as much a Scapy problem as it is a being-a-Python-newbie problem. On the <a href="http://www.secdev.org/projects/scapy/build_your_own_tools.html">scapy site</a>, they give a...
6
2008-10-23T13:41:31Z
942,244
<p>I had the same problem, in the scapy v2.x use </p> <pre><code> from scapy.all import * </code></pre> <p>instead the v1.x</p> <pre><code> from scapy import * </code></pre> <p>as written <a href="http://www.secdev.org/projects/scapy/doc/installation.html" rel="nofollow">here</a></p> <p>Enjoy it =)</p>
4
2009-06-02T22:30:00Z
[ "python", "networking", "scapy" ]
Any good "contact us" recipes for Cherrypy?
230,310
<p>I'm looking to implement a "Contact Us" form with Cherrypy and was wondering: Is there a good recipe (or a BSD licensed set of code) that I could use instead of reinventing the wheel?</p> <p>Ideally, this would be Cherrpy 3.1 compatible.</p>
3
2008-10-23T15:59:07Z
232,565
<p>Well, I had to look into a solution. This works (ugly, and w/o Javascript validation) -- using the smtplib lib. Also, note that I stole Jeff's captcha for this example. Anyone using this will need to change it. </p> <p><strong>EDIT:</strong> I added validation.</p> <pre><code>#!/usr/local/bin/python2.4 import...
3
2008-10-24T05:31:27Z
[ "python", "cherrypy", "contactus" ]
Any good "contact us" recipes for Cherrypy?
230,310
<p>I'm looking to implement a "Contact Us" form with Cherrypy and was wondering: Is there a good recipe (or a BSD licensed set of code) that I could use instead of reinventing the wheel?</p> <p>Ideally, this would be Cherrpy 3.1 compatible.</p>
3
2008-10-23T15:59:07Z
13,885,542
<p>I realize the question is four years old, but for those still searching:</p> <p>I recommend using the python library <a href="https://github.com/marrow/marrow.mailer" rel="nofollow">Marrow Mailer</a>. It abstracts the whole smtp vs sendmail, etc., and also provides excellent server-side validation. The code is unde...
3
2012-12-14T20:07:20Z
[ "python", "cherrypy", "contactus" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
230,774
<pre><code>import sys sys.stdout.flush() </code></pre> <p>Print by default prints to <code>sys.stdout</code>.</p> <p>References:</p> <ul> <li><a href="http://docs.python.org/reference/simple_stmts.html#the-print-statement">http://docs.python.org/reference/simple_stmts.html#the-print-statement</a></li> <li><a href="h...
765
2008-10-23T18:04:59Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
230,780
<p>Running <code>python -h</code>, I see a <em>command line option</em>:</p> <blockquote> <p>-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'</p> </blockquote> <p>Here is the <a href="http://docs.python.org/using/cmdline...
229
2008-10-23T18:06:49Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
231,216
<p>Using the <code>-u</code> command-line switch works, but it is a little bit clumsy. It would mean that the program would potentially behave incorrectly if the user invoked the script without the <code>-u</code> option. I usually use a custom <code>stdout</code>, like this:</p> <pre><code>class flushfile(file): d...
26
2008-10-23T19:54:26Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
288,536
<p>Dan's idea doesn't quite work:</p> <pre><code>#!/usr/bin/env python class flushfile(file): def __init__(self, f): self.f = f def write(self, x): self.f.write(x) self.f.flush() import sys sys.stdout = flushfile(sys.stdout) print "foo" </code></pre> <p>The result:</p> <pre><code>Tr...
12
2008-11-13T22:15:25Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
741,601
<p>Why not try using an unbuffered file?</p> <pre><code>f = open('xyz.log', 'a', 0) </code></pre> <p>OR</p> <pre><code>sys.stdout = open('out.log', 'a', 0) </code></pre>
17
2009-04-12T10:57:58Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
5,020,567
<p>Loved Dan's solution! For python3 do:</p> <pre><code>import io,sys class flushfile: def __init__(self, f): self.f = f def write(self, x): self.f.write(x) self.f.flush() sys.stdout = flushfile(sys.stdout) </code></pre>
5
2011-02-16T18:29:28Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
6,055,744
<p>Here is my version, which provides writelines() and fileno(), too:</p> <pre><code>class FlushFile(object): def __init__(self, fd): self.fd = fd def write(self, x): ret = self.fd.write(x) self.fd.flush() return ret def writelines(self, lines): ret = self.writelin...
5
2011-05-19T08:20:36Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
8,471,288
<pre><code>import sys print 'This will be output immediately.' sys.stdout.flush() </code></pre>
11
2011-12-12T07:46:41Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
9,462,099
<p>Also as suggested in <a href="http://algorithmicallyrandom.blogspot.com/2009/10/python-tips-and-tricks-flushing-stdout.html">this blog</a> one can reopen <code>sys.stdout</code> in unbuffered mode:</p> <pre><code>sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) </code></pre> <p>Each <code>stdout.write</code> an...
55
2012-02-27T08:38:27Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
23,142,556
<p>Since Python 3.3, you can force the normal <code>print()</code> function to flush without the need to use <code>sys.stdout.flush()</code>; just set the "flush" keyword argument to true. From <a href="https://docs.python.org/3.3/library/functions.html#print">the documentation</a>:</p> <blockquote> <p><strong>prin...
143
2014-04-17T20:10:31Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
30,682,091
<p>I did it like this in Python 3.4:</p> <pre><code>'''To write to screen in real-time''' message = lambda x: print(x, flush=True, end="") message('I am flushing out now...') </code></pre>
3
2015-06-06T11:10:54Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
33,265,549
<pre><code>print("Foo", flush=True) </code></pre> <p>Like that</p>
8
2015-10-21T17:23:32Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
35,467,658
<blockquote> <h1>How to flush output of Python print?</h1> </blockquote> <h2>Python 3.3+</h2> <p>Using Python 3.3 or higher, you can just provide <code>flush=True</code> as a keyword argument to the <code>print</code> function: </p> <pre><code>print('foo', flush=True) </code></pre> <h2>Python 2 (or &lt; 3.3)</h2...
11
2016-02-17T21:01:03Z
[ "python", "printing", "flush" ]
How to flush output of Python print?
230,751
<p>How do I force Python's print function to output to the screen?</p>
605
2008-10-23T17:59:39Z
37,242,598
<p>In Python 3 you can overwrite print function with default set to <code>flush = True</code> </p> <pre class="lang-py prettyprint-override"><code>def print(*objects, sep=' ', end='\n', file=sys.stdout, flush=True): __builtins__.print(*objects, sep=sep, end=end, file=file, flush=flush) </code></pre>
1
2016-05-15T19:13:34Z
[ "python", "printing", "flush" ]
Make python enter password when running a csh script
230,845
<p>I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:</p> <pre><code>import com...
5
2008-10-23T18:22:33Z
230,855
<p>Should be able to pass it as a parameter. something like:</p> <pre><code>commands.getoutput('server stop -p password') </code></pre>
0
2008-10-23T18:24:49Z
[ "python", "scripting", "passwords", "root", "csh" ]
Make python enter password when running a csh script
230,845
<p>I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:</p> <pre><code>import com...
5
2008-10-23T18:22:33Z
230,862
<p>Use <a href="http://www.python.org/doc/2.5.2/lib/module-subprocess.html" rel="nofollow">subprocess</a>. Call Popen() to create your process and use communicate() to send it text. Sorry, forgot to include the PIPE..</p> <pre><code>from subprocess import Popen, PIPE proc = Popen(['server', 'stop'], stdin=PIPE) pr...
3
2008-10-23T18:25:33Z
[ "python", "scripting", "passwords", "root", "csh" ]
Make python enter password when running a csh script
230,845
<p>I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:</p> <pre><code>import com...
5
2008-10-23T18:22:33Z
230,982
<p>This seems to work better:</p> <pre><code>import popen2 (stdout, stdin) = popen2.popen2('server stop') stdin.write("password") </code></pre> <p>But it's not 100% yet. Even though "password" is the correct password I'm still getting su: Sorry back from the csh script when it's trying to su to root.</p>
0
2008-10-23T18:57:21Z
[ "python", "scripting", "passwords", "root", "csh" ]
Make python enter password when running a csh script
230,845
<p>I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:</p> <pre><code>import com...
5
2008-10-23T18:22:33Z
230,986
<p>Have a look at the <a href="http://www.noah.org/wiki/Pexpect">pexpect</a> module. It is designed to deal with interactive programs, which seems to be your case.</p> <p>Oh, and remember that hard-encoding root's password in a shell or python script is potentially a security hole :D</p>
7
2008-10-23T18:58:34Z
[ "python", "scripting", "passwords", "root", "csh" ]
Make python enter password when running a csh script
230,845
<p>I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:</p> <pre><code>import com...
5
2008-10-23T18:22:33Z
234,301
<p>To avoid having to answer the Password question in the python script I'm just going to run the script as root. This question is still unanswered but I guess I'll just do it this way for now.</p>
0
2008-10-24T16:39:21Z
[ "python", "scripting", "passwords", "root", "csh" ]
Make python enter password when running a csh script
230,845
<p>I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:</p> <pre><code>import com...
5
2008-10-23T18:22:33Z
321,950
<pre><code>import pexpect child = pexpect.spawn('server stop') child.expect_exact('Password:') child.sendline('password') print "Stopping the servers..." index = child.expect_exact(['Server processes successfully stopped.', 'Server is not running...'], 60) child.expect(pexpect.EOF) </code></pre> <p>Did the trick! P...
1
2008-11-26T19:58:36Z
[ "python", "scripting", "passwords", "root", "csh" ]
Make python enter password when running a csh script
230,845
<p>I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script:</p> <pre><code>import com...
5
2008-10-23T18:22:33Z
809,168
<p>Add <code>input=</code> in <code>proc.communicate()</code> make it run, for guys who like to use standard lib.</p> <pre><code>from subprocess import Popen, PIPE proc = Popen(['server', 'stop'], stdin=PIPE) proc.communicate(input='password') </code></pre>
0
2009-04-30T21:24:48Z
[ "python", "scripting", "passwords", "root", "csh" ]
Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?
230,896
<p>I have a list of variable names, like this:</p> <pre><code>['foo', 'bar', 'baz'] </code></pre> <p>(I originally asked how I convert a list of variables. See Greg Hewgill's answer below.)</p> <p>How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values ...
13
2008-10-23T18:33:51Z
230,907
<p>Your original list <code>[foo, bar, baz]</code> doesn't contain the variable <em>names</em>, it just contains elements that refer to the same <em>values</em> as the variables you listed. This is because you can have two different variable names that refer to the same value.</p> <p>So, the list by itself doesn't con...
4
2008-10-23T18:35:35Z
[ "python", "list", "dictionary" ]
Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?
230,896
<p>I have a list of variable names, like this:</p> <pre><code>['foo', 'bar', 'baz'] </code></pre> <p>(I originally asked how I convert a list of variables. See Greg Hewgill's answer below.)</p> <p>How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values ...
13
2008-10-23T18:33:51Z
230,955
<p>You can use list or generator comprehensions to build a list of key, value tuples used to directly instantiate a dict. The best way is below:</p> <pre><code>dict((name, eval(name)) for name in list_of_variable_names) </code></pre> <p>In addition, if you know, for example, that the variables exist in the local sym...
3
2008-10-23T18:49:48Z
[ "python", "list", "dictionary" ]
Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?
230,896
<p>I have a list of variable names, like this:</p> <pre><code>['foo', 'bar', 'baz'] </code></pre> <p>(I originally asked how I convert a list of variables. See Greg Hewgill's answer below.)</p> <p>How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values ...
13
2008-10-23T18:33:51Z
230,976
<p>Not efficient, but without invoking <code>eval</code>:</p> <pre><code>dict((k,v) for (k,v) in globals().iteritems() if k in list_of_variable_names) </code></pre> <p>or</p> <pre><code>dict((k,v) for (k,v) in vars().iteritems() if k in list_of_variable_names) </code></pre> <p>depending on what you want.</p>
1
2008-10-23T18:54:33Z
[ "python", "list", "dictionary" ]
Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?
230,896
<p>I have a list of variable names, like this:</p> <pre><code>['foo', 'bar', 'baz'] </code></pre> <p>(I originally asked how I convert a list of variables. See Greg Hewgill's answer below.)</p> <p>How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values ...
13
2008-10-23T18:33:51Z
231,368
<p>Forget filtering <code>locals()</code>! The dictionary you give to the formatting string is allowed to contain unused keys:</p> <pre><code>&gt;&gt;&gt; name = 'foo' &gt;&gt;&gt; zip = 123 &gt;&gt;&gt; unused = 'whoops!' &gt;&gt;&gt; locals() {'name': 'foo', 'zip': 123, ... 'unused': 'whoops!', ...} &gt;&gt;&gt; '%(...
14
2008-10-23T20:29:33Z
[ "python", "list", "dictionary" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
231,778
<p><code>yield</code> is just like <code>return</code> - it returns whatever you tell it to. The only difference is that the next time you call the function, execution starts from the last call to the <code>yield</code> statement.</p> <p>In the case of your code, the function <code>get_child_candidates</code> is acti...
141
2008-10-23T22:24:03Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
231,788
<p>It's returning a generator. I'm not particularly familiar with Python, but I believe it's the same kind of thing as <a href="http://csharpindepth.com/Articles/Chapter11/StreamingAndIterators.aspx">C#'s iterator blocks</a> if you're familiar with those.</p> <p>There's an <a href="http://www.ibm.com/developerworks/li...
78
2008-10-23T22:26:06Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
231,801
<p>Think of it this way:</p> <p>An iterator is just a fancy sounding term for an object that has a next() method. So a yield-ed function ends up being something like this:</p> <p>Original version:</p> <pre><code>def some_function(): for i in xrange(4): yield i for i in some_function(): print i </co...
236
2008-10-23T22:28:41Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
231,855
<p>To understand what <code>yield</code> does, you must understand what <em>generators</em> are. And before generators come <em>iterables</em>.</p> <h2>Iterables</h2> <p>When you create a list, you can read its items one by one. Reading its items one by one is called iteration:</p> <pre><code>&gt;&gt;&gt; mylist = [...
8,384
2008-10-23T22:48:44Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
232,111
<p>An example in plain language. I will provide a correspondence between high-level human concepts to low-level python concepts.</p> <p>I want to operate on a sequence of numbers, but I don't want to bother my self with the creation of that sequence, I want only to focus on the operation I want to do. So, I do the fol...
72
2008-10-24T00:36:05Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
232,791
<p>I feel like I post a link to this presentation every day: David M. Beazly's <a href="http://www.dabeaz.com/generators/">Generator Tricks for Systems Programmers</a>. If you're a Python programmer and you're not extremely familiar with generators, you should read this. It's a very clear explanation of what generat...
160
2008-10-24T07:59:15Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
232,853
<p>There's one extra thing to mention: a function that yields doesn't actually have to terminate. I've written code like this:</p> <pre><code>def fib(): last, cur = 0, 1 while True: yield cur last, cur = cur, last + cur </code></pre> <p>Then I can use it in other code like this:</p> <pre><co...
121
2008-10-24T08:44:08Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
237,028
<h2>Shortcut to <a href="http://en.wikipedia.org/wiki/Grok">Grokking</a> <code>yield</code></h2> <p>When you see a function with <code>yield</code> statements, apply this easy trick to understand what will happen:</p> <ol> <li>Insert a line <code>result = []</code> at the start of the function.</li> <li>Replace each ...
1,095
2008-10-25T21:22:30Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
6,400,990
<p>The <code>yield</code> keyword is reduced to two simple facts:</p> <ol> <li>If the compiler detects the <code>yield</code> keyword <em>anywhere</em> inside a function, that function no longer returns via the <code>return</code> statement. <strong><em>Instead</em></strong>, it <strong>immediately</strong> returns a ...
215
2011-06-19T06:33:58Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
12,716,515
<p>Here are some <a href="https://github.com/dustingetz/sandbox/blob/master/etc/lazy.py">Python examples of how to actually implement generators</a> as if Python did not provide syntactic sugar for them (or in a language without native syntax, like <a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a>). Snip...
49
2012-10-03T20:38:16Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
14,352,675
<p>Yield gives you a generator. </p> <pre><code>def get_odd_numbers(i): return range(1, i, 2) def yield_odd_numbers(i): for x in range(1, i, 2): yield x foo = get_odd_numbers(10) bar = yield_odd_numbers(10) foo [1, 3, 5, 7, 9] bar &lt;generator object yield_odd_numbers at 0x1029c6f50&gt; bar.next() 1 ba...
88
2013-01-16T06:42:09Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
14,404,292
<p>For those who prefer a minimal working example, meditate on this interactive <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a> session:</p> <pre><code>&gt;&gt;&gt; def f(): ... yield 1 ... yield 2 ... yield 3 ... &gt;&gt;&gt; g = f() &gt;&gt;&gt; for i in g: ... print i .....
95
2013-01-18T17:25:17Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
14,554,322
<p>I was going to post "read page 19 of Beazley's 'Python: Essential Reference' for a quick description of generators", but so many others have posted good descriptions already.</p> <p>Also, note that <code>yield</code> can be used in coroutines as the dual of their use in generator functions. Although it isn't the s...
51
2013-01-28T01:37:10Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
15,814,755
<p>There is one type of answer that I don't feel has been given yet, among the many great answers that describe how to use generators. Here is the PL theory answer:</p> <p>The <code>yield</code> statement in python returns a generator. A generator in python is a function that returns <i>continuations</i> (and specif...
81
2013-04-04T14:56:19Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
17,113,322
<p>Here is a mental image of what <code>yield</code> does.</p> <p>I like to think of a thread as having a stack (even if it's not implemented that way).</p> <p>When a normal function is called, it puts its local variables on the stack, does some computation, returns and clears the stack. The values of its local varia...
34
2013-06-14T16:36:59Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
18,365,578
<p>From a programming viewpoint, the iterators are implemented as <strong>thunks</strong> </p> <p><a href="http://en.wikipedia.org/wiki/Thunk_(functional_programming)">http://en.wikipedia.org/wiki/Thunk_(functional_programming)</a></p> <p>To implement iterators/generators/etc as thunks (also called anonymous function...
33
2013-08-21T19:01:25Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
20,704,301
<p>Here is a simple example:</p> <pre><code>def isPrimeNumber(n): print "isPrimeNumber({}) call".format(n) if n==1: return False for x in range(2,n): if n % x == 0: return False return True def primes (n=1): while(True): print "loop step ---------------- {}".f...
41
2013-12-20T13:07:18Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
21,541,902
<p>While a lot of answers show why you'd use a <code>yield</code> to create a generator, there are more uses for <code>yield</code>. It's quite easy to make a coroutine, which enables the passing of information between two blocks of code. I won't repeat any of the fine examples that have already been given about usin...
64
2014-02-04T02:27:35Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
24,944,096
<p>There is another <code>yield</code> use and meaning (since python 3.3):</p> <pre><code>yield from &lt;expr&gt; </code></pre> <p><a href="http://www.python.org/dev/peps/pep-0380/">http://www.python.org/dev/peps/pep-0380/</a></p> <blockquote> <p>A syntax is proposed for a generator to delegate part of its operati...
49
2014-07-24T21:15:29Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
30,341,713
<p><code>yield</code> is like a return element for a function. The difference is, that the <code>yield</code> element turns a function into a generator. A generator behaves just like a function until something is 'yielded'. The generator stops until it is next called, and continues from exactly the same point as it sta...
24
2015-05-20T06:19:32Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
31,042,491
<blockquote> <p><strong>What does the <code>yield</code> keyword do in Python?</strong></p> </blockquote> <h1>Answer Outline/Summary</h1> <ul> <li>A function with <a href="https://docs.python.org/reference/expressions.html#yieldexpr"><strong><code>yield</code></strong></a>, when called, <strong>returns a <a href="h...
113
2015-06-25T06:11:11Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
31,692,481
<p>Like every answer suggests, <code>yield</code> is used for creating a sequence generator. It's used for generating some sequence dynamically. Eg. While reading a file line by line on a network, you can use the <code>yield</code> function as follows:</p> <pre><code>def getNextLines(): while con.isOpen(): y...
24
2015-07-29T06:11:25Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
32,331,953
<p><strong>Yield is an Object</strong></p> <p>A <code>return</code> in a function will return a single value.</p> <p>If you want <strong>function to return huge set of values</strong> use <code>yield</code>.</p> <p>More importantly, <code>yield</code> is a <strong>barrier</strong> </p> <blockquote> <p>like Barrie...
18
2015-09-01T12:42:19Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
33,788,856
<p>The <code>yield</code> keyword simply collects returning results. Think of <code>yield</code> like <code>return +=</code></p>
17
2015-11-18T19:37:29Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
35,526,740
<h3>Official Reference on <code>yield</code> : <strong><a href="https://www.python.org/dev/peps/pep-0255/">PEP 255 -- Simple Generators</a></strong>:</h3> <p>Most questions regarding the <code>yield</code> statement and the semantics/functionality that it introduces are present in <em>PEP 255</em>. The collective know...
12
2016-02-20T17:41:32Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
36,168,155
<p>At a glance, the yield statement is used to define generators, replacing the return of a function to provide a result to its caller without destroying local variables. Unlike a function, where on each call it starts with new set of variables, a generator will resume the execution where it was left off.</p> <p>About...
10
2016-03-23T01:18:17Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
36,214,653
<p>(My below answer only speaks from the perspective of using Python generator, not the <a href="http://stackoverflow.com/questions/8389812/how-are-generators-and-coroutines-implemented-in-cpython">underlying implementation of generator mechanism</a>, which involves some tricks of stack and heap manipulation.)</p> <p>...
14
2016-03-25T05:40:24Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
36,220,775
<p><strong>TL;DR</strong></p> <h1>When you find yourself building a list from scratch...</h1> <pre><code>def squares_list(n): the_list = [] for x in range(n): y = x * x the_list.append(y) return the_list </code></pre> <h1>...you may want to yield the pieces instead.</h1> <pre><code>def s...
27
2016-03-25T13:21:44Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
37,964,180
<p>Yet another TL;DR</p> <p><strong>iterator on list</strong>: <code>next()</code> returns the next element of the list</p> <p><strong>iterator generator</strong>: <code>next()</code> will compute the next element on the fly</p> <p>You can see the yield/generator as a way to manually run the <strong>control flow</st...
8
2016-06-22T09:40:15Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
39,425,637
<p>Many people use <code>return</code> rather than <code>yield</code> but in some cases <code>yield</code> can be more efficient and easier to work with.</p> <p>Here is an example which <code>yield</code> is definitely best for:</p> <pre><code>import random def return_dates(): dates = [] # with return you need t...
4
2016-09-10T11:37:25Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
What does the "yield" keyword do?
231,767
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist &lt; self._median: ...
5,524
2008-10-23T22:21:11Z
40,022,748
<p>In summary, the <code>yield</code> statement transforms your function into a factory that produces a special object called a <code>generator</code> which wraps around the body of your original function. When the <code>generator</code> is iterated, it executes your function until it reaches the next <code>yield</cod...
1
2016-10-13T13:43:40Z
[ "python", "iterator", "generator", "yield", "coroutine" ]
Python inheritance - how to disable a function
231,839
<p>In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface?</p>
21
2008-10-23T22:40:55Z
231,857
<pre><code>class X(object): def some_function(self): do_some_stuff() class Y(object): some_function = None </code></pre> <p>This may lead to some nasty and hard to find exceptions being thrown though, so you might try this:</p> <pre><code>class X(object): def some_function(self): do_some_...
4
2008-10-23T22:49:22Z
[ "python", "inheritance", "interface", "private" ]
Python inheritance - how to disable a function
231,839
<p>In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface?</p>
21
2008-10-23T22:40:55Z
231,871
<p>There really aren't any true "private" attributes or methods in Python. One thing you can do is simply override the method you don't want in the subclass, and raise an exception:</p> <pre><code>&gt;&gt;&gt; class Foo( object ): ... def foo( self ): ... print 'FOO!' ... &gt;&gt;&gt; class Bar( Foo ):...
16
2008-10-23T22:52:51Z
[ "python", "inheritance", "interface", "private" ]
Python inheritance - how to disable a function
231,839
<p>In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface?</p>
21
2008-10-23T22:40:55Z
235,657
<p>kurosch's method of solving the problem isn't quite correct, because you can still use <code>b.foo</code> without getting an <code>AttributeError</code>. If you don't invoke the function, no error occurs. Here are two ways that I can think to do this:</p> <pre><code>import doctest class Foo(object): """ &g...
15
2008-10-25T00:05:19Z
[ "python", "inheritance", "interface", "private" ]
Python inheritance - how to disable a function
231,839
<p>In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface?</p>
21
2008-10-23T22:40:55Z
23,126,120
<p>This is the cleanest way I know to do it.</p> <p>Override the methods and have each of the overridden methods call your disabledmethods() method. Like this:</p> <pre><code>class Deck(list): ... @staticmethod def disabledmethods(): raise Exception('Function Disabled') def pop(self): Deck.disabledmet...
0
2014-04-17T06:32:24Z
[ "python", "inheritance", "interface", "private" ]
Python inheritance - how to disable a function
231,839
<p>In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface?</p>
21
2008-10-23T22:40:55Z
23,126,260
<p>A variation on the answer of kurosch:</p> <pre><code>class Foo( object ): def foo( self ): print 'FOO!' class Bar( Foo ): @property def foo( self ): raise AttributeError( "'Bar' object has no attribute 'foo'" ) b = Bar() b.foo </code></pre> <p>This raises an <code>AttributeError</code...
6
2014-04-17T06:41:17Z
[ "python", "inheritance", "interface", "private" ]
What's the best python soap stack for consuming Amazon Web Services WSDL?
231,924
<p>Python has a <a href="http://stackoverflow.com/questions/206154/whats-the-best-soap-client-library-for-python-and-where-is-the-documentation-fo">number of soap stacks</a>; as near as I can tell, all have substantial defects.</p> <p>Has anyone had luck consuming <i>and</i> using WSDL for S3, EC2, and SQS in python?<...
14
2008-10-23T23:20:38Z
236,691
<p>if i'm not mistaken, you can consume Amazon Web Services via REST as well as SOAP. using REST with python would be <em>much</em> easier. </p>
1
2008-10-25T17:00:01Z
[ "python", "soap", "wsdl", "amazon-web-services", "amazon" ]
What's the best python soap stack for consuming Amazon Web Services WSDL?
231,924
<p>Python has a <a href="http://stackoverflow.com/questions/206154/whats-the-best-soap-client-library-for-python-and-where-is-the-documentation-fo">number of soap stacks</a>; as near as I can tell, all have substantial defects.</p> <p>Has anyone had luck consuming <i>and</i> using WSDL for S3, EC2, and SQS in python?<...
14
2008-10-23T23:20:38Z
237,010
<p>The REST or "Query" APIs are definitely easier to use than SOAP, but unfortunately at least once service (EC2) doesn't provide any alternatives to SOAP. As you've already discovered, Python's existing SOAP implementations are woefully inadequate for most purposes; one workaround approach is to just generate the XML ...
3
2008-10-25T21:08:14Z
[ "python", "soap", "wsdl", "amazon-web-services", "amazon" ]
What's the best python soap stack for consuming Amazon Web Services WSDL?
231,924
<p>Python has a <a href="http://stackoverflow.com/questions/206154/whats-the-best-soap-client-library-for-python-and-where-is-the-documentation-fo">number of soap stacks</a>; as near as I can tell, all have substantial defects.</p> <p>Has anyone had luck consuming <i>and</i> using WSDL for S3, EC2, and SQS in python?<...
14
2008-10-23T23:20:38Z
547,226
<p>Check out <a href="http://boto.googlecode.com" rel="nofollow">http://boto.googlecode.com</a>. This is the best way to use AWS in Python.</p>
0
2009-02-13T19:03:47Z
[ "python", "soap", "wsdl", "amazon-web-services", "amazon" ]
What's the best python soap stack for consuming Amazon Web Services WSDL?
231,924
<p>Python has a <a href="http://stackoverflow.com/questions/206154/whats-the-best-soap-client-library-for-python-and-where-is-the-documentation-fo">number of soap stacks</a>; as near as I can tell, all have substantial defects.</p> <p>Has anyone had luck consuming <i>and</i> using WSDL for S3, EC2, and SQS in python?<...
14
2008-10-23T23:20:38Z
1,752,189
<p>FWIW, I get this Amazon WSDL to parse with Suds 0.3.8:</p> <p>url = '<a href="http://s3.amazonaws.com/ec2-downloads/2009-04-04.ec2.wsdl" rel="nofollow">http://s3.amazonaws.com/ec2-downloads/2009-04-04.ec2.wsdl</a>' <br> c = Client(url) <br> print c <br></p> <p>-- snip -- <br> Ports (1):<br> (AmazonEC2Port...
0
2009-11-17T22:06:32Z
[ "python", "soap", "wsdl", "amazon-web-services", "amazon" ]
Will Django be a good choice for a permissions based web-app?
232,008
<p>I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface.</p> <p>What I'm writing is an Intranet client management web-app. The organisation is about 6 tiers, and I need to re...
12
2008-10-23T23:50:15Z
232,051
<p><a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/options.py#L154" rel="nofollow">ModelAdmin</a> objects have <code>has_add_permission</code>, <code>has_change_permission</code>, <code>has_delete_permission</code> and <code>queryset</code> methods which can be used to enforce permissio...
3
2008-10-24T00:06:33Z
[ "python", "django", "permissions" ]
Will Django be a good choice for a permissions based web-app?
232,008
<p>I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface.</p> <p>What I'm writing is an Intranet client management web-app. The organisation is about 6 tiers, and I need to re...
12
2008-10-23T23:50:15Z
232,243
<p>The Django permission system totally rules. Each model has a default set of permissions. You can add new permissions to your models, also.</p> <p>Each User has a set of permissions as well as group memberships. Individual users can have individual permissions. And they inherit permissions from their group member...
5
2008-10-24T01:58:34Z
[ "python", "django", "permissions" ]
Will Django be a good choice for a permissions based web-app?
232,008
<p>I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface.</p> <p>What I'm writing is an Intranet client management web-app. The organisation is about 6 tiers, and I need to re...
12
2008-10-23T23:50:15Z
237,214
<p>If I read your updated requirements correctly, I don't think Django's existing auth system will be sufficient. It sounds like you need a full-on ACL system.</p> <p>This subject has come up a number of times. Try googling on django+acl.</p> <p>Random samplings ...</p> <p>There was a Summer of Code project a couple...
7
2008-10-25T23:49:42Z
[ "python", "django", "permissions" ]
Will Django be a good choice for a permissions based web-app?
232,008
<p>I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface.</p> <p>What I'm writing is an Intranet client management web-app. The organisation is about 6 tiers, and I need to re...
12
2008-10-23T23:50:15Z
323,439
<p>You may also want to have a look at the granular-permissions monkeypatch: <a href="http://code.google.com/p/django-granular-permissions/" rel="nofollow">http://code.google.com/p/django-granular-permissions/</a></p> <p>It adds row-level permissions to django's permission system.</p>
0
2008-11-27T10:40:14Z
[ "python", "django", "permissions" ]
Will Django be a good choice for a permissions based web-app?
232,008
<p>I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface.</p> <p>What I'm writing is an Intranet client management web-app. The organisation is about 6 tiers, and I need to re...
12
2008-10-23T23:50:15Z
1,338,370
<p>I've just found <a href="http://bitbucket.org/jezdez/django-authority/" rel="nofollow">http://bitbucket.org/jezdez/django-authority/</a> , it looks promising.</p>
0
2009-08-27T01:08:13Z
[ "python", "django", "permissions" ]
Will Django be a good choice for a permissions based web-app?
232,008
<p>I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface.</p> <p>What I'm writing is an Intranet client management web-app. The organisation is about 6 tiers, and I need to re...
12
2008-10-23T23:50:15Z
7,008,048
<p>From django 1.2 there is support for row-level permissions, which <a href="http://packages.python.org/django-guardian/" rel="nofollow">django-guardian</a> makes very intuitive to handle.</p>
2
2011-08-10T08:44:23Z
[ "python", "django", "permissions" ]
How to do Makefile dependencies for python code
232,162
<p>I have a bunch of C files that are generated by a collection of python programs that have a number of shared python modules and I need to account for this in my make system.</p> <p>It is easy enough to enumerate which python program need to be run to generate each C file. What I can't find a good solution for is de...
7
2008-10-24T01:09:24Z
232,233
<p>The <code>import</code> statements are pretty much all the dependencies there are. There are are two relevant forms for the import statements:</p> <pre><code>import x, y, z from x import a, b, c </code></pre> <p>You'll also need the <code>PYTHONPATH</code> and <code>sites</code> information that is used to build ...
1
2008-10-24T01:50:50Z
[ "python", "makefile", "dependencies" ]
How to do Makefile dependencies for python code
232,162
<p>I have a bunch of C files that are generated by a collection of python programs that have a number of shared python modules and I need to account for this in my make system.</p> <p>It is easy enough to enumerate which python program need to be run to generate each C file. What I can't find a good solution for is de...
7
2008-10-24T01:09:24Z
232,385
<p><a href="http://docs.python.org/library/modulefinder.html" rel="nofollow">modulefinder</a> can be used to <a href="http://www.tarind.com/depgraph.html" rel="nofollow">get the dependency graph</a>.</p>
3
2008-10-24T03:24:37Z
[ "python", "makefile", "dependencies" ]
How do I restrict foreign keys choices to related objects only in django
232,435
<p>I have a two way foreign relation similar to the following</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Par...
33
2008-10-24T03:52:50Z
232,644
<p>This isn't how django works. You would only create the relation going one way.</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Parent) </code></pre> <p>And if you were trying to...
12
2008-10-24T06:28:47Z
[ "python", "django", "django-models" ]
How do I restrict foreign keys choices to related objects only in django
232,435
<p>I have a two way foreign relation similar to the following</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Par...
33
2008-10-24T03:52:50Z
232,969
<p>Do you want to restrict the choices available in the admin interface when creating/editing a model instance?</p> <p>One way to do this is validation of the model. This lets you raise an error in the admin interface if the foreign field is not the right choice.</p> <p>Of course, Eric's answer is correct: You only r...
3
2008-10-24T10:01:15Z
[ "python", "django", "django-models" ]
How do I restrict foreign keys choices to related objects only in django
232,435
<p>I have a two way foreign relation similar to the following</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Par...
33
2008-10-24T03:52:50Z
234,325
<p>@Ber: I have added validation to the model similar to this</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) def save(self, force_insert=False, force_update=False): if self.favoritechild is not None and self...
3
2008-10-24T16:44:40Z
[ "python", "django", "django-models" ]
How do I restrict foreign keys choices to related objects only in django
232,435
<p>I have a two way foreign relation similar to the following</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Par...
33
2008-10-24T03:52:50Z
252,087
<p>I just came across <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to">ForeignKey.limit_choices_to</a> in the Django docs. Not sure yet how this works, but it might just be the right think here.</p> <p><strong>Update:</strong> ForeignKey.limit_choices_to al...
20
2008-10-30T23:07:01Z
[ "python", "django", "django-models" ]
How do I restrict foreign keys choices to related objects only in django
232,435
<p>I have a two way foreign relation similar to the following</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Par...
33
2008-10-24T03:52:50Z
1,749,330
<p>I'm trying to do something similar. It seems like everyone saying 'you should only have a foreign key one way' has maybe misunderstood what you're trying do.</p> <p>It's a shame the limit_choices_to={"myparent": "self"} you wanted to do doesn't work... that would have been clean and simple. Unfortunately the 'self...
0
2009-11-17T14:40:04Z
[ "python", "django", "django-models" ]
How do I restrict foreign keys choices to related objects only in django
232,435
<p>I have a two way foreign relation similar to the following</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Par...
33
2008-10-24T03:52:50Z
3,753,916
<p>An alternative approach would be not to have 'favouritechild' fk as a field on the Parent model.</p> <p>Instead you could have an is_favourite boolean field on the Child.</p> <p>This may help: <a href="https://github.com/anentropic/django-exclusivebooleanfield" rel="nofollow">https://github.com/anentropic/django-e...
1
2010-09-20T17:36:57Z
[ "python", "django", "django-models" ]
How do I restrict foreign keys choices to related objects only in django
232,435
<p>I have a two way foreign relation similar to the following</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Par...
33
2008-10-24T03:52:50Z
4,653,418
<p>The new "right" way of doing this, at least since Django 1.1 is by overriding the AdminModel.formfield_for_foreignkey(self, db_field, request, **kwargs). </p> <p>See <a href="http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey">http://docs.djangoproject....
8
2011-01-11T01:44:54Z
[ "python", "django", "django-models" ]
How do I restrict foreign keys choices to related objects only in django
232,435
<p>I have a two way foreign relation similar to the following</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Par...
33
2008-10-24T03:52:50Z
19,556,353
<p>The 'right' way to do it is to use a custom form. From there, you can access self.instance, which is the current object. Example --</p> <pre><code>from django import forms from django.contrib import admin from models import * class SupplierAdminForm(forms.ModelForm): class Meta: model = Supplier ...
16
2013-10-24T03:25:58Z
[ "python", "django", "django-models" ]
How do I restrict foreign keys choices to related objects only in django
232,435
<p>I have a two way foreign relation similar to the following</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Par...
33
2008-10-24T03:52:50Z
29,455,444
<p>If you only need the limitations in the Django admin interface, this might work. I based it on <a href="http://w3facility.org/question/django-limit-manytomany-queryset-based-on-selected-fk/#answer-13147522" rel="nofollow">this answer</a> from another forum - although it's for ManyToMany relationships, you should be ...
2
2015-04-05T08:24:42Z
[ "python", "django", "django-models" ]
How do I restrict foreign keys choices to related objects only in django
232,435
<p>I have a two way foreign relation similar to the following</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Par...
33
2008-10-24T03:52:50Z
35,395,212
<pre><code>from django.contrib import admin from sopin.menus.models import Restaurant, DishType class ObjInline(admin.TabularInline): def __init__(self, parent_model, admin_site, obj=None): self.obj = obj super(ObjInline, self).__init__(parent_model, admin_site) class ObjAdmin(admin.ModelAdmin): ...
-1
2016-02-14T18:04:35Z
[ "python", "django", "django-models" ]