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
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
16,028,076
<p>The <a href="http://en.wikipedia.org/wiki/YAML" rel="nofollow">YAML</a> parser can help you figure out what datatype your string is. Use <code>yaml.load()</code>, and then you can use <code>type(result)</code> to test for type:</p> <pre><code>&gt;&gt;&gt; import yaml &gt;&gt;&gt; a = "545.2222" &gt;&gt;&gt; result = yaml.load(a) &gt;&gt;&gt; result 545.22220000000004 &gt;&gt;&gt; type(result) &lt;type 'float'&gt; &gt;&gt;&gt; b = "31" &gt;&gt;&gt; result = yaml.load(b) &gt;&gt;&gt; result 31 &gt;&gt;&gt; type(result) &lt;type 'int'&gt; &gt;&gt;&gt; c = "HI" &gt;&gt;&gt; result = yaml.load(c) &gt;&gt;&gt; result 'HI' &gt;&gt;&gt; type(result) &lt;type 'str'&gt; </code></pre>
7
2013-04-16T03:03:11Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
17,815,252
<h2>Localization and commas</h2> <p>You should consider the possibility of commas in the string representation of a number, for cases like <code>float("545,545.2222")</code> which throws an exception. Instead, use methods in <code>locale</code> to convert the strings to numbers and interpret commas correctly. The <code>locale.atof</code> method converts to a float in one step once the locale has been set for the desired number convention.</p> <p><strong>Example 1 -- United States number conventions</strong> </p> <p>In the United States and the UK, commas can be used as a thousands separator. In this example with American locale, the comma is handled properly as a separator:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; a = u'545,545.2222' &gt;&gt;&gt; locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') 'en_US.UTF-8' &gt;&gt;&gt; locale.atof(a) 545545.2222 &gt;&gt;&gt; int(locale.atof(a)) 545545 &gt;&gt;&gt; </code></pre> <p><strong>Example 2 -- European number conventions</strong></p> <p>In the <a href="https://en.wikipedia.org/wiki/Decimal_mark">majority of countries of the world</a>, commas are used for decimal marks instead of periods. In this example with French locale, the comma is correctly handled as a decimal mark:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; b = u'545,2222' &gt;&gt;&gt; locale.setlocale(locale.LC_ALL, 'fr_FR') 'fr_FR' &gt;&gt;&gt; locale.atof(b) 545.2222 </code></pre> <p>The method <code>locale.atoi</code> is also available, but the argument should be an integer.</p>
26
2013-07-23T16:00:21Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
20,929,983
<h2>Python method to check if a string is a float:</h2> <pre><code>def isfloat(value): try: float(value) return True except: return False </code></pre> <h2>What is, and is not a float in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a> may surprise you:</h2> <pre><code>Command to parse isFloat? Note ------------------------------------ -------- -------------------------------- print(isfloat("")) False Blank string print(isfloat("127")) True Passed string print(isfloat(True)) True Pure sweet Truth print(isfloat("True")) False Vile contemptible lie print(isfloat(False)) True So false it becomes true print(isfloat("123.456")) True Decimal print(isfloat(" -127 ")) True Spaces trimmed print(isfloat("\t\n12\r\n")) True whitespace ignored print(isfloat("NaN")) True Not a number print(isfloat("NaNanananaBATMAN")) False I am Batman print(isfloat("-iNF")) True Negative infinity print(isfloat("123.E4")) True Exponential notation print(isfloat(".1")) True mantissa only print(isfloat("1,234")) False Commas gtfo print(isfloat(u'\x30')) True Unicode is fine. print(isfloat("NULL")) False Null is not special print(isfloat(0x3fade)) True Hexidecimal print(isfloat("6e7777777777777")) True Shrunk to infinity print(isfloat("1.797693e+308")) True This is max value print(isfloat("infinity")) True Same as inf print(isfloat("infinityandBEYOND")) False Extra characters wreck it print(isfloat("12.34.56")) False Only one dot allowed print(isfloat(u'四')) False Japanese '4' is not a float. print(isfloat("#56")) False Pound sign print(isfloat("56%")) False Percent of what? print(isfloat("0E0")) True Exponential, move dot 0 places print(isfloat(0**0)) True 0___0 Exponentiation print(isfloat("-5e-5")) True Raise to a negative number print(isfloat("+1e1")) True Plus is OK with exponent print(isfloat("+1e1^5")) False Fancy exponent not interpreted print(isfloat("+1e1.3")) False No decimals in exponent print(isfloat("-+1")) False Make up your mind print(isfloat("(1)")) False Parenthesis is bad </code></pre> <p>You think you know what numbers are? You are not so good as you think! Not big surprise.</p>
246
2014-01-05T04:15:39Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
25,299,501
<p>If you aren't averse to third-party modules, you could check out the <a href="https://pypi.python.org/pypi/fastnumbers">fastnumbers</a> module. It provides a function called <a href="http://pythonhosted.org//fastnumbers/fast.html#fast-real">fast_real</a> that does exactly what this question is asking for and does it faster than a pure-Python implementation:</p> <pre><code>&gt;&gt;&gt; from fastnumbers import fast_real &gt;&gt;&gt; fast_real("545.2222") 545.2222 &gt;&gt;&gt; type(fast_real("545.2222")) float &gt;&gt;&gt; fast_real("31") 31 &gt;&gt;&gt; type(fast_real("31")) int </code></pre>
8
2014-08-14T03:21:37Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
31,588,754
<blockquote> <p><strong>In Python, how can I parse a numeric string like "545.2222" to its corresponding float value, 542.2222? Or parse the string "31" to an integer, 31?</strong> I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p> </blockquote> <p>It's good that you ask to do these separately. If you're mixing them, you may be setting yourself up for problems later. The simple answer is:</p> <p><strong><code>"545.2222"</code> to float:</strong></p> <pre><code>&gt;&gt;&gt; float("545.2222") 545.2222 </code></pre> <p><strong><code>"31"</code> to an integer:</strong></p> <pre><code>&gt;&gt;&gt; int("31") 31 </code></pre> <h1>Other conversions, ints to and from strings and literals:</h1> <p>Conversions from various bases, and you must know the base in advance (10 is the default). Note you can prefix them with what Python expects for its literals (see below) or remove the prefix:</p> <pre><code>&gt;&gt;&gt; int("0b11111", 2) 31 &gt;&gt;&gt; int("11111", 2) 31 &gt;&gt;&gt; int('0o37', 8) 31 &gt;&gt;&gt; int('37', 8) 31 &gt;&gt;&gt; int('0x1f', 16) 31 &gt;&gt;&gt; int('1f', 16) 31 </code></pre> <h3>Non-Decimal (i.e. Integer) Literals from other Bases</h3> <p>If your motivation is to have your own code clearly represent hard-coded specific values, however, you may not need to convert from the bases - you can let Python do it for you automatically with the correct syntax.</p> <p>You can use the apropos prefixes to get automatic conversion to integers with <a href="https://docs.python.org/3/reference/lexical_analysis.html#integer-literals" rel="nofollow">the following literals</a>. These are valid for Python 2 and 3:</p> <p>Binary, prefix <code>0b</code></p> <pre><code>&gt;&gt;&gt; 0b11111 31 </code></pre> <p>Octal, prefix <code>0o</code></p> <pre><code>&gt;&gt;&gt; 0o37 31 </code></pre> <p>Hexadecimal, prefix <code>0x</code></p> <pre><code>&gt;&gt;&gt; 0x1f 31 </code></pre> <p>This can be useful when describing binary flags, file permissions in code, or hex values for colors - for example, note no quotes:</p> <pre><code>&gt;&gt;&gt; 0b10101 # binary flags 21 &gt;&gt;&gt; 0o755 # read, write, execute perms for owner, read &amp; ex for group &amp; others 493 &gt;&gt;&gt; 0xffffff # the color, white, max values for red, green, and blue 16777215 </code></pre> <h3>Making ambiguous Python 2 octals compatible with Python 3</h3> <p>If you see an integer that starts with a 0, in Python 2, this is (deprecated) octal syntax.</p> <pre><code>&gt;&gt;&gt; 037 31 </code></pre> <p>It is bad because it looks like the value should be <code>37</code>. So in Python 3, it now raises a <code>SyntaxError</code>:</p> <pre><code>&gt;&gt;&gt; 037 File "&lt;stdin&gt;", line 1 037 ^ SyntaxError: invalid token </code></pre> <p>Convert your Python 2 octals to octals that work in both 2 and 3 with the <code>0o</code> prefix:</p> <pre><code>&gt;&gt;&gt; 0o37 31 </code></pre>
6
2015-07-23T13:26:05Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
33,017,514
<pre><code>def get_int_or_float(v): try: number_float = float(v) number_int = int(v) return number_int if number_float == number_int else number_float except ValueError: raise </code></pre>
3
2015-10-08T13:39:08Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
33,044,577
<pre><code>def num(s): """num(s) num(3),num(3.7)--&gt;3 num('3')--&gt;3, num('3.7')--&gt;3.7 num('3,700')--&gt;ValueError num('3a'),num('a3'),--&gt;ValueError num('3e4') --&gt; 30000.0 """ try: return int(s) except ValueError: try: return float(s) except ValueError: raise ValueError('argument is not a string of number') </code></pre>
5
2015-10-09T18:04:52Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
39,437,128
<pre><code>&gt;&gt;&gt; str_float = "545.2222" &gt;&gt;&gt; float(str_float) 545.2222 &gt;&gt;&gt; type(_) #check its type &lt;type 'float'&gt; &gt;&gt;&gt; str_int = "31" &gt;&gt;&gt; int(str_int) 31 &gt;&gt;&gt; type(_) #check its type &lt;type 'int'&gt; </code></pre>
0
2016-09-11T14:32:41Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
39,940,402
<pre><code>def num(s): try: for each in s: yield int(each) except ValueError: yield float(each) a = num(["123.55","345","44"]) print a.next() print a.next() </code></pre> <p>This is the most Pythonic way i could come up with. </p>
0
2016-10-09T05:40:12Z
[ "python", "string", "parsing", "floating-point", "integer" ]
How do you make a class attribute that isn't a standard data type?
379,995
<p>I have one class that needs to grab an attribute that is set in another. It's not a standard data type though. Here's the code;</p> <pre><code>class graphics: def __init__(self, Fullscreen = False, Width = 640, Height = 480): print "Graphics Init" SCREEN_SIZE = (Width, Height) pygame.init() if Fullscreen: self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32) print "Fullscreen Initialized" else: self.screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32) print "Non-Fullscreen Initialized" </code></pre> <p>What I need to do is reference the screen attribute, which I can set with self.screen and be readable within that class...but from another class I have to set</p> <pre><code>screen = ? </code></pre> <p>under</p> <pre><code>class graphics: </code></pre> <p>What does that question mark need to be? I've tried 0, None, ""...nothing seems to work, I have no idea what data type that pygame call would be. :S</p>
0
2008-12-19T03:03:34Z
380,001
<p>It's likely an <code>object</code> type so</p> <pre><code>self.screen = object() </code></pre> <p>might work (If I understood your question correctly).</p>
0
2008-12-19T03:09:01Z
[ "python", "pygame" ]
How do you make a class attribute that isn't a standard data type?
379,995
<p>I have one class that needs to grab an attribute that is set in another. It's not a standard data type though. Here's the code;</p> <pre><code>class graphics: def __init__(self, Fullscreen = False, Width = 640, Height = 480): print "Graphics Init" SCREEN_SIZE = (Width, Height) pygame.init() if Fullscreen: self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32) print "Fullscreen Initialized" else: self.screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32) print "Non-Fullscreen Initialized" </code></pre> <p>What I need to do is reference the screen attribute, which I can set with self.screen and be readable within that class...but from another class I have to set</p> <pre><code>screen = ? </code></pre> <p>under</p> <pre><code>class graphics: </code></pre> <p>What does that question mark need to be? I've tried 0, None, ""...nothing seems to work, I have no idea what data type that pygame call would be. :S</p>
0
2008-12-19T03:03:34Z
380,018
<p>ugh...PEBKAC.</p> <p>I'm so used to C that I keep forgetting you can do more than just prototype outside of defs.</p> <p>Rewrote as this and it worked:</p> <pre><code>class graphics: SCREEN_SIZE = (640, 480) screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32) def __init__(self, Fullscreen = False, Width = 640, Height = 480): print "Graphics Init" self.SCREEN_SIZE = (Width, Height) pygame.init() if Fullscreen: self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32) print "Fullscreen Initialized" else: self.screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32) print "Non-Fullscreen Initialized" </code></pre>
0
2008-12-19T03:22:25Z
[ "python", "pygame" ]
How do you make a class attribute that isn't a standard data type?
379,995
<p>I have one class that needs to grab an attribute that is set in another. It's not a standard data type though. Here's the code;</p> <pre><code>class graphics: def __init__(self, Fullscreen = False, Width = 640, Height = 480): print "Graphics Init" SCREEN_SIZE = (Width, Height) pygame.init() if Fullscreen: self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32) print "Fullscreen Initialized" else: self.screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32) print "Non-Fullscreen Initialized" </code></pre> <p>What I need to do is reference the screen attribute, which I can set with self.screen and be readable within that class...but from another class I have to set</p> <pre><code>screen = ? </code></pre> <p>under</p> <pre><code>class graphics: </code></pre> <p>What does that question mark need to be? I've tried 0, None, ""...nothing seems to work, I have no idea what data type that pygame call would be. :S</p>
0
2008-12-19T03:03:34Z
380,026
<p>You rarely, if ever, reference attributes of a class. You reference attributes of an object.</p> <p>(Also, class names should be uppercase: <code>Graphics</code>).</p> <pre><code>class Graphics: SCREEN_SIZE = (640, 480) def __init__(self, Fullscreen = False, Width = 640, Height = 480): print "Graphics Init" self.SCREEN_SIZE = (Width, Height) pygame.init() if Fullscreen: self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32) print "Fullscreen Initialized" else: self.screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32) print "Non-Fullscreen Initialized" </code></pre> <p>Here's an example of getting or setting an attribute of an object.</p> <pre><code>g= Graphics() # create an object # access the object's instance variables print "screen", g.screen g.screen= pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32) </code></pre> <p>Note that we created an object (<code>g</code>) from our class (<code>Graphics</code>). We don't reference the class very often at all. Almost the only time a class name is used is to create object instances (<code>Graphics()</code>). We rarely say <code>Graphics.this</code> or <code>Graphics.that</code> to refer to attributes of the class itself.</p>
0
2008-12-19T03:28:48Z
[ "python", "pygame" ]
How do you make a class attribute that isn't a standard data type?
379,995
<p>I have one class that needs to grab an attribute that is set in another. It's not a standard data type though. Here's the code;</p> <pre><code>class graphics: def __init__(self, Fullscreen = False, Width = 640, Height = 480): print "Graphics Init" SCREEN_SIZE = (Width, Height) pygame.init() if Fullscreen: self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32) print "Fullscreen Initialized" else: self.screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32) print "Non-Fullscreen Initialized" </code></pre> <p>What I need to do is reference the screen attribute, which I can set with self.screen and be readable within that class...but from another class I have to set</p> <pre><code>screen = ? </code></pre> <p>under</p> <pre><code>class graphics: </code></pre> <p>What does that question mark need to be? I've tried 0, None, ""...nothing seems to work, I have no idea what data type that pygame call would be. :S</p>
0
2008-12-19T03:03:34Z
380,666
<p>I'm thinking that a short explanation of the difference between class and instance attributes in Python might be helpful to you.</p> <p>When you write code like so:</p> <pre><code>class Graphics: screen_size = (1024, 768) </code></pre> <p>The class <code>Graphics</code> is actually an object itself -- a class object. Because you defined <code>screen_size</code> inside of it, <code>screen_size</code> is an attribute of the <code>Graphics</code> object. You can see this in the following:</p> <pre><code>assert Graphics.screen_size == (1024, 768) </code></pre> <p>In Python, these class objects can be used like functions -- just use the invocation syntax:</p> <pre><code>g = Graphics() </code></pre> <p><code>g</code> is called an "instance" of the class <code>Graphics</code>. When you create instances of a class, all attribute lookups that don't match attributes of the instance look at the attributes of the class object next. That's why this lookup works:</p> <pre><code>assert g.screen_size == (1024, 768) </code></pre> <p>If we add an attribute to the <em>instance</em> with the same name, however, the lookup on the instance will succeed, and it won't have to go looking to the class object. You basically "mask" the class object's value with a value set directly on the instance. Note that this <em>doesn't</em> change the value of the attribute in the class object:</p> <pre><code>g.screen_size = (1400, 1050) assert g.screen_size == (1400, 1050) assert Graphics.screen_size == (1024, 768) </code></pre> <p>So, what you're doing in your <code>__init__</code> method is <em>exactly</em> what we did above: setting an attribute of the <em>instance</em>, <code>self</code>.</p> <pre><code>class Graphics: screen_size = (1024, 768) def __init__(self): self.screen_size = (1400, 1050) g = Graphics() assert Graphics.screen_size == (1024, 768) assert g.screen_size == (1400, 1050) </code></pre> <p>The value <code>Graphics.screen_size</code> can be used anywhere after this class definition, as shown with the first assert statement in the above snippet.</p> <p>Edit: And don't forget to check out <a href="http://docs.python.org/tutorial/classes.html" rel="nofollow">the Python Tutorial's section on classes</a>, which covers all this and more.</p>
1
2008-12-19T11:01:06Z
[ "python", "pygame" ]
How do I respond to mouse clicks on sprites in PyGame?
380,420
<p>What is the canonical way of making your sprites respond to mouse clicks in PyGame ? </p> <p>Here's something simple, in my event loop:</p> <pre><code>for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() [...] elif ( event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]): for sprite in sprites: sprite.mouse_click(pygame.mouse.get_pos()) </code></pre> <p>Some questions about it:</p> <ol> <li>Is this the best way of responding to mouse clicks ? </li> <li>What if the mouse stays pressed on the sprite for some time ? How do I make a single event out of it ?</li> <li>Is this a reasonable way to notify all my sprites of the click ?</li> </ol> <p>Thanks in advance</p>
5
2008-12-19T08:54:57Z
393,256
<p>I usually give my clickable objects a click function, like in your example. I put all of those objects in a list, for easy iteration when the click functions are to be called.</p> <p>when checking for which mousebutton you press, use the button property of the event.</p> <pre><code>import pygame from pygame.locals import * #This lets you use pygame's constants directly. for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN: #Better to seperate to a new if statement aswell, since there's more buttons that can be clicked and makes for cleaner code. if event.button == 1: for object in clickableObjectsList: object.clickCheck(event.pos) </code></pre> <p>I would say this is the recommended way of doing it. The click only registers once, so it wont tell your sprite if the user is "dragging" with a button. That can easily be done with a boolean that is set to true with the MOUSEBUTTONDOWN event, and false with the MOUSEBUTTONUP. The have "draggable" objects iterated for activating their functions... and so on.</p> <p>However, if you don't want to use an event handler, you can let an update function check for input with:</p> <pre><code>pygame.mouse.get_pos() pygame.mouse.get_pressed(). </code></pre> <p>This is a bad idea for larger projects, since it can create hard to find bugs. Better just keeping events in one place. Smaller games, like simple arcade games might make more sense using the probing style though.</p>
10
2008-12-25T22:46:33Z
[ "python", "pygame" ]
How do I get the full XML or HTML content of an element using ElementTree?
380,603
<p>That is, all text and subtags, without the tag of an element itself?</p> <p>Having</p> <pre><code>&lt;p&gt;blah &lt;b&gt;bleh&lt;/b&gt; blih&lt;/p&gt; </code></pre> <p>I want </p> <pre><code>blah &lt;b&gt;bleh&lt;/b&gt; blih </code></pre> <p>element.text returns "blah " and etree.tostring(element) returns:</p> <pre><code>&lt;p&gt;blah &lt;b&gt;bleh&lt;/b&gt; blih&lt;/p&gt; </code></pre>
5
2008-12-19T10:33:52Z
380,717
<p>ElementTree works perfectly, you have to assemble the answer yourself. Something like this...</p> <pre><code>"".join( [ "" if t.text is None else t.text ] + [ xml.tostring(e) for e in t.getchildren() ] ) </code></pre> <p>Thanks to JV amd PEZ for pointing out the errors.</p> <p><hr /></p> <p>Edit.</p> <pre><code>&gt;&gt;&gt; import xml.etree.ElementTree as xml &gt;&gt;&gt; s= '&lt;p&gt;blah &lt;b&gt;bleh&lt;/b&gt; blih&lt;/p&gt;\n' &gt;&gt;&gt; t=xml.fromstring(s) &gt;&gt;&gt; "".join( [ t.text ] + [ xml.tostring(e) for e in t.getchildren() ] ) 'blah &lt;b&gt;bleh&lt;/b&gt; blih' &gt;&gt;&gt; </code></pre> <p>Tail not needed.</p>
11
2008-12-19T11:21:52Z
[ "python", "xml", "api", "elementtree" ]
How do I get the full XML or HTML content of an element using ElementTree?
380,603
<p>That is, all text and subtags, without the tag of an element itself?</p> <p>Having</p> <pre><code>&lt;p&gt;blah &lt;b&gt;bleh&lt;/b&gt; blih&lt;/p&gt; </code></pre> <p>I want </p> <pre><code>blah &lt;b&gt;bleh&lt;/b&gt; blih </code></pre> <p>element.text returns "blah " and etree.tostring(element) returns:</p> <pre><code>&lt;p&gt;blah &lt;b&gt;bleh&lt;/b&gt; blih&lt;/p&gt; </code></pre>
5
2008-12-19T10:33:52Z
380,719
<p>No idea if an external library might be an option, but anyway -- assuming there is one <code>&lt;p&gt;</code> with this text on the page, a jQuery-solution would be:</p> <pre><code>alert($('p').html()); // returns blah &lt;b&gt;bleh&lt;/b&gt; blih </code></pre>
-3
2008-12-19T11:23:59Z
[ "python", "xml", "api", "elementtree" ]
How do I get the full XML or HTML content of an element using ElementTree?
380,603
<p>That is, all text and subtags, without the tag of an element itself?</p> <p>Having</p> <pre><code>&lt;p&gt;blah &lt;b&gt;bleh&lt;/b&gt; blih&lt;/p&gt; </code></pre> <p>I want </p> <pre><code>blah &lt;b&gt;bleh&lt;/b&gt; blih </code></pre> <p>element.text returns "blah " and etree.tostring(element) returns:</p> <pre><code>&lt;p&gt;blah &lt;b&gt;bleh&lt;/b&gt; blih&lt;/p&gt; </code></pre>
5
2008-12-19T10:33:52Z
380,783
<p>I doubt ElementTree is the thing to use for this. But assuming you have strong reasons for using it maybe you could try stripping the root tag from the fragment:</p> <pre><code> re.sub(r'(^&lt;%s\b.*?&gt;|&lt;/%s\b.*?&gt;$)' % (element.tag, element.tag), '', ElementTree.tostring(element)) </code></pre>
1
2008-12-19T11:56:30Z
[ "python", "xml", "api", "elementtree" ]
How do I get the full XML or HTML content of an element using ElementTree?
380,603
<p>That is, all text and subtags, without the tag of an element itself?</p> <p>Having</p> <pre><code>&lt;p&gt;blah &lt;b&gt;bleh&lt;/b&gt; blih&lt;/p&gt; </code></pre> <p>I want </p> <pre><code>blah &lt;b&gt;bleh&lt;/b&gt; blih </code></pre> <p>element.text returns "blah " and etree.tostring(element) returns:</p> <pre><code>&lt;p&gt;blah &lt;b&gt;bleh&lt;/b&gt; blih&lt;/p&gt; </code></pre>
5
2008-12-19T10:33:52Z
381,614
<p>This is the solution I ended up using:</p> <pre><code>def element_to_string(element): s = element.text or "" for sub_element in element: s += etree.tostring(sub_element) s += element.tail return s </code></pre>
5
2008-12-19T17:27:09Z
[ "python", "xml", "api", "elementtree" ]
How do I get the full XML or HTML content of an element using ElementTree?
380,603
<p>That is, all text and subtags, without the tag of an element itself?</p> <p>Having</p> <pre><code>&lt;p&gt;blah &lt;b&gt;bleh&lt;/b&gt; blih&lt;/p&gt; </code></pre> <p>I want </p> <pre><code>blah &lt;b&gt;bleh&lt;/b&gt; blih </code></pre> <p>element.text returns "blah " and etree.tostring(element) returns:</p> <pre><code>&lt;p&gt;blah &lt;b&gt;bleh&lt;/b&gt; blih&lt;/p&gt; </code></pre>
5
2008-12-19T10:33:52Z
34,084,933
<p>These are good answers, which answer the OP's question, particularly if the question is confined to HTML. But documents are inherently messy, and the depth of element nesting is usually impossible to predict.</p> <p>To simulate DOM's getTextContent() you would have to use a (very) simple recursive mechanism. </p> <p>To get just the bare text:</p> <pre><code>def get_deep_text( element ): text = element.text or '' for subelement in element: text += get_deep_text( subelement ) text += element.tail or '' return text print( get_deep_text( element_of_interest )) </code></pre> <p>To get all the details about the boundaries between raw text:</p> <pre><code>root_el_of_interest.element_count = 0 def get_deep_text_w_boundaries( element, depth = 0 ): root_el_of_interest.element_count += 1 element_no = root_el_of_interest.element_count indent = depth * ' ' text1 = '%s(el %d - attribs: %s)\n' % ( indent, element_no, element.attrib, ) text1 += '%s(el %d - text: |%s|)' % ( indent, element_no, element.text or '', ) print( text1 ) for subelement in element: get_deep_text_w_boundaries( subelement, depth + 1 ) text2 = '%s(el %d - tail: |%s|)' % ( indent, element_no, element.tail or '', ) print( text2 ) get_deep_text_w_boundaries( root_el_of_interest ) </code></pre> <p>Example output from single para in LibreOffice Writer doc (.fodt file):</p> <pre><code>(el 1 - attribs: {'{urn:oasis:names:tc:opendocument:xmlns:text:1.0}style-name': 'Standard'}) (el 1 - text: |Ci-après individuellement la "|) (el 2 - attribs: {'{urn:oasis:names:tc:opendocument:xmlns:text:1.0}style-name': 'T5'}) (el 2 - text: |Partie|) (el 2 - tail: |" et ensemble les "|) (el 3 - attribs: {'{urn:oasis:names:tc:opendocument:xmlns:text:1.0}style-name': 'T5'}) (el 3 - text: |Parties|) (el 3 - tail: |", |) (el 1 - tail: | |) </code></pre> <p>One of the points about messiness is that there is no hard and fast rule about when a text style indicates a word boundary and when it doesnt: superscript immediately following a word (with no white space) means a separate word in all use cases I can imagine. OTOH sometimes you might find, for example, a document where the first letter is either bolded for some reason, or perhaps uses a different style for the first letter to represent it as upper case, rather than simply using the normal UC character.</p> <p>And of course the less primarily "English-centric" this discussion gets the greater the subtleties and complexities!</p>
3
2015-12-04T09:29:26Z
[ "python", "xml", "api", "elementtree" ]
How do I get PIL to work when built on mingw/cygwin?
380,731
<p>I'm trying to build PIL 1.1.6 against cygwin or mingw whilst running against a windows install of python. When I do either the build works but I get the following failure when trying to save files.</p> <pre> $ python25 Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from PIL.Image import open >>> im = open('test.gif') >>> im.save('output1.gif') Traceback (most recent call last): File "", line 1, in File "c:\Python25\Lib\site-packages\PIL\Image.py", line 1405, in save save_handler(self, fp, filename) File "c:\Python25\Lib\site-packages\PIL\GifImagePlugin.py", line 291, in _save ImageFile._save(imOut, fp, [("gif", (0,0)+im.size, 0, rawmode)]) File "c:\Python25\Lib\site-packages\PIL\ImageFile.py", line 491, in _save s = e.encode_to_file(fh, bufsize) IOError: [Errno 0] Error >>> </pre> <p>I'm not compiling with the libraries for jpeg or zip support but I don't think this should be relevant here.</p> <p>The failing line seems to be a write in encode_to_file in encode.c. </p> <p>I'm suspiscious that this occurs because a file descriptor is being passed from Python (which was build under visual studio 2003) to _imaging.pyd but that the file descriptors don't match because on windows file descriptors are and abstraction on top of the operating system. Does anyone know anything about this?</p>
3
2008-12-19T11:31:12Z
471,677
<p>As far as I can tell from some cursory Google searching, you need to rebase the DLLs after building PIL in order for it to work properly on Cygwin.</p> <p>References: </p> <ul> <li><p><strong><a href="http://jetfar.com/cygwin-install-python-imaging-library/" rel="nofollow">http://jetfar.com/cygwin-install-python-imaging-library/</a></strong></p></li> <li><p><strong><a href="http://www.cygwin.com/ml/cygwin/2003-06/msg01121.html" rel="nofollow">http://www.cygwin.com/ml/cygwin/2003-06/msg01121.html</a></strong></p></li> </ul>
1
2009-01-23T02:29:23Z
[ "python", "windows", "cygwin", "python-imaging-library" ]
How to do this - python dictionary traverse and search
380,734
<p>I have nested dictionaries:</p> <pre><code>{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'}, u'key1': {'attrs': {'entity': 'r', 'hash': '34njasd3h43b4n3', 'id': '4130-1'}, u'key2': {'attrs': {'entity': 'c', 'hash': '34njasd3h43bdsfsd4n3', 'id': '4130-1-1'}}}, u'key3': {'attrs': {'entity': 'r', 'hash': '34njasasasd3h43b4n3', 'id': '4130-2'}, u'key4': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-1'}}, u'key5': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-2'}}}}, 'someohterthing': 'someothervalue', 'something': 'somevalue'} </code></pre> <p>given an <code>id</code> - one of all the <code>ids</code> like <code>4130</code> to <code>4130-2-2</code>.<br> whats the easiest way to navigate to the correct dictionary?</p> <p>Like if the given <code>id</code> is <code>4130-2-1</code> then it should reach the dictionary with <code>key=key5</code></p> <p>non xml approaches please.</p> <p><strong>Edit(1):</strong> The nesting is between <code>1</code> to <code>4</code> levels, but I know the nesting before I parse.</p> <p><strong>Edit(2)</strong>: Fixed the code.</p> <p>**Edit(3):**Fixed code again for string values of <code>ids</code>. Please excuse for the confusion created. This is final I hope :)</p>
7
2008-12-19T11:33:06Z
380,759
<p>Well, if you have to do it only a few times, you can just use nested dict.iteritems() to find what you are looking for.</p> <p>If you plan to do it several times, performances will quickly becomes an issue. In that case you could :</p> <ul> <li><p>change the way you data is returned to you to something more suitable.</p></li> <li><p>if you can't, convert the data once the fly to a dict between id and keys (using iteritems). Then use it.</p></li> </ul>
0
2008-12-19T11:43:22Z
[ "python", "dictionary", "parsing" ]
How to do this - python dictionary traverse and search
380,734
<p>I have nested dictionaries:</p> <pre><code>{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'}, u'key1': {'attrs': {'entity': 'r', 'hash': '34njasd3h43b4n3', 'id': '4130-1'}, u'key2': {'attrs': {'entity': 'c', 'hash': '34njasd3h43bdsfsd4n3', 'id': '4130-1-1'}}}, u'key3': {'attrs': {'entity': 'r', 'hash': '34njasasasd3h43b4n3', 'id': '4130-2'}, u'key4': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-1'}}, u'key5': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-2'}}}}, 'someohterthing': 'someothervalue', 'something': 'somevalue'} </code></pre> <p>given an <code>id</code> - one of all the <code>ids</code> like <code>4130</code> to <code>4130-2-2</code>.<br> whats the easiest way to navigate to the correct dictionary?</p> <p>Like if the given <code>id</code> is <code>4130-2-1</code> then it should reach the dictionary with <code>key=key5</code></p> <p>non xml approaches please.</p> <p><strong>Edit(1):</strong> The nesting is between <code>1</code> to <code>4</code> levels, but I know the nesting before I parse.</p> <p><strong>Edit(2)</strong>: Fixed the code.</p> <p>**Edit(3):**Fixed code again for string values of <code>ids</code>. Please excuse for the confusion created. This is final I hope :)</p>
7
2008-12-19T11:33:06Z
380,769
<p>If you want to solve the problem in a general way, no matter how many level of nesting you have in your dict, then create a recursive function which will traverse the tree:</p> <pre><code>def traverse_tree(dictionary, id=None): for key, value in dictionary.items(): if key == 'id': if value == id: print dictionary else: traverse_tree(value, id) return &gt;&gt;&gt; traverse_tree({1: {'id': 2}, 2: {'id': 3}}, id=2) {'id': 2} </code></pre>
12
2008-12-19T11:44:56Z
[ "python", "dictionary", "parsing" ]
How to do this - python dictionary traverse and search
380,734
<p>I have nested dictionaries:</p> <pre><code>{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'}, u'key1': {'attrs': {'entity': 'r', 'hash': '34njasd3h43b4n3', 'id': '4130-1'}, u'key2': {'attrs': {'entity': 'c', 'hash': '34njasd3h43bdsfsd4n3', 'id': '4130-1-1'}}}, u'key3': {'attrs': {'entity': 'r', 'hash': '34njasasasd3h43b4n3', 'id': '4130-2'}, u'key4': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-1'}}, u'key5': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-2'}}}}, 'someohterthing': 'someothervalue', 'something': 'somevalue'} </code></pre> <p>given an <code>id</code> - one of all the <code>ids</code> like <code>4130</code> to <code>4130-2-2</code>.<br> whats the easiest way to navigate to the correct dictionary?</p> <p>Like if the given <code>id</code> is <code>4130-2-1</code> then it should reach the dictionary with <code>key=key5</code></p> <p>non xml approaches please.</p> <p><strong>Edit(1):</strong> The nesting is between <code>1</code> to <code>4</code> levels, but I know the nesting before I parse.</p> <p><strong>Edit(2)</strong>: Fixed the code.</p> <p>**Edit(3):**Fixed code again for string values of <code>ids</code>. Please excuse for the confusion created. This is final I hope :)</p>
7
2008-12-19T11:33:06Z
380,874
<p>Your structure is unpleasantly irregular. Here's a version with a <strong>Visitor</strong> function that traverses the <code>attrs</code> sub-dictionaries.</p> <pre><code>def walkDict( aDict, visitor, path=() ): for k in aDict: if k == 'attrs': visitor( path, aDict[k] ) elif type(aDict[k]) != dict: pass else: walkDict( aDict[k], visitor, path+(k,) ) def printMe( path, element ): print path, element def filterFor( path, element ): if element['id'] == '4130-2-2': print path, element </code></pre> <p>You'd use it like this.</p> <pre><code>walkDict( myDict, filterFor ) </code></pre> <p>This can be turned into a generator instead of a <strong>Visitor</strong>; it would <code>yield path, aDict[k]</code> instead of invoking the visitor function.</p> <p>You'd use it in a for loop.</p> <pre><code>for path, attrDict in walkDictIter( aDict ): # process attrDict... </code></pre>
12
2008-12-19T12:45:28Z
[ "python", "dictionary", "parsing" ]
How to do this - python dictionary traverse and search
380,734
<p>I have nested dictionaries:</p> <pre><code>{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'}, u'key1': {'attrs': {'entity': 'r', 'hash': '34njasd3h43b4n3', 'id': '4130-1'}, u'key2': {'attrs': {'entity': 'c', 'hash': '34njasd3h43bdsfsd4n3', 'id': '4130-1-1'}}}, u'key3': {'attrs': {'entity': 'r', 'hash': '34njasasasd3h43b4n3', 'id': '4130-2'}, u'key4': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-1'}}, u'key5': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-2'}}}}, 'someohterthing': 'someothervalue', 'something': 'somevalue'} </code></pre> <p>given an <code>id</code> - one of all the <code>ids</code> like <code>4130</code> to <code>4130-2-2</code>.<br> whats the easiest way to navigate to the correct dictionary?</p> <p>Like if the given <code>id</code> is <code>4130-2-1</code> then it should reach the dictionary with <code>key=key5</code></p> <p>non xml approaches please.</p> <p><strong>Edit(1):</strong> The nesting is between <code>1</code> to <code>4</code> levels, but I know the nesting before I parse.</p> <p><strong>Edit(2)</strong>: Fixed the code.</p> <p>**Edit(3):**Fixed code again for string values of <code>ids</code>. Please excuse for the confusion created. This is final I hope :)</p>
7
2008-12-19T11:33:06Z
380,987
<p>This kind of problem is often better solved with proper class definitions, not generic dictionaries.</p> <pre><code>class ProperObject( object ): """A proper class definition for each "attr" dictionary.""" def __init__( self, path, attrDict ): self.path= path self.__dict__.update( attrDict ) def __str__( self ): return "path %r, entity %r, hash %r, id %r" % ( self.path, self.entity, self.hash, self.id ) masterDict= {} def builder( path, element ): masterDict[path]= ProperObject( path, element ) # Use the Visitor to build ProperObjects for each "attr" walkDict( myDict, builder ) # Now that we have a simple dictionary of Proper Objects, things are simple for k,v in masterDict.items(): if v.id == '4130-2-2': print v </code></pre> <p>Also, now that you have Proper Object definitions, you can do the following</p> <pre><code># Create an "index" of your ProperObjects import collections byId= collections.defaultdict(list) for k in masterDict: byId[masterDict[k].id].append( masterDict[k] ) # Look up a particular item in the index print map( str, byId['4130-2-2'] ) </code></pre>
9
2008-12-19T13:37:03Z
[ "python", "dictionary", "parsing" ]
How to do this - python dictionary traverse and search
380,734
<p>I have nested dictionaries:</p> <pre><code>{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'}, u'key1': {'attrs': {'entity': 'r', 'hash': '34njasd3h43b4n3', 'id': '4130-1'}, u'key2': {'attrs': {'entity': 'c', 'hash': '34njasd3h43bdsfsd4n3', 'id': '4130-1-1'}}}, u'key3': {'attrs': {'entity': 'r', 'hash': '34njasasasd3h43b4n3', 'id': '4130-2'}, u'key4': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-1'}}, u'key5': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-2'}}}}, 'someohterthing': 'someothervalue', 'something': 'somevalue'} </code></pre> <p>given an <code>id</code> - one of all the <code>ids</code> like <code>4130</code> to <code>4130-2-2</code>.<br> whats the easiest way to navigate to the correct dictionary?</p> <p>Like if the given <code>id</code> is <code>4130-2-1</code> then it should reach the dictionary with <code>key=key5</code></p> <p>non xml approaches please.</p> <p><strong>Edit(1):</strong> The nesting is between <code>1</code> to <code>4</code> levels, but I know the nesting before I parse.</p> <p><strong>Edit(2)</strong>: Fixed the code.</p> <p>**Edit(3):**Fixed code again for string values of <code>ids</code>. Please excuse for the confusion created. This is final I hope :)</p>
7
2008-12-19T11:33:06Z
16,508,033
<p>This is an old question but still a top google result, so I'll update:</p> <p>A friend and myself published a library to solve (very nearly) this exact problem. dpath-python (no relation to the perl dpath module which does similar things).</p> <p><a href="http://github.com/akesterson/dpath-python" rel="nofollow">http://github.com/akesterson/dpath-python</a></p> <p>All you would need to do is something like this:</p> <pre><code>$ easy_install dpath &gt;&gt;&gt; import dpath.util &gt;&gt;&gt; results = [] &gt;&gt;&gt; for (path, value) in dpath.util.search(my_dictionary, "*/attrs/entity/4130*", yielded=True): &gt;&gt;&gt; ... parent = dpath.util.search("/".join(path.split("/")[:-2]) &gt;&gt;&gt; ... results.append(parent) </code></pre> <p>... that would give you a list of all the dictionary objects that matched your search, i.e., all the objects that had (key = 4130*). The parent bit is a little janky, but it would work.</p>
1
2013-05-12T13:46:28Z
[ "python", "dictionary", "parsing" ]
How to do this - python dictionary traverse and search
380,734
<p>I have nested dictionaries:</p> <pre><code>{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'}, u'key1': {'attrs': {'entity': 'r', 'hash': '34njasd3h43b4n3', 'id': '4130-1'}, u'key2': {'attrs': {'entity': 'c', 'hash': '34njasd3h43bdsfsd4n3', 'id': '4130-1-1'}}}, u'key3': {'attrs': {'entity': 'r', 'hash': '34njasasasd3h43b4n3', 'id': '4130-2'}, u'key4': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-1'}}, u'key5': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-2'}}}}, 'someohterthing': 'someothervalue', 'something': 'somevalue'} </code></pre> <p>given an <code>id</code> - one of all the <code>ids</code> like <code>4130</code> to <code>4130-2-2</code>.<br> whats the easiest way to navigate to the correct dictionary?</p> <p>Like if the given <code>id</code> is <code>4130-2-1</code> then it should reach the dictionary with <code>key=key5</code></p> <p>non xml approaches please.</p> <p><strong>Edit(1):</strong> The nesting is between <code>1</code> to <code>4</code> levels, but I know the nesting before I parse.</p> <p><strong>Edit(2)</strong>: Fixed the code.</p> <p>**Edit(3):**Fixed code again for string values of <code>ids</code>. Please excuse for the confusion created. This is final I hope :)</p>
7
2008-12-19T11:33:06Z
23,568,748
<p>Since recursion is known to be limited in python (see <a href="http://stackoverflow.com/questions/3323001/maximum-recursion-depth">Maximum recursion depth?</a>) I would rather have a loop based answer to this question, so the answer can be adapted to any level of depth in the dictionary. For that, the function </p> <pre><code>def walkDict( aDict, visitor, path=() ): for k in aDict: if k == 'attrs': visitor( path, aDict[k] ) elif type(aDict[k]) != dict: pass else: walkDict( aDict[k], visitor, path+(k,) ) </code></pre> <p>Can be replaced by:</p> <pre><code>def walkDictLoop(aDict, visitor, path=()): toProcess = [(aDict, path)] while toProcess: dictNode, pathNode = toProcess.pop(0) for k in dictNode: if k == 'attrs': visitor(pathNode, dictNode[k]) if isinstance(dictNode[k], dict): toProcess.append( (dictNode[k], pathNode+(k,)) ) </code></pre>
0
2014-05-09T15:41:51Z
[ "python", "dictionary", "parsing" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
380,876
<p>I don't know if it's pythonic enough, but in the Java world listening on a defined port is a pretty widely used solution, as it works on all major platforms and doesn't have any problems with crashing programs.</p> <p>Another advantage of listening to a port is that you could send a command to the running instance. For example when the users starts the program a second time, you could send the running instance a command to tell it to open another window (that's what Firefox does, for example. I don't know if they use TCP ports or named pipes or something like that, 'though).</p>
16
2008-12-19T12:46:38Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
380,894
<p>This may work.</p> <ol> <li><p>Attempt create a PID file to a known location. If you fail, someone has the file locked, you're done.</p></li> <li><p>When you finish normally, close and remove the PID file, so someone else can overwrite it.</p></li> </ol> <p>You can wrap your program in a shell script that removes the PID file even if your program crashes.</p> <p>You can, also, use the PID file to kill the program if it hangs.</p>
4
2008-12-19T12:56:55Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
380,904
<p>Using a lock-file is a quite common approach on unix. If it crashes, you have to clean up manually. You could stor the PID in the file, and on startup check if there is a process with this PID, overriding the lock-file if not. (However, you also need a lock around the read-file-check-pid-rewrite-file). You will find what you need for getting and checking pid in the <a href="http://docs.python.org/library/os.html" rel="nofollow">os</a>-package. The common way of checking if there exists a process with a given pid, is to send it a non-fatal signal.</p> <p>Other alternatives could be combining this with flock or posix semaphores.</p> <p>Opening a network socket, as saua proposed, would probably be the easiest and most portable.</p>
3
2008-12-19T13:01:54Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
380,943
<p>Use a pid file. You have some known location, "/path/to/pidfile" and at startup you do something like this (partially pseudocode because I'm pre-coffee and don't want to work all that hard):</p> <pre><code>import os, os.path pidfilePath = """/path/to/pidfile""" if os.path.exists(pidfilePath): pidfile = open(pidfilePath,"r") pidString = pidfile.read() if &lt;pidString is equal to os.getpid()&gt;: # something is real weird Sys.exit(BADCODE) else: &lt;use ps or pidof to see if the process with pid pidString is still running&gt; if &lt;process with pid == 'pidString' is still running&gt;: Sys.exit(ALREADAYRUNNING) else: # the previous server must have crashed &lt;log server had crashed&gt; &lt;reopen pidfilePath for writing&gt; pidfile.write(os.getpid()) else: &lt;open pidfilePath for writing&gt; pidfile.write(os.getpid()) </code></pre> <p>So, in other words, you're checking if a pidfile exists; if not, write your pid to that file. If the pidfile does exist, then check to see if the pid is the pid of a running process; if so, then you've got another live process running, so just shut down. If not, then the previous process crashed, so log it, and then write your own pid to the file in place of the old one. Then continue.</p>
5
2008-12-19T13:16:39Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
384,493
<p>Simple, <s>cross-platform</s> solution, found in <strong><a href="http://stackoverflow.com/questions/220525/ensuring-a-single-instance-of-an-application-in-linux#221159">another question</a></strong> by <a href="http://stackoverflow.com/users/12138/zgoda">zgoda</a>:</p> <pre><code>import fcntl, sys pid_file = 'program.pid' fp = open(pid_file, 'w') try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: # another instance is running sys.exit(0) </code></pre> <p>A lot like S.Lott's suggestion, but with the code.</p>
25
2008-12-21T14:02:47Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
385,862
<p>You already found reply to similar question in another thread, so for completeness sake see how to achieve the same on Windows uning named mutex.</p> <p><a href="http://code.activestate.com/recipes/474070/" rel="nofollow">http://code.activestate.com/recipes/474070/</a></p>
4
2008-12-22T09:35:09Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
1,265,445
<p>The following code should do the job, it is cross-platform and runs on Python 2.4-3.2. I tested it on Windows, OS X and Linux.</p> <pre><code>from tendo import singleton me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running </code></pre> <p>The latest code version is available <a href="https://github.com/pycontribs/tendo/blob/master/tendo/singleton.py">singleton.py</a>. Please <a href="https://github.com/pycontribs/tendo/issues">file bugs here</a>.</p> <p>You can install tend using one of the following methods:</p> <ul> <li><code>easy_install tendo</code></li> <li><code>pip install tendo</code></li> <li>manually by getting it from <a href="http://pypi.python.org/pypi/tendo">http://pypi.python.org/pypi/tendo</a></li> </ul>
56
2009-08-12T10:45:24Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
1,662,504
<p>This code is Linux specific ( it uses 'abstract' UNIX domain sockets ) but it is simple and won't leave stale lock files around. I prefer it to the solution above because it doesn't require a specially reserved TCP port. </p> <pre><code>try: import socket s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) ## Create an abstract socket, by prefixing it with null. s.bind( '\0postconnect_gateway_notify_lock') except socket.error, e: error_code = e.args[0] error_string = e.args[1] print "Process already running (%d:%s ). Exiting" % ( error_code, error_string) sys.exit (0) </code></pre> <p>The unique string <code>postconnect_gateway_notify_lock</code> can be changed to allow multiple programs that need a single instance enforced.</p>
19
2009-11-02T17:10:48Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
4,337,301
<p>I'm posting this as an answer because I'm a new user and Stack Overflow won't let me vote yet.</p> <p>Sorin Sbarnea's solution works for me under OS X, Linux and Windows, and I am grateful for it.</p> <p>However, tempfile.gettempdir() behaves one way under OS X and Windows and another under other some/many/all(?) *nixes (ignoring the fact that OS X is also Unix!). The difference is important to this code. </p> <p>OS X and Windows have user-specific temp directories, so a tempfile created by one user isn't visible to another user. By contrast, under many versions of *nix (I tested Ubuntu 9, RHEL 5, OpenSolaris 2008 and FreeBSD 8), the temp dir is /tmp for all users.</p> <p>That means that when the lockfile is created on a multi-user machine, it's created in /tmp and only the user who creates the lockfile the first time will be able to run the application.</p> <p>A possible solution is to embed the current username in the name of the lock file.</p> <p>It's worth noting that the OP's solution of grabbing a port will also misbehave on a multi-user machine.</p>
2
2010-12-02T16:29:22Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
7,258,093
<p>Never written python before, but this is what I've just implemented in mycheckpoint, to prevent it being started twice or more by crond:</p> <pre><code>import os import sys import fcntl fh=0 def run_once(): global fh fh=open(os.path.realpath(__file__),'r') try: fcntl.flock(fh,fcntl.LOCK_EX|fcntl.LOCK_NB) except: os._exit(0) run_once() </code></pre> <p>Found Slava-N's suggestion after posting this in another issue (http://stackoverflow.com/questions/2959474). This one is called as a function, locks the executing scripts file (not a pid file) and maintains the lock until the script ends (normal or error).</p>
5
2011-08-31T14:02:54Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
15,135,898
<p>I would just do something like: </p> <pre><code>if commands.getstatusoutput("mkdir /tmp/test")[0]: print "Exiting" sys.exit(1) </code></pre> <p>And somewhere at the end of my code, I'll remove the directory. <code>mkdir</code> is a atomic and works pretty well here. </p>
-1
2013-02-28T12:45:15Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
17,838,832
<p>I keep suspecting there ought to be a good POSIXy solution using process groups, without having to hit the file system, but I can't quite nail it down. Something like:</p> <p>On startup, your process sends a 'kill -0' to all processes in a particular group. If any such processes exist, it exits. Then it joins the group. No other processes use that group.</p> <p>However, this has a race condition - multiple processes could all do this at precisely the same time and all end up joining the group and running simultaneously. By the time you've added some sort of mutex to make it watertight, you no longer need the process groups.</p> <p>This might be acceptable if your process only gets started by cron, once every minute or every hour, but it makes me a bit nervous that it would go wrong precisely on the day when you don't want it to.</p> <p>I guess this isn't a very good solution after all, unless someone can improve on it?</p>
0
2013-07-24T15:44:41Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
23,262,587
<p>I use <code>single_process</code> on my gentoo;</p> <pre><code>pip install single_process </code></pre> <p><strong>example</strong>: </p> <pre><code>from single_process import single_process @single_process def main(): print 1 if __name__ == "__main__": main() </code></pre> <p>refer: <a href="https://pypi.python.org/pypi/single_process/1.0" rel="nofollow">https://pypi.python.org/pypi/single_process/1.0</a></p>
2
2014-04-24T07:31:24Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
28,186,309
<p>I ran into this exact problem last week, and although I did find some good solutions, I decided to make a very simple and clean python package and uploaded it to PyPI. It differs from tendo in that it can lock any string resource name. Although you could certainly lock <code>__file__</code> to achieve the same effect.</p> <p>Install with: <code>pip install quicklock</code></p> <p>Using it is extremely simple:</p> <pre><code>[nate@Nates-MacBook-Pro-3 ~/live] python Python 2.7.6 (default, Sep 9 2014, 15:04:36) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from quicklock import singleton &gt;&gt;&gt; # Let's create a lock so that only one instance of a script will run ... &gt;&gt;&gt; singleton('hello world') &gt;&gt;&gt; &gt;&gt;&gt; # Let's try to do that again, this should fail ... &gt;&gt;&gt; singleton('hello world') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/nate/live/gallery/env/lib/python2.7/site-packages/quicklock/quicklock.py", line 47, in singleton raise RuntimeError('Resource &lt;{}&gt; is currently locked by &lt;Process {}: "{}"&gt;'.format(resource, other_process.pid, other_process.name())) RuntimeError: Resource &lt;hello world&gt; is currently locked by &lt;Process 24801: "python"&gt; &gt;&gt;&gt; &gt;&gt;&gt; # But if we quit this process, we release the lock automatically ... &gt;&gt;&gt; ^D [nate@Nates-MacBook-Pro-3 ~/live] python Python 2.7.6 (default, Sep 9 2014, 15:04:36) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from quicklock import singleton &gt;&gt;&gt; singleton('hello world') &gt;&gt;&gt; &gt;&gt;&gt; # No exception was thrown, we own 'hello world'! </code></pre> <p>Take a look: <a href="https://pypi.python.org/pypi/quicklock" rel="nofollow">https://pypi.python.org/pypi/quicklock</a></p>
0
2015-01-28T06:51:51Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
33,127,087
<p>linux example</p> <p>This method is based on the creation of a temporary file automatically deleted after you close the application. the program launch we verify the existence of the file; if the file exists ( there is a pending execution) , the program is closed ; otherwise it creates the file and continues the execution of the program.</p> <pre><code>from tempfile import * import time import os import sys f = NamedTemporaryFile( prefix='lock01_', delete=True) if not [f for f in os.listdir('/tmp') if f.find('lock01_')!=-1] else sys.exit() YOUR CODE COMES HERE </code></pre>
0
2015-10-14T13:44:47Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
36,489,564
<p>For anybody using <strong>wxPython</strong> for their application, you can use the function <code>wx.SingleInstanceChecker</code> <a href="https://wxpython.org/Phoenix/docs/html/wx.SingleInstanceChecker.html" rel="nofollow">documented here</a>.</p> <p>I personally use a subclass of <code>wx.App</code> which makes use of <code>wx.SingleInstanceChecker</code> and returns <code>False</code> from <code>OnInit()</code> if there is an existing instance of the app already executing like so:</p> <pre><code>import wx class SingleApp(wx.App): """ class that extends wx.App and only permits a single running instance. """ def OnInit(self): """ wx.App init function that returns False if the app is already running. """ self.name = "SingleApp-%s".format(wx.GetUserId()) self.instance = wx.SingleInstanceChecker(self.name) if self.instance.IsAnotherRunning(): wx.MessageBox( "An instance of the application is already running", "Error", wx.OK | wx.ICON_WARNING ) return False return True </code></pre> <p>This is a simple drop-in replacement for <code>wx.App</code> that prohibits multiple instances. To use it simply replace <code>wx.App</code> with <code>SingleApp</code> in your code like so:</p> <pre><code>app = SingleApp(redirect=False) frame = wx.Frame(None, wx.ID_ANY, "Hello World") frame.Show(True) app.MainLoop() </code></pre>
2
2016-04-08T00:34:12Z
[ "python", "locking" ]
Python: single instance of program
380,870
<p>Is there a Pythonic way to have only one instance of a program running? </p> <p>The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this? </p> <p>(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)</p> <p><b>Update</b>: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.</p>
66
2008-12-19T12:42:52Z
39,665,123
<p>Here is my eventual Windows-only solution. Put the following into a module, perhaps called 'onlyone.py', or whatever. Include that module directly into your __ main __ python script file.</p> <pre><code>import win32event, win32api, winerror, time, sys, os main_path = os.path.abspath(sys.modules['__main__'].__file__).replace("\\", "/") first = True while True: mutex = win32event.CreateMutex(None, False, main_path + "_{&lt;paste YOUR GUID HERE&gt;}") if win32api.GetLastError() == 0: break win32api.CloseHandle(mutex) if first: print "Another instance of %s running, please wait for completion" % main_path first = False time.sleep(1) </code></pre> <h2>Explanation</h2> <p>The code attempts to create a mutex with name derived from the full path to the script. We use forward-slashes to avoid potential confusion with the real file system.</p> <h2>Advantages</h2> <ul> <li>No configuration or 'magic' identifiers needed, use it in as many different scripts as needed.</li> <li>No stale files left around, the mutex dies with you.</li> <li>Prints a helpful message when waiting</li> </ul>
0
2016-09-23T16:04:05Z
[ "python", "locking" ]
Psyco x64?
381,479
<p>Is there a way to get the same sort of speedup on x64 architecture as you can get from psyco on 32 bit processors?</p>
3
2008-12-19T16:40:38Z
381,618
<p>No, unfortunately, Psyco <a href="http://psyco.sourceforge.net/introduction.html" rel="nofollow">only runs on 32-bit x86 right now</a>.</p>
5
2008-12-19T17:28:33Z
[ "python", "psyco" ]
Comparing massive lists of dictionaries in python
382,466
<p>I never actually thought I'd run into speed-issues with python, but I have. I'm trying to compare really big lists of dictionaries to each other based on the dictionary values. I compare two lists, with the first like so</p> <pre><code>biglist1=[{'transaction':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, ...] </code></pre> <p>With 'somevalue' standing for a user-generated string, int or decimal. Now, the second list is pretty similar, except the id-values are always empty, as they have not been assigned yet.</p> <pre><code>biglist2=[{'transaction':'somevalue', 'id':'', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'', 'date':'somevalue' ...}, ...] </code></pre> <p>So I want to get a list of the dictionaries in biglist2 that match the dictionaries in biglist1 for all other keys <em>except</em> id.</p> <p>I've been doing </p> <pre><code>for item in biglist2: for transaction in biglist1: if item['transaction'] == transaction['transaction']: list_transactionnamematches.append(transaction) for item in biglist2: for transaction in list_transactionnamematches: if item['date'] == transaction['date']: list_transactionnamematches.append(transaction) </code></pre> <p>... and so on, not comparing id values, until I get a final list of matches. Since the lists can be really big (around 3000+ items each), this takes quite some time for python to loop through.</p> <p>I'm guessing this isn't really how this kind of comparison should be done. Any ideas?</p>
11
2008-12-19T22:49:15Z
382,483
<p>What you want to do is to use correct data structures: </p> <ol> <li><p>Create a dictionary of mappings of tuples of other values in the first dictionary to their id.</p></li> <li><p>Create two sets of tuples of values in both dictionaries. Then use set operations to get the tuple set you want.</p></li> <li><p>Use the dictionary from the point 1 to assign ids to those tuples.</p></li> </ol>
4
2008-12-19T22:58:09Z
[ "python" ]
Comparing massive lists of dictionaries in python
382,466
<p>I never actually thought I'd run into speed-issues with python, but I have. I'm trying to compare really big lists of dictionaries to each other based on the dictionary values. I compare two lists, with the first like so</p> <pre><code>biglist1=[{'transaction':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, ...] </code></pre> <p>With 'somevalue' standing for a user-generated string, int or decimal. Now, the second list is pretty similar, except the id-values are always empty, as they have not been assigned yet.</p> <pre><code>biglist2=[{'transaction':'somevalue', 'id':'', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'', 'date':'somevalue' ...}, ...] </code></pre> <p>So I want to get a list of the dictionaries in biglist2 that match the dictionaries in biglist1 for all other keys <em>except</em> id.</p> <p>I've been doing </p> <pre><code>for item in biglist2: for transaction in biglist1: if item['transaction'] == transaction['transaction']: list_transactionnamematches.append(transaction) for item in biglist2: for transaction in list_transactionnamematches: if item['date'] == transaction['date']: list_transactionnamematches.append(transaction) </code></pre> <p>... and so on, not comparing id values, until I get a final list of matches. Since the lists can be really big (around 3000+ items each), this takes quite some time for python to loop through.</p> <p>I'm guessing this isn't really how this kind of comparison should be done. Any ideas?</p>
11
2008-12-19T22:49:15Z
382,495
<p>In O(m*n)...</p> <pre><code>for item in biglist2: for transaction in biglist1: if (item['transaction'] == transaction['transaction'] &amp;&amp; item['date'] == transaction['date'] &amp;&amp; item['foo'] == transaction['foo'] ) : list_transactionnamematches.append(transaction) </code></pre>
0
2008-12-19T23:02:50Z
[ "python" ]
Comparing massive lists of dictionaries in python
382,466
<p>I never actually thought I'd run into speed-issues with python, but I have. I'm trying to compare really big lists of dictionaries to each other based on the dictionary values. I compare two lists, with the first like so</p> <pre><code>biglist1=[{'transaction':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, ...] </code></pre> <p>With 'somevalue' standing for a user-generated string, int or decimal. Now, the second list is pretty similar, except the id-values are always empty, as they have not been assigned yet.</p> <pre><code>biglist2=[{'transaction':'somevalue', 'id':'', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'', 'date':'somevalue' ...}, ...] </code></pre> <p>So I want to get a list of the dictionaries in biglist2 that match the dictionaries in biglist1 for all other keys <em>except</em> id.</p> <p>I've been doing </p> <pre><code>for item in biglist2: for transaction in biglist1: if item['transaction'] == transaction['transaction']: list_transactionnamematches.append(transaction) for item in biglist2: for transaction in list_transactionnamematches: if item['date'] == transaction['date']: list_transactionnamematches.append(transaction) </code></pre> <p>... and so on, not comparing id values, until I get a final list of matches. Since the lists can be really big (around 3000+ items each), this takes quite some time for python to loop through.</p> <p>I'm guessing this isn't really how this kind of comparison should be done. Any ideas?</p>
11
2008-12-19T22:49:15Z
382,507
<p>Forgive my rusty python syntax, it's been a while, so consider this partially pseudocode</p> <pre><code>import operator biglist1.sort(key=(operator.itemgetter(2),operator.itemgetter(0))) biglist2.sort(key=(operator.itemgetter(2),operator.itemgetter(0))) i1=0; i2=0; while i1 &lt; len(biglist1) and i2 &lt; len(biglist2): if (biglist1[i1]['date'],biglist1[i1]['transaction']) == (biglist2[i2]['date'],biglist2[i2]['transaction']): biglist3.append(biglist1[i1]) i1++ i2++ elif (biglist1[i1]['date'],biglist1[i1]['transaction']) &lt; (biglist2[i2]['date'],biglist2[i2]['transaction']): i1++ elif (biglist1[i1]['date'],biglist1[i1]['transaction']) &gt; (biglist2[i2]['date'],biglist2[i2]['transaction']): i2++ else: print "this wont happen if i did the tuple comparison correctly" </code></pre> <p>This sorts both lists into the same order, by (date,transaction). Then it walks through them side by side, stepping through each looking for relatively adjacent matches. It assumes that (date,transaction) is unique, and that I am not completely off my rocker with regards to tuple sorting and comparison.</p>
1
2008-12-19T23:07:13Z
[ "python" ]
Comparing massive lists of dictionaries in python
382,466
<p>I never actually thought I'd run into speed-issues with python, but I have. I'm trying to compare really big lists of dictionaries to each other based on the dictionary values. I compare two lists, with the first like so</p> <pre><code>biglist1=[{'transaction':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, ...] </code></pre> <p>With 'somevalue' standing for a user-generated string, int or decimal. Now, the second list is pretty similar, except the id-values are always empty, as they have not been assigned yet.</p> <pre><code>biglist2=[{'transaction':'somevalue', 'id':'', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'', 'date':'somevalue' ...}, ...] </code></pre> <p>So I want to get a list of the dictionaries in biglist2 that match the dictionaries in biglist1 for all other keys <em>except</em> id.</p> <p>I've been doing </p> <pre><code>for item in biglist2: for transaction in biglist1: if item['transaction'] == transaction['transaction']: list_transactionnamematches.append(transaction) for item in biglist2: for transaction in list_transactionnamematches: if item['date'] == transaction['date']: list_transactionnamematches.append(transaction) </code></pre> <p>... and so on, not comparing id values, until I get a final list of matches. Since the lists can be really big (around 3000+ items each), this takes quite some time for python to loop through.</p> <p>I'm guessing this isn't really how this kind of comparison should be done. Any ideas?</p>
11
2008-12-19T22:49:15Z
382,707
<p>Index on the fields you want to use for lookup. O(n+m)</p> <pre><code>matches = [] biglist1_indexed = {} for item in biglist1: biglist1_indexed[(item["transaction"], item["date"])] = item for item in biglist2: if (item["transaction"], item["date"]) in biglist1_indexed: matches.append(item) </code></pre> <p>This is probably thousands of times faster than what you're doing now.</p>
18
2008-12-20T01:01:00Z
[ "python" ]
Comparing massive lists of dictionaries in python
382,466
<p>I never actually thought I'd run into speed-issues with python, but I have. I'm trying to compare really big lists of dictionaries to each other based on the dictionary values. I compare two lists, with the first like so</p> <pre><code>biglist1=[{'transaction':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, ...] </code></pre> <p>With 'somevalue' standing for a user-generated string, int or decimal. Now, the second list is pretty similar, except the id-values are always empty, as they have not been assigned yet.</p> <pre><code>biglist2=[{'transaction':'somevalue', 'id':'', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'', 'date':'somevalue' ...}, ...] </code></pre> <p>So I want to get a list of the dictionaries in biglist2 that match the dictionaries in biglist1 for all other keys <em>except</em> id.</p> <p>I've been doing </p> <pre><code>for item in biglist2: for transaction in biglist1: if item['transaction'] == transaction['transaction']: list_transactionnamematches.append(transaction) for item in biglist2: for transaction in list_transactionnamematches: if item['date'] == transaction['date']: list_transactionnamematches.append(transaction) </code></pre> <p>... and so on, not comparing id values, until I get a final list of matches. Since the lists can be really big (around 3000+ items each), this takes quite some time for python to loop through.</p> <p>I'm guessing this isn't really how this kind of comparison should be done. Any ideas?</p>
11
2008-12-19T22:49:15Z
382,739
<p>The approach I would probably take to this is to make a very, very lightweight class with one instance variable and one method. The instance variable is a pointer to a dictionary; the method overrides the built-in special method <code>__hash__(self)</code>, returning a value calculated from all the values in the dictionary except <code>id</code>.</p> <p>From there the solution seems fairly obvious: Create two initially empty dictionaries: <code>N</code> and <code>M</code> (for <em>no-matches</em> and <em>matches</em>.) Loop over each list exactly once, and for each of these dictionaries representing a transaction (let's call it a <code>Tx_dict</code>), create an instance of the new class (a <code>Tx_ptr</code>). Then test for an item matching this <code>Tx_ptr</code> in <code>N</code> and <code>M</code>: if there is no matching item in <code>N</code>, insert the current <code>Tx_ptr</code> into <code>N</code>; if there is a matching item in <code>N</code> but no matching item in <code>M</code>, insert the current <code>Tx_ptr</code> into <code>M</code> with the <code>Tx_ptr</code> itself as a key and a list containing the <code>Tx_ptr</code> as the value; if there is a matching item in <code>N</code> and in <code>M</code>, append the current <code>Tx_ptr</code> to the value associated with that key in <code>M</code>.</p> <p>After you've gone through every item once, your dictionary <code>M</code> will contain pointers to all the transactions which match other transactions, all neatly grouped together into lists for you.</p> <p><em>Edit</em>: Oops! Obviously, the correct action if there is a matching <code>Tx_ptr</code> in <code>N</code> but not in <code>M</code> is to insert a key-value pair into <code>M</code> with the current <code>Tx_ptr</code> as the key and as the value, a list of the current <code>Tx_ptr</code> <em>and</em> the <code>Tx_ptr</code> that was already in <code>N</code>.</p>
0
2008-12-20T01:31:19Z
[ "python" ]
Comparing massive lists of dictionaries in python
382,466
<p>I never actually thought I'd run into speed-issues with python, but I have. I'm trying to compare really big lists of dictionaries to each other based on the dictionary values. I compare two lists, with the first like so</p> <pre><code>biglist1=[{'transaction':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, ...] </code></pre> <p>With 'somevalue' standing for a user-generated string, int or decimal. Now, the second list is pretty similar, except the id-values are always empty, as they have not been assigned yet.</p> <pre><code>biglist2=[{'transaction':'somevalue', 'id':'', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'', 'date':'somevalue' ...}, ...] </code></pre> <p>So I want to get a list of the dictionaries in biglist2 that match the dictionaries in biglist1 for all other keys <em>except</em> id.</p> <p>I've been doing </p> <pre><code>for item in biglist2: for transaction in biglist1: if item['transaction'] == transaction['transaction']: list_transactionnamematches.append(transaction) for item in biglist2: for transaction in list_transactionnamematches: if item['date'] == transaction['date']: list_transactionnamematches.append(transaction) </code></pre> <p>... and so on, not comparing id values, until I get a final list of matches. Since the lists can be really big (around 3000+ items each), this takes quite some time for python to loop through.</p> <p>I'm guessing this isn't really how this kind of comparison should be done. Any ideas?</p>
11
2008-12-19T22:49:15Z
383,097
<p>Have a look at Psyco. Its a Python compiler that can create very fast, optimized machine code from your source.</p> <p><a href="http://sourceforge.net/projects/psyco/" rel="nofollow">http://sourceforge.net/projects/psyco/</a></p> <p>While this isn't a direct solution to your code's efficiency issues, it could still help speed things up without needing to write any new code. That said, I'd still highly recommend optimizing your code as much as possible AND use Psyco to squeeze as much speed out of it as possible.</p> <p>Part of their guide specifically talks about using it to speed up list, string, and numeric computation heavy functions.</p> <p><a href="http://psyco.sourceforge.net/psycoguide/node8.html" rel="nofollow">http://psyco.sourceforge.net/psycoguide/node8.html</a></p>
0
2008-12-20T08:32:02Z
[ "python" ]
Comparing massive lists of dictionaries in python
382,466
<p>I never actually thought I'd run into speed-issues with python, but I have. I'm trying to compare really big lists of dictionaries to each other based on the dictionary values. I compare two lists, with the first like so</p> <pre><code>biglist1=[{'transaction':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, ...] </code></pre> <p>With 'somevalue' standing for a user-generated string, int or decimal. Now, the second list is pretty similar, except the id-values are always empty, as they have not been assigned yet.</p> <pre><code>biglist2=[{'transaction':'somevalue', 'id':'', 'date':'somevalue' ...}, {'transactio':'somevalue', 'id':'', 'date':'somevalue' ...}, ...] </code></pre> <p>So I want to get a list of the dictionaries in biglist2 that match the dictionaries in biglist1 for all other keys <em>except</em> id.</p> <p>I've been doing </p> <pre><code>for item in biglist2: for transaction in biglist1: if item['transaction'] == transaction['transaction']: list_transactionnamematches.append(transaction) for item in biglist2: for transaction in list_transactionnamematches: if item['date'] == transaction['date']: list_transactionnamematches.append(transaction) </code></pre> <p>... and so on, not comparing id values, until I get a final list of matches. Since the lists can be really big (around 3000+ items each), this takes quite some time for python to loop through.</p> <p>I'm guessing this isn't really how this kind of comparison should be done. Any ideas?</p>
11
2008-12-19T22:49:15Z
8,356,511
<p>I'm also a newbie. My code is structured in much the same way as his. </p> <pre><code>for A in biglist: for B in biglist: if ( A.get('somekey') &lt;&gt; B.get('somekey') and #don't match to itself len( set(A.get('list')) - set(B.get('list')) ) &gt; 10: [do stuff...] </code></pre> <p>This takes hours to run through a list of 10000 dictionaries. Each dictionary contains lots of stuff but I could potentially pull out just the ids ('somekey') and lists ('list') and rewrite as a single dictionary of 10000 key:value pairs. </p> <p>Question: how much faster would that be? And I assume this is faster than using a list of lists, right?</p>
0
2011-12-02T12:44:44Z
[ "python" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
382,605
<p>Off the top of the head, it can be useful as an initial value when searching for a minimum value.</p> <p>For example:</p> <pre><code>min = float('inf') for x in somelist: if x&lt;min: min=x </code></pre> <p>Which I prefer to setting <code>min</code> initially to the first value of <code>somelist</code></p> <p>Of course, in Python, you should just use the min() built-in function in most cases. </p>
34
2008-12-19T23:55:12Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
382,618
<p>When working in a problem domain where trig is used (especially tangent) infinity is an answer that can come up. Trig ends up being used heavily in graphics applications, games, and geospatial applications, plus the obvious math applications. </p>
1
2008-12-20T00:01:33Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
382,628
<p>In some physics calculations you can normalize irregularities (ie, infinite numbers) of the same order with each other, canceling them both and allowing a approximate result to come through.</p> <p>When you deal with limits, calculations like (infinity / infinity) -> approaching a finite a number could be achieved. It's useful for the language to have the ability to overwrite the regular divide-by-zero error.</p>
11
2008-12-20T00:07:03Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
382,642
<p>I'm sure there are other ways to do this, but you could use Infinity to check for reasonable inputs in a String-to-Float conversion. In Java, at least, the Float.isNaN() static method will return false for numbers with infinite magnitude, indicating they are valid numbers, even though your program might want to classify them as invalid. Checking against the Float.POSITIVE_INFINITY and Float.NEGATIVE_INFINITY constants solves that problem. For example:</p> <pre><code>// Some sample values to test our code with String stringValues[] = { "-999999999999999999999999999999999999999999999", "12345", "999999999999999999999999999999999999999999999" }; // Loop through each string representation for (String stringValue : stringValues) { // Convert the string representation to a Float representation Float floatValue = Float.parseFloat(stringValue); System.out.println("String representation: " + stringValue); System.out.println("Result of isNaN: " + floatValue.isNaN()); // Check the result for positive infinity, negative infinity, and // "normal" float numbers (within the defined range for Float values). if (floatValue == Float.POSITIVE_INFINITY) { System.out.println("That number is too big."); } else if (floatValue == Float.NEGATIVE_INFINITY) { System.out.println("That number is too small."); } else { System.out.println("That number is jussssst right."); } } </code></pre> <p><strong>Sample Output:</strong></p> <p>String representation: -999999999999999999999999999999999999999999999<br/> Result of isNaN: false<br/> That number is too small.<br/></p> <p>String representation: 12345<br/> Result of isNaN: false<br/> That number is jussssst right.<br/></p> <p>String representation: 999999999999999999999999999999999999999999999<br/> Result of isNaN: false<br/> That number is too big.<br/></p>
1
2008-12-20T00:19:37Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
382,674
<p>Dijkstra's Algorithm typically assigns infinity as the initial edge weights in a graph. This doesn't <em>have</em> to be "infinity", just some arbitrarily constant but in java I typically use Double.Infinity. I assume ruby could be used similarly.</p>
34
2008-12-20T00:40:24Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
382,686
<p><a href="http://en.wikipedia.org/wiki/Alpha-beta_pruning">Alpha-beta pruning</a></p>
8
2008-12-20T00:46:51Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
382,690
<p>Some programmers use Infinity or <code>NaN</code>s to show a variable has never been initialized or assigned in the program.</p>
0
2008-12-20T00:51:04Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
382,735
<p>I use it when I have a Range object where one or both ends need to be open</p>
2
2008-12-20T01:28:57Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
382,736
<p>Use <code>Infinity</code> and <code>-Infinity</code> when implementing a mathematical algorithm calls for it.</p> <p>In Ruby, <code>Infinity</code> and <code>-Infinity</code> have nice comparative properties so that <code>-Infinity</code> &lt; <code>x</code> &lt; <code>Infinity</code> for any real number <code>x</code>. For example, <code>Math.log(0)</code> returns <code>-Infinity</code>, extending to <code>0</code> the property that <code>x &gt; y</code> implies that <code>Math.log(x) &gt; Math.log(y)</code>. Also, <code>Infinity * x</code> is <code>Infinity</code> if x > 0, <code>-Infinity</code> if x &lt; 0, and 'NaN' (not a number; that is, undefined) if x is 0.</p> <p>For example, I use the following bit of code in part of the calculation of some <a href="http://en.wikipedia.org/wiki/Likelihood_ratio">log likelihood ratios</a>. I explicitly reference <code>-Infinity</code> to define a value even if <code>k</code> is <code>0</code> or <code>n</code> AND <code>x</code> is <code>0</code> or <code>1</code>. </p> <pre><code>Infinity = 1.0/0.0 def Similarity.log_l(k, n, x) unless x == 0 or x == 1 k * Math.log(x.to_f) + (n-k) * Math.log(1.0-x) end -Infinity end end </code></pre>
10
2008-12-20T01:29:23Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
383,348
<p>There seems to be an implied "Why does this functionality even exist?" in your question. And the reason is that Ruby and Python are just giving access to the full range of values that one can specify in floating point form as specified by IEEE. </p> <p>This page seems to describe it well: <a href="http://steve.hollasch.net/cgindex/coding/ieeefloat.html">http://steve.hollasch.net/cgindex/coding/ieeefloat.html</a></p> <p>As a result, you can also have NaN (Not-a-number) values and -0.0, while you may not immediately have real-world uses for those either. </p>
17
2008-12-20T14:03:13Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
386,291
<p>I've used it in the <a href="http://en.wikipedia.org/wiki/Minimax" rel="nofollow">minimax algorithm</a>. When I'm generating new moves, if the min player wins on that node then the value of the node is -∞. Conversely, if the max player wins then the value of that node is +∞.</p> <p>Also, if you're generating nodes/game states and then trying out several heuristics you can set all the node values to -∞/+∞ which ever makes sense and then when you're running a heuristic its easy to set the node value:</p> <pre><code>node_val = -∞ node_val = max(heuristic1(node), node_val) node_val = max(heuristic2(node), node_val) node_val = max(heuristic2(node), node_val) </code></pre>
3
2008-12-22T13:56:57Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
398,869
<p>I've used it in a DSL similar to Rails' <code>has_one</code> and <code>has_many</code>:</p> <pre><code>has 0..1 :author has 0..INFINITY :tags </code></pre> <p>This makes it easy to express concepts like Kleene star and plus in your DSL.</p>
3
2008-12-29T22:14:52Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
399,013
<p>I use it to specify the mass and inertia of a static object in physics simulations. Static objects are essentially unaffected by gravity and other simulation forces.</p>
8
2008-12-29T23:05:55Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
419,337
<p>I've used it for cases where you want to define ranges of preferences / allowed.</p> <p>For example in 37signals apps you have like a limit to project number</p> <pre><code>Infinity = 1 / 0.0 FREE = 0..1 BASIC = 0..5 PREMIUM = 0..Infinity </code></pre> <p>then you can do checks like </p> <pre><code>if PREMIUM.include? current_user.projects.count # do something end </code></pre>
5
2009-01-07T05:57:16Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
422,343
<p>I've used symbolic values for positive and negative infinity in dealing with range comparisons to eliminate corner cases that would otherwise require special handling:</p> <p>Given two ranges A=[a,b) and C=[c,d) do they intersect, is one greater than the other, or does one contain the other?</p> <pre><code>A &gt; C iff a &gt;= d A &lt; C iff b &lt;= c etc... </code></pre> <p>If you have values for positive and negative infinity that respectively compare greater than and less than all other values, you don't need to do any special handling for open-ended ranges. Since floats and doubles already implement these values, you might as well use them instead of trying to find the largest/smallest values on your platform. With integers, it's more difficult to use "infinity" since it's not supported by hardware.</p>
2
2009-01-07T22:04:54Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
439,197
<p>It is used quite extensively in graphics. For example, any pixel in a 3D image that is not part of an actual object is marked as infinitely far away. So that it can later be replaced with a background image.</p>
1
2009-01-13T14:49:21Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
1,213,937
<p>I used it for representing camera focus distance and to my surprise in Python:</p> <pre><code>&gt;&gt;&gt; float("inf") is float("inf") False &gt;&gt;&gt; float("inf") == float("inf") True </code></pre> <p>I wonder why is that.</p>
4
2009-07-31T17:49:14Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
1,885,570
<p>In Ruby infinity can be used to implement lazy lists. Say i want N numbers starting at 200 which get successively larger by 100 units each time:</p> <pre><code>Inf = 1.0 / 0.0 (200..Inf).step(100).take(N) </code></pre> <p>More info here: <a href="http://banisterfiend.wordpress.com/2009/10/02/wtf-infinite-ranges-in-ruby/">http://banisterfiend.wordpress.com/2009/10/02/wtf-infinite-ranges-in-ruby/</a></p>
6
2009-12-11T03:08:47Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
2,632,913
<p>I ran across this because I'm looking for an "infinite" value to set for a maximum, if a given value doesn't exist, in an attempt to create a binary tree. (Because I'm selecting based on a range of values, and not just a single value, I quickly realized that even a hash won't work in my situation.)</p> <p>Since I expect all numbers involved to be positive, the minimum is easy: 0. Since I don't know what to expect for a maximum, though, I would like the upper bound to be Infinity of some sort. This way, I won't have to figure out what "maximum" I should compare things to.</p> <p>Since this is a project I'm working on at work, it's technically a "Real world problem". It may be kindof rare, but like a lot of abstractions, it's convenient when you need it!</p> <p>Also, to those who say that this (and other examples) are contrived, I would point out that <i>all</i> abstractions are somewhat contrived; that doesn't mean they are useful when you contrive them.</p>
2
2010-04-13T20:18:39Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
5,601,710
<p>I'm using a network library where you can specify the maximum number of reconnection attempts. Since I want mine to reconnect forever:</p> <p><code>my_connection = ConnectionLibrary(max_connection_attempts = float('inf'))</code></p> <p>In my opinion, it's more clear than the typical "set to -1 to retry forever" style, since it's literally saying "retry until the number of connection attempts is greater than infinity".</p>
1
2011-04-08T23:18:20Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
8,032,341
<p>You can to use:</p> <pre><code>import decimal decimal.Decimal("Infinity") </code></pre> <p>or:</p> <pre><code>from decimal import * Decimal("Infinity") </code></pre>
-2
2011-11-07T03:05:08Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
25,448,893
<h1>For sorting</h1> <p>I've seen it used as a sort value, to say "always sort these items to the bottom".</p>
-1
2014-08-22T14:04:23Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
29,044,406
<p>If you want the largest number from an input but they might use very large negatives. If I enter -13543124321.431 it still works out as the largest number since it's bigger than -inf.</p> <pre><code>enter code here initial_value = float('-inf') while True: try: x = input('gimmee a number or type the word, stop ') except KeyboardInterrupt: print("we done - by yo command") break if x == "stop": print("we done") break try: x = float(x) except ValueError: print('not a number') continue if x &gt; initial_value: initial_value = x print("The largest number is: " + str(initial_value)) </code></pre>
0
2015-03-14T01:20:30Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
In what contexts do programming languages make real use of an Infinity value?
382,603
<p>So in Ruby there is a trick to specify infinity:</p> <pre><code>1.0/0 =&gt; Infinity </code></pre> <p>I believe in Python you can do something like this</p> <pre><code>float('inf') </code></pre> <p>These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance</p> <pre><code>(0..1.0/0).include?(number) == (number &gt;= 0) # True for all values of number =&gt; true </code></pre> <p>To summarize, what I'm looking for is a real world reason to use Infinity.</p> <p><strong>EDIT</strong>: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people <em>actually</em> used it.</p>
25
2008-12-19T23:54:04Z
29,147,218
<h2>To specify a non-existent maximum</h2> <p>If you're dealing with numbers, <code>nil</code> represents an unknown quantity, and should be preferred to <code>0</code> for that case. Similarly, <code>Infinity</code> represents an unbounded quantity, and should be preferred to <code>(arbitrarily_large_number)</code> in that case.</p> <p>I think it can make the code cleaner. For example, I'm using <code>Float::INFINITY</code> <a href="https://github.com/nathanl/nokogiri_bang_finders/blob/bd0f735376f82b35ca95a4fa7fa7e371f0f2337b/lib/nokogiri_bang_finders.rb#L13" rel="nofollow">in a Ruby gem</a> for exactly that: the user can specify a maximum string length for a message, or they can specify <code>:all</code>. In that case, I represent the maximum length as <code>Float::INFINITY</code>, so that later when I check "is this message longer than the maximum length?" the answer will always be false, without needing a special case.</p>
-1
2015-03-19T14:28:04Z
[ "python", "ruby", "language-agnostic", "idioms", "infinity" ]
Is @measured a standard decorator? What library is it in?
382,624
<p>In <a href="http://abstracthack.wordpress.com/2007/09/05/multi-threaded-map-for-python/" rel="nofollow">this blog article</a> they use the construct:</p> <pre><code> @measured def some_func(): #... # Presumably outputs something like "some_func() is finished in 121.333 s" somewhere </code></pre> <p>This <code>@measured</code> directive doesn't seem to work with raw python. What is it?</p> <p>UPDATE: I see from Triptych that <code>@something</code> is valid, but is where can I find <code>@measured</code>, is it in a library somewhere, or is the author of this blog using something from his own private code base?</p>
2
2008-12-20T00:04:41Z
382,627
<p>Yes it's real. It's a function decorator. </p> <p>Function decorators in Python are functions that take a function as it's single argument, and return a new function in it's place. </p> <p><code>@classmethod</code> and <code>@staticmethod</code> are two built in function decorators.</p> <p><a href="http://www.python.org/dev/peps/pep-0318/" rel="nofollow">Read more &raquo;</a></p>
3
2008-12-20T00:05:52Z
[ "python", "decorator" ]
Is @measured a standard decorator? What library is it in?
382,624
<p>In <a href="http://abstracthack.wordpress.com/2007/09/05/multi-threaded-map-for-python/" rel="nofollow">this blog article</a> they use the construct:</p> <pre><code> @measured def some_func(): #... # Presumably outputs something like "some_func() is finished in 121.333 s" somewhere </code></pre> <p>This <code>@measured</code> directive doesn't seem to work with raw python. What is it?</p> <p>UPDATE: I see from Triptych that <code>@something</code> is valid, but is where can I find <code>@measured</code>, is it in a library somewhere, or is the author of this blog using something from his own private code base?</p>
2
2008-12-20T00:04:41Z
382,655
<p>measured is the name of a function that must be defined before that code will work.</p> <p>In general any function used as a decorator must accept a function and return a function. The function will be replaced with the result of passing it to the decorator - measured() in this case.</p>
0
2008-12-20T00:29:56Z
[ "python", "decorator" ]
Is @measured a standard decorator? What library is it in?
382,624
<p>In <a href="http://abstracthack.wordpress.com/2007/09/05/multi-threaded-map-for-python/" rel="nofollow">this blog article</a> they use the construct:</p> <pre><code> @measured def some_func(): #... # Presumably outputs something like "some_func() is finished in 121.333 s" somewhere </code></pre> <p>This <code>@measured</code> directive doesn't seem to work with raw python. What is it?</p> <p>UPDATE: I see from Triptych that <code>@something</code> is valid, but is where can I find <code>@measured</code>, is it in a library somewhere, or is the author of this blog using something from his own private code base?</p>
2
2008-12-20T00:04:41Z
382,666
<p><code>@measured</code> decorates the some_func() function, using a function or class named <code>measured</code>. The <code>@</code> is the decorator syntax, <code>measured</code> is the decorator function name.</p> <p>Decorators can be a bit hard to understand, but they are basically used to either wrap code around a function, or inject code into one.</p> <p>For example the measured function (used as a decorator) is probably implemented like this...</p> <pre><code>import time def measured(orig_function): # When you decorate a function, the decorator func is called # with the original function as the first argument. # You return a new, modified function. This returned function # is what the to-be-decorated function becomes. print "INFO: This from the decorator function" print "INFO: I am about to decorate %s" % (orig_function) # This is what some_func will become: def newfunc(*args, **kwargs): print "INFO: This is the decorated function being called" start = time.time() # Execute the old function, passing arguments orig_func_return = orig_function(*args, **kwargs) end = time.time() print "Function took %s seconds to execute" % (end - start) return orig_func_return # return the output of the original function # Return the modified function, which.. return newfunc @measured def some_func(arg1): print "This is my original function! Argument was %s" % arg1 # We call the now decorated function.. some_func(123) #.. and we should get (minus the INFO messages): This is my original function! Argument was 123 # Function took 7.86781311035e-06 to execute </code></pre> <p>The decorator syntax is just a shorter and neater way of doing the following:</p> <pre><code>def some_func(): print "This is my original function!" some_func = measured(some_func) </code></pre> <p>There are some decorators included with Python, for example <a href="http://docs.python.org/library/functions.html#staticmethod" rel="nofollow"><code>staticmethod</code></a> - but <code>measured</code> is not one of them:</p> <pre><code>&gt;&gt;&gt; type(measured) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'measured' is not defined </code></pre> <p>Check the projects <code>import</code> statements to see where the function or class is coming from. If it uses <code>from blah import *</code> you'll need to check all of those files (which is why <code>import *</code> is discouraged), or you could just do something like <code>grep -R def measured *</code></p>
13
2008-12-20T00:37:25Z
[ "python", "decorator" ]
Using Python's ctypes to pass/read a parameter declared as "struct_name *** param_name"?
383,010
<p>I am trying to use Python's ctypes library to access some methods in the scanning library <a href="http://www.sane-project.org/" rel="nofollow">SANE</a>. This is my first experience with ctypes and the first time I have had to deal with C datatypes in over a year so there is a fair learning curve here, but I think even without that this particular declaration would be troublesome:</p> <pre><code>extern SANE_Status sane_get_devices (const SANE_Device *** device_list, SANE_Bool local_only); </code></pre> <p>First of all, I've successfully dealt with <code>SANE_Status</code> (an enum) and <code>SANE_Bool</code> (a typedef to <code>c_int</code>). Those were both simple. That first parameter, on the other hand, is causing me all sorts of grief. I'm unfamiliar with the "<code>***</code>" notation to begin with and my tracer bullets so far have yielded nothing more than garbage data. How do I format the input to this function such that I can read back a list of my Python structure-objects? For reference, the C structure being referenced is:</p> <pre><code>typedef struct { SANE_String_Const name; /* unique device name */ SANE_String_Const vendor; /* device vendor string */ SANE_String_Const model; /* device model name */ SANE_String_Const type; /* device type (e.g., "flatbed scanner") */ } SANE_Device; </code></pre> <p>Where <code>SANE_String_Const</code> is defined as a <code>c_char_p</code>.</p> <p>My Python/ctypes version of this object is:</p> <pre><code>class SANE_Device(Structure): _fields_ = [ ("name", c_char_p), ("vendor", c_char_p), ("model", c_char_p), ("type", c_char_p)] </code></pre> <p>Suggestions on what I should pass in such that I can get the expected behavior (a list of structure-objects) out of this? All responses appreciated.</p> <p><strong>Update 1:</strong></p> <p>Using the following, I was able to retrieve a correct SANE_Device Python structure:</p> <pre><code>devices = pointer(pointer(pointer(SANE_Device()))) status = libsane.sane_get_devices(devices, c_int(0)) print status, devices, devices.contents.contents.contents.name </code></pre> <p>However, 1) yuck and 2) that seems like it would only work if there is a single result. I can't len() on <code>devices.contents.contents</code> or <code>devices.contents.contents.contents</code>. How am I to determine the number of results? The SANE docs specify that "If the function executes successfully, it stores a pointer to a NULL terminated array of pointers to SANE_Device structures in *device_list". Suggestions?</p> <p><strong>Update 2:</strong></p> <p>I was able to pass an ten-item array and then access the first element using:</p> <pre><code>devices = pointer(pointer(pointer((SANE_Device * 10)()))) status = libsane.sane_get_devices(devices, c_int(0)) print status, devices, devices.contents.contents.contents[0].name </code></pre> <p>However, ten is obviously an arbitrary number and I have no way of determining the actual number of results. Trying to access <code>devices.contents.contents.contents[1].name</code> when only one device is connected causes a segmentation fault. There must be a proper way of dealing with variable-length constructs like these in ctypes.</p>
1
2008-12-20T06:26:39Z
383,074
<p>A <code>const SANE_Device ***</code> is a three-level pointer: it's a pointer to a pointer to a pointer to a constant SANE_Device. You can use the program <a href="http://gd.tuwien.ac.at/linuxcommand.org/man_pages/cdecl1.html">cdecl</a> to decipher complicated C/C++ type definitions.</p> <p>According to the <a href="http://www.sane-project.org/html/doc012.html">SANE documentation</a>, <code>SANE_get_devices()</code> will store a pointer to a NULL-terminated list of pointers to SANE devices if successful. Thus, the proper way to call it is to declare a variable of type <code>const SANE_Device **</code> (i.e. a pointer to a pointer to a constant `SANE_Device), and pass in the address of that pointer:</p> <pre><code>const SANE_Device **device_list; SANE_get_devices(&amp;device_list, local_only); // check return value // Now, device_list[0] points to the first device, // device_list[1] points to the second device, etc. // Once you hit a NULL pointer, that's the end of the list: int num_devices = 0; while(device_list[num_devices] != NULL) num_devices++; // num_devices now stores the total number of devices </code></pre> <p>Now, this is how you would call it from C code. I've skimmed the documentation on ctypes, and it appears that you want to use the <code>byref</code> function to pass the argument by reference, and that the value you pass should be a POINTER to a POINTER to a SANE_Device. Note the distinction between <code>pointer</code> and <code>POINTER</code>: the former creates a pointer to an <em>instance</em>, whereas the latter creates a pointer to a <em>type</em>. Thus, I'm guessing the following code will work:</p> <pre><code>// SANE_Device declared as you had it devices = POINTER(POINTER(SANE_Device))() // devices is a NULL pointer to a pointer to a SANE_Device status = libsane.sane_get_devices(byref(devices), c_int(0)) if status != successful: // replace this by whatever success is print error else: num_devices = 0 // Convert NULL-terminated C list into Python list device_list = [] while devices[num_devices]: device_list.append(devices[num_devices].contents) // use .contents here since each entry in the C list is itself a pointer num_devices += 1 print device_list </code></pre> <p>[Edit] I've tested the above code using a very simple placeholder for <code>SANE_get_devices</code>, and it works.</p>
7
2008-12-20T07:49:30Z
[ "python", "pointers", "ctypes", "structure", "sane" ]
Django: How can I use my model classes to interact with my database from outside Django?
383,073
<p>I'd like to write a script that interacts with my DB using a Django app's model. However, I would like to be able to run this script from the command line or via cron. What all do I need to import to allow this?</p>
13
2008-12-20T07:48:15Z
383,089
<p>You need to set up the Django environment variables. These tell Python where your project is, and what the name of the settings module is (the project name in the settings module is optional):</p> <pre><code>import os os.environ['PYTHONPATH'] = '/path/to/myproject' os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' </code></pre> <p>Now you should be able to access the models:</p> <pre><code>from myproject.models import MyModel all_my_models = MyModel.objects.all() </code></pre>
15
2008-12-20T08:18:44Z
[ "python", "django", "django-models" ]
Django: How can I use my model classes to interact with my database from outside Django?
383,073
<p>I'd like to write a script that interacts with my DB using a Django app's model. However, I would like to be able to run this script from the command line or via cron. What all do I need to import to allow this?</p>
13
2008-12-20T07:48:15Z
383,102
<p>Depending on your specific needs, <a href="http://code.google.com/p/django-command-extensions/wiki/CommandExtensions">django-command-extensions</a> might save you a bit of time. To run any script as-is without messing around with environment variables just type:</p> <pre><code>./manage.py runscript path/to/my/script.py </code></pre> <p>django-command-extensions also has commands for automating scripts as cron jobs, which is something you mentioned that you'd like to do.</p> <p>If you are a more nuts and bolts type of person, you might check out this <a href="http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/">very detailed post</a> outlining how to make "standalone" django scripts to be run from cron jobs and whatnot.</p>
5
2008-12-20T08:39:53Z
[ "python", "django", "django-models" ]
Django: How can I use my model classes to interact with my database from outside Django?
383,073
<p>I'd like to write a script that interacts with my DB using a Django app's model. However, I would like to be able to run this script from the command line or via cron. What all do I need to import to allow this?</p>
13
2008-12-20T07:48:15Z
383,246
<p>The preferred way should be to add a <a href="http://docs.djangoproject.com/en/dev/howto/custom-management-commands/">custom command</a> and then run it as any other <code>django-admin</code> (not to be confused with <code>django.contrib.admin</code>) command:</p> <pre><code>./manage.py mycustomcommand --customarg </code></pre> <p>Setting DJANGO_SETTINGS_MODULE should only be used when a custom command is not feasible.</p>
13
2008-12-20T12:06:39Z
[ "python", "django", "django-models" ]
JavaScript implementation that allows access to [[Call]]
383,189
<p>The ECMA standard defines a hidden, internal property <code>[[Call]]</code>, which, if implemented, mean the object is callable / is a function.</p> <p>In Python, something similar takes place, except that you can override it yourself to create your own callable objects:</p> <pre><code>&gt;&gt;&gt; class B: ... def __call__(self, x,y): print x,y ... &gt;&gt;&gt; inst = B() &gt;&gt;&gt; inst(1,2) 1, 2 </code></pre> <p>Is there any similar mechanism available in standard JavaScript? If not, what about any of the current JavaScript implementations? </p>
2
2008-12-20T10:47:09Z
383,199
<p>As far as I know it's not possible. It is supposed to be an internal property of an object and not exposed to the script itself. The only way I know is to define a function.</p> <p>However, since functions is first class citizens you can add properties to them:</p> <pre><code>function myfunc(){ var myself = arguments.callee; myself.anotherfunc(); } myfunc.avalue=5; myfunc.anotherfunc=function(){ alert(this.avalue); } myfunc(); //Alerts 5 myfunc.anotherfunc(); //Alerts 5 </code></pre>
2
2008-12-20T11:04:11Z
[ "javascript", "python", "function" ]
JavaScript implementation that allows access to [[Call]]
383,189
<p>The ECMA standard defines a hidden, internal property <code>[[Call]]</code>, which, if implemented, mean the object is callable / is a function.</p> <p>In Python, something similar takes place, except that you can override it yourself to create your own callable objects:</p> <pre><code>&gt;&gt;&gt; class B: ... def __call__(self, x,y): print x,y ... &gt;&gt;&gt; inst = B() &gt;&gt;&gt; inst(1,2) 1, 2 </code></pre> <p>Is there any similar mechanism available in standard JavaScript? If not, what about any of the current JavaScript implementations? </p>
2
2008-12-20T10:47:09Z
383,465
<p>It is not possible yet: [[Call]] is hidden and not directly available in all conformat implementations. It may change in the <a href="http://wiki.ecmascript.org/doku.php?id=es3.1:es3.1_proposal_working_draft" rel="nofollow">new standard of ECMAScript</a>.</p>
0
2008-12-20T16:41:53Z
[ "javascript", "python", "function" ]
JavaScript implementation that allows access to [[Call]]
383,189
<p>The ECMA standard defines a hidden, internal property <code>[[Call]]</code>, which, if implemented, mean the object is callable / is a function.</p> <p>In Python, something similar takes place, except that you can override it yourself to create your own callable objects:</p> <pre><code>&gt;&gt;&gt; class B: ... def __call__(self, x,y): print x,y ... &gt;&gt;&gt; inst = B() &gt;&gt;&gt; inst(1,2) 1, 2 </code></pre> <p>Is there any similar mechanism available in standard JavaScript? If not, what about any of the current JavaScript implementations? </p>
2
2008-12-20T10:47:09Z
384,249
<p>[[Call]] is an internal property used to describe a particular piece of functionality in the language specification. There's no guarantee that such a property is even available in an interpreter. There are many other properties and objects that are referenced in the spec, such as the Completion object, which is only necessary if you have implemented the language as an AST interpreter which is what KJS and JavaScriptCore (JSC == WebKit fork of KJS) used to do. Non-AST based interpreters (SpiderMonkey, the new KJS and JavaScriptCore execution engines FrostByte and SquirrelFish, probably the Opera JS engine, and V8) have no need a lot of these constructs as they are used primarily for the purpose of describing behaviour -- not implementation.</p> <p>There is another reason that such access isn't available -- A lot of these properties are so intrinsic to the interpreter that allowing custom behaviour can impact performance whether those features are used or not -- for instance the JSC API provides a mechanism for an embedder to override a number of these properties, and supporting that even at the C level actually has a <em>measurable</em> performance impact.</p> <p>[Edit: minor note, when i say "intrepreter" i mean in the general sense -- it could be interpreting an AST, bytecode, or machine code (eg. jit)]</p>
1
2008-12-21T08:20:23Z
[ "javascript", "python", "function" ]
JavaScript implementation that allows access to [[Call]]
383,189
<p>The ECMA standard defines a hidden, internal property <code>[[Call]]</code>, which, if implemented, mean the object is callable / is a function.</p> <p>In Python, something similar takes place, except that you can override it yourself to create your own callable objects:</p> <pre><code>&gt;&gt;&gt; class B: ... def __call__(self, x,y): print x,y ... &gt;&gt;&gt; inst = B() &gt;&gt;&gt; inst(1,2) 1, 2 </code></pre> <p>Is there any similar mechanism available in standard JavaScript? If not, what about any of the current JavaScript implementations? </p>
2
2008-12-20T10:47:09Z
996,597
<p>Applications that use the Mozilla Spidermonkey implementation of Javascript 1.5 or greater (e.g. Firefox) have access to the <a href="https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Global%5FObjects/Object/noSuchMethod" rel="nofollow"><code>__noSuchMethod__</code></a> mechanism:</p> <pre><code>c:\&gt;jsdb js&gt;x = {}; [object Object] js&gt;x.__noSuchMethod__ = function(id,args) {writeln('you just called: '+id+'()');} function (id, args) { writeln("you just called: " + id + "()"); } js&gt;x.foo() you just called: foo() js&gt;x.bar() you just called: bar() js&gt; </code></pre>
1
2009-06-15T15:00:06Z
[ "javascript", "python", "function" ]
How to iterate over a list repeating each element in Python
383,565
<p>I'm using Python to <strong>infinitely</strong> iterate over a list, repeating each element in the list a number of times. For example given the list:</p> <pre><code>l = [1, 2, 3, 4] </code></pre> <p>I would like to output each element two times and then repeat the cycle:</p> <pre><code>1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ... </code></pre> <p>I've got an idea of where to start:</p> <pre><code>def cycle(iterable): if not hasattr(cycle, 'state'): cycle.state = itertools.cycle(iterable) return cycle.next() &gt;&gt;&gt; l = [1, 2, 3, 4] &gt;&gt;&gt; cycle(l) 1 &gt;&gt;&gt; cycle(l) 2 &gt;&gt;&gt; cycle(l) 3 &gt;&gt;&gt; cycle(l) 4 &gt;&gt;&gt; cycle(l) 1 </code></pre> <p>But how would I repeat each element?</p> <p><strong>Edit</strong></p> <p>To clarify this should iterate infinitely. Also I've used repeating the element twice as the shortest example - <strong>I would really like to repeat each element n times</strong>.</p> <p><strong>Update</strong></p> <p>Will your solution lead me to what I was looking for:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; def ncycle(iterable, n): ... for item in itertools.cycle(iterable): ... for i in range(n): ... yield item &gt;&gt;&gt; a = ncycle([1,2], 2) &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 2 </code></pre> <p>Thanks for the quick answers!</p>
6
2008-12-20T18:23:52Z
383,573
<p>Solution should be something like</p> <pre><code>iterable = [1, 2, 3, 4] n = 2 while (True): for elem in iterable: for dummy in range(n): print elem # or call function, or whatever </code></pre> <p>Edit: added 'While (True)' to iterate indefinitely.</p>
1
2008-12-20T18:30:05Z
[ "python", "iterator" ]
How to iterate over a list repeating each element in Python
383,565
<p>I'm using Python to <strong>infinitely</strong> iterate over a list, repeating each element in the list a number of times. For example given the list:</p> <pre><code>l = [1, 2, 3, 4] </code></pre> <p>I would like to output each element two times and then repeat the cycle:</p> <pre><code>1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ... </code></pre> <p>I've got an idea of where to start:</p> <pre><code>def cycle(iterable): if not hasattr(cycle, 'state'): cycle.state = itertools.cycle(iterable) return cycle.next() &gt;&gt;&gt; l = [1, 2, 3, 4] &gt;&gt;&gt; cycle(l) 1 &gt;&gt;&gt; cycle(l) 2 &gt;&gt;&gt; cycle(l) 3 &gt;&gt;&gt; cycle(l) 4 &gt;&gt;&gt; cycle(l) 1 </code></pre> <p>But how would I repeat each element?</p> <p><strong>Edit</strong></p> <p>To clarify this should iterate infinitely. Also I've used repeating the element twice as the shortest example - <strong>I would really like to repeat each element n times</strong>.</p> <p><strong>Update</strong></p> <p>Will your solution lead me to what I was looking for:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; def ncycle(iterable, n): ... for item in itertools.cycle(iterable): ... for i in range(n): ... yield item &gt;&gt;&gt; a = ncycle([1,2], 2) &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 2 </code></pre> <p>Thanks for the quick answers!</p>
6
2008-12-20T18:23:52Z
383,574
<p>You could do it with a generator pretty easily:</p> <pre><code>def cycle(iterable): while True: for item in iterable: yield item yield item x=[1,2,3] c=cycle(x) print [c.next() for i in range(10)] // prints out [1,1,2,2,3,3,1,1,2,2] </code></pre>
6
2008-12-20T18:31:49Z
[ "python", "iterator" ]
How to iterate over a list repeating each element in Python
383,565
<p>I'm using Python to <strong>infinitely</strong> iterate over a list, repeating each element in the list a number of times. For example given the list:</p> <pre><code>l = [1, 2, 3, 4] </code></pre> <p>I would like to output each element two times and then repeat the cycle:</p> <pre><code>1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ... </code></pre> <p>I've got an idea of where to start:</p> <pre><code>def cycle(iterable): if not hasattr(cycle, 'state'): cycle.state = itertools.cycle(iterable) return cycle.next() &gt;&gt;&gt; l = [1, 2, 3, 4] &gt;&gt;&gt; cycle(l) 1 &gt;&gt;&gt; cycle(l) 2 &gt;&gt;&gt; cycle(l) 3 &gt;&gt;&gt; cycle(l) 4 &gt;&gt;&gt; cycle(l) 1 </code></pre> <p>But how would I repeat each element?</p> <p><strong>Edit</strong></p> <p>To clarify this should iterate infinitely. Also I've used repeating the element twice as the shortest example - <strong>I would really like to repeat each element n times</strong>.</p> <p><strong>Update</strong></p> <p>Will your solution lead me to what I was looking for:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; def ncycle(iterable, n): ... for item in itertools.cycle(iterable): ... for i in range(n): ... yield item &gt;&gt;&gt; a = ncycle([1,2], 2) &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 2 </code></pre> <p>Thanks for the quick answers!</p>
6
2008-12-20T18:23:52Z
383,578
<p>How about this:</p> <pre><code>import itertools def bicycle(iterable, repeat=1): for item in itertools.cycle(iterable): for _ in xrange(repeat): yield item c = bicycle([1,2,3,4], 2) print [c.next() for _ in xrange(10)] </code></pre> <p>EDIT: incorporated <a href="http://stackoverflow.com/users/37522/bishanty">bishanty's</a> repeat count parameter and <a href="http://stackoverflow.com/questions/383565/how-to-iterate-over-a-list-repeating-each-element-in-python#383574">Adam Rosenfield's list comprehension</a>.</p>
12
2008-12-20T18:36:27Z
[ "python", "iterator" ]
How to iterate over a list repeating each element in Python
383,565
<p>I'm using Python to <strong>infinitely</strong> iterate over a list, repeating each element in the list a number of times. For example given the list:</p> <pre><code>l = [1, 2, 3, 4] </code></pre> <p>I would like to output each element two times and then repeat the cycle:</p> <pre><code>1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ... </code></pre> <p>I've got an idea of where to start:</p> <pre><code>def cycle(iterable): if not hasattr(cycle, 'state'): cycle.state = itertools.cycle(iterable) return cycle.next() &gt;&gt;&gt; l = [1, 2, 3, 4] &gt;&gt;&gt; cycle(l) 1 &gt;&gt;&gt; cycle(l) 2 &gt;&gt;&gt; cycle(l) 3 &gt;&gt;&gt; cycle(l) 4 &gt;&gt;&gt; cycle(l) 1 </code></pre> <p>But how would I repeat each element?</p> <p><strong>Edit</strong></p> <p>To clarify this should iterate infinitely. Also I've used repeating the element twice as the shortest example - <strong>I would really like to repeat each element n times</strong>.</p> <p><strong>Update</strong></p> <p>Will your solution lead me to what I was looking for:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; def ncycle(iterable, n): ... for item in itertools.cycle(iterable): ... for i in range(n): ... yield item &gt;&gt;&gt; a = ncycle([1,2], 2) &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 2 </code></pre> <p>Thanks for the quick answers!</p>
6
2008-12-20T18:23:52Z
383,585
<pre><code>[ "%d, %d" % (i, i) for i in [1, 2, 3, 4] * 4] </code></pre> <p>The last 4 there is the number of cycles.</p>
0
2008-12-20T18:40:13Z
[ "python", "iterator" ]
How to iterate over a list repeating each element in Python
383,565
<p>I'm using Python to <strong>infinitely</strong> iterate over a list, repeating each element in the list a number of times. For example given the list:</p> <pre><code>l = [1, 2, 3, 4] </code></pre> <p>I would like to output each element two times and then repeat the cycle:</p> <pre><code>1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ... </code></pre> <p>I've got an idea of where to start:</p> <pre><code>def cycle(iterable): if not hasattr(cycle, 'state'): cycle.state = itertools.cycle(iterable) return cycle.next() &gt;&gt;&gt; l = [1, 2, 3, 4] &gt;&gt;&gt; cycle(l) 1 &gt;&gt;&gt; cycle(l) 2 &gt;&gt;&gt; cycle(l) 3 &gt;&gt;&gt; cycle(l) 4 &gt;&gt;&gt; cycle(l) 1 </code></pre> <p>But how would I repeat each element?</p> <p><strong>Edit</strong></p> <p>To clarify this should iterate infinitely. Also I've used repeating the element twice as the shortest example - <strong>I would really like to repeat each element n times</strong>.</p> <p><strong>Update</strong></p> <p>Will your solution lead me to what I was looking for:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; def ncycle(iterable, n): ... for item in itertools.cycle(iterable): ... for i in range(n): ... yield item &gt;&gt;&gt; a = ncycle([1,2], 2) &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 2 </code></pre> <p>Thanks for the quick answers!</p>
6
2008-12-20T18:23:52Z
386,685
<pre><code>import itertools as it def ncycle(iterable, n=1): if n == 1: return it.cycle(iterable) return it.cycle(it.chain(*it.izip(*([iterable]*n)))) </code></pre>
1
2008-12-22T16:32:41Z
[ "python", "iterator" ]
How to iterate over a list repeating each element in Python
383,565
<p>I'm using Python to <strong>infinitely</strong> iterate over a list, repeating each element in the list a number of times. For example given the list:</p> <pre><code>l = [1, 2, 3, 4] </code></pre> <p>I would like to output each element two times and then repeat the cycle:</p> <pre><code>1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ... </code></pre> <p>I've got an idea of where to start:</p> <pre><code>def cycle(iterable): if not hasattr(cycle, 'state'): cycle.state = itertools.cycle(iterable) return cycle.next() &gt;&gt;&gt; l = [1, 2, 3, 4] &gt;&gt;&gt; cycle(l) 1 &gt;&gt;&gt; cycle(l) 2 &gt;&gt;&gt; cycle(l) 3 &gt;&gt;&gt; cycle(l) 4 &gt;&gt;&gt; cycle(l) 1 </code></pre> <p>But how would I repeat each element?</p> <p><strong>Edit</strong></p> <p>To clarify this should iterate infinitely. Also I've used repeating the element twice as the shortest example - <strong>I would really like to repeat each element n times</strong>.</p> <p><strong>Update</strong></p> <p>Will your solution lead me to what I was looking for:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; def ncycle(iterable, n): ... for item in itertools.cycle(iterable): ... for i in range(n): ... yield item &gt;&gt;&gt; a = ncycle([1,2], 2) &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 1 &gt;&gt;&gt; a.next() 2 &gt;&gt;&gt; a.next() 2 </code></pre> <p>Thanks for the quick answers!</p>
6
2008-12-20T18:23:52Z
36,515,591
<pre><code>itertools.chain.from_iterable(itertools.repeat(item, repeat) for item in itertools.cycle(l)) </code></pre>
0
2016-04-09T10:30:56Z
[ "python", "iterator" ]
How do you apply 'or' to all values of a list in Python?
383,623
<p>How do you apply 'or' to all values of a list in Python? I'm thinking something like:</p> <pre><code>or([True, True, False]) </code></pre> <p>or if it was possible:</p> <pre><code>reduce(or, [True, True, False]) </code></pre>
14
2008-12-20T19:05:12Z
383,637
<p>You can do this:</p> <pre><code>reduce(lambda a,b: a or b, [True, True, False]) </code></pre>
2
2008-12-20T19:11:38Z
[ "python", "list", "reduce" ]
How do you apply 'or' to all values of a list in Python?
383,623
<p>How do you apply 'or' to all values of a list in Python? I'm thinking something like:</p> <pre><code>or([True, True, False]) </code></pre> <p>or if it was possible:</p> <pre><code>reduce(or, [True, True, False]) </code></pre>
14
2008-12-20T19:05:12Z
383,638
<p>reduce should do it for you, shouldn't it?</p> <pre><code>&gt;&gt;&gt; def _or(x, y): ... return x or y ... &gt;&gt;&gt; reduce(_or, [True, True, False]) True </code></pre>
1
2008-12-20T19:12:26Z
[ "python", "list", "reduce" ]
How do you apply 'or' to all values of a list in Python?
383,623
<p>How do you apply 'or' to all values of a list in Python? I'm thinking something like:</p> <pre><code>or([True, True, False]) </code></pre> <p>or if it was possible:</p> <pre><code>reduce(or, [True, True, False]) </code></pre>
14
2008-12-20T19:05:12Z
383,642
<p>The built-in function <code>any</code> does what you want:</p> <pre><code>&gt;&gt;&gt; any([True, True, False]) True &gt;&gt;&gt; any([False, False, False]) False &gt;&gt;&gt; any([False, False, True]) True </code></pre> <p><code>any</code> has the advantage over <code>reduce</code> of shortcutting the test for later items in the sequence once it finds a true value. This can be very handy if the sequence is a generator with an expensive operation behind it. For example:</p> <pre><code>&gt;&gt;&gt; def iam(result): ... # Pretend this is expensive. ... print "iam(%r)" % result ... return result ... &gt;&gt;&gt; any((iam(x) for x in [False, True, False])) iam(False) iam(True) True &gt;&gt;&gt; reduce(lambda x,y: x or y, (iam(x) for x in [False, True, False])) iam(False) iam(True) iam(False) True </code></pre> <p>If your Python's version doesn't have <code>any()</code>, <code>all()</code> builtins then they are easily implemented as <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=98196">Guido van Rossum suggested</a>:</p> <pre><code>def any(S): for x in S: if x: return True return False def all(S): for x in S: if not x: return False return True </code></pre>
31
2008-12-20T19:16:37Z
[ "python", "list", "reduce" ]
How do you apply 'or' to all values of a list in Python?
383,623
<p>How do you apply 'or' to all values of a list in Python? I'm thinking something like:</p> <pre><code>or([True, True, False]) </code></pre> <p>or if it was possible:</p> <pre><code>reduce(or, [True, True, False]) </code></pre>
14
2008-12-20T19:05:12Z
383,643
<pre><code>&gt;&gt;&gt; all([True,False,True]) False &gt;&gt;&gt; any([True,False,True]) True </code></pre> <p>Python 2.5 and up (<a href="http://docs.python.org/library/functions.html" rel="nofollow">documentation</a>)</p>
3
2008-12-20T19:17:12Z
[ "python", "list", "reduce" ]
How do you apply 'or' to all values of a list in Python?
383,623
<p>How do you apply 'or' to all values of a list in Python? I'm thinking something like:</p> <pre><code>or([True, True, False]) </code></pre> <p>or if it was possible:</p> <pre><code>reduce(or, [True, True, False]) </code></pre>
14
2008-12-20T19:05:12Z
383,668
<p>No one has mentioned it, but "<code>or</code>" is available as a function in the operator module:</p> <pre><code>from operator import or_ </code></pre> <p>Then you can use <code>reduce</code> as above.</p> <p>Would always advise "<code>any</code>" though in more recent Pythons.</p>
7
2008-12-20T19:49:58Z
[ "python", "list", "reduce" ]
104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?
383,738
<p>We're developing a Python web service and a client web site in parallel. When we make an HTTP request from the client to the service, one call consistently raises a socket.error in socket.py, in read:</p> <pre>(104, 'Connection reset by peer')</pre> <p>When I listen in with wireshark, the "good" and "bad" responses look very similar:</p> <ul> <li>Because of the size of the OAuth header, the request is split into two packets. The service responds to both with ACK</li> <li>The service sends the response, one packet per header (HTTP/1.0 200 OK, then the Date header, etc.). The client responds to each with ACK.</li> <li>(Good request) the server sends a FIN, ACK. The client responds with a FIN, ACK. The server responds ACK.</li> <li>(Bad request) the server sends a RST, ACK, the client doesn't send a TCP response, the socket.error is raised on the client side.</li> </ul> <p>Both the web service and the client are running on a Gentoo Linux x86-64 box running glibc-2.6.1. We're using Python 2.5.2 inside the same virtual_env.</p> <p>The client is a Django 1.0.2 app that is calling httplib2 0.4.0 to make requests. We're signing requests with the OAuth signing algorithm, with the OAuth token always set to an empty string.</p> <p>The service is running Werkzeug 0.3.1, which is using Python's wsgiref.simple_server. I ran the WSGI app through wsgiref.validator with no issues.</p> <p>It seems like this should be easy to debug, but when I trace through a good request on the service side, it looks just like the bad request, in the socket._socketobject.close() function, turning delegate methods into dummy methods. When the send or sendto (can't remember which) method is switched off, the FIN or RST is sent, and the client starts processing.</p> <p>"Connection reset by peer" seems to place blame on the service, but I don't trust httplib2 either. Can the client be at fault?</p> <p>** Further debugging - Looks like server on Linux **</p> <p>I have a MacBook, so I tried running the service on one and the client website on the other. The Linux client calls the OS X server without the bug (FIN ACK). The OS X client calls the Linux service with the bug (RST ACK, and a (54, 'Connection reset by peer')). So, it looks like it's the service running on Linux. Is it x86_64? A bad glibc? wsgiref? Still looking...</p> <p>** Further testing - wsgiref looks flaky **</p> <p>We've gone to production with Apache and mod_wsgi, and the connection resets have gone away. See my answer below, but my advice is to log the connection reset and retry. This will let your server run OK in development mode, and solidly in production.</p>
20
2008-12-20T21:04:42Z
383,816
<p>I've had this problem. See <a href="http://www.itmaybeahack.com/homepage/iblog/architecture/C551260341/E20081031204203/index.html">The Python "Connection Reset By Peer" Problem</a>.</p> <p>You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.</p> <p>You can (sometimes) correct this with a <code>time.sleep(0.01)</code> placed strategically. </p> <p>"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just <em>before</em> you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.</p>
10
2008-12-20T22:18:15Z
[ "python", "sockets", "wsgi", "httplib2", "werkzeug" ]
104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?
383,738
<p>We're developing a Python web service and a client web site in parallel. When we make an HTTP request from the client to the service, one call consistently raises a socket.error in socket.py, in read:</p> <pre>(104, 'Connection reset by peer')</pre> <p>When I listen in with wireshark, the "good" and "bad" responses look very similar:</p> <ul> <li>Because of the size of the OAuth header, the request is split into two packets. The service responds to both with ACK</li> <li>The service sends the response, one packet per header (HTTP/1.0 200 OK, then the Date header, etc.). The client responds to each with ACK.</li> <li>(Good request) the server sends a FIN, ACK. The client responds with a FIN, ACK. The server responds ACK.</li> <li>(Bad request) the server sends a RST, ACK, the client doesn't send a TCP response, the socket.error is raised on the client side.</li> </ul> <p>Both the web service and the client are running on a Gentoo Linux x86-64 box running glibc-2.6.1. We're using Python 2.5.2 inside the same virtual_env.</p> <p>The client is a Django 1.0.2 app that is calling httplib2 0.4.0 to make requests. We're signing requests with the OAuth signing algorithm, with the OAuth token always set to an empty string.</p> <p>The service is running Werkzeug 0.3.1, which is using Python's wsgiref.simple_server. I ran the WSGI app through wsgiref.validator with no issues.</p> <p>It seems like this should be easy to debug, but when I trace through a good request on the service side, it looks just like the bad request, in the socket._socketobject.close() function, turning delegate methods into dummy methods. When the send or sendto (can't remember which) method is switched off, the FIN or RST is sent, and the client starts processing.</p> <p>"Connection reset by peer" seems to place blame on the service, but I don't trust httplib2 either. Can the client be at fault?</p> <p>** Further debugging - Looks like server on Linux **</p> <p>I have a MacBook, so I tried running the service on one and the client website on the other. The Linux client calls the OS X server without the bug (FIN ACK). The OS X client calls the Linux service with the bug (RST ACK, and a (54, 'Connection reset by peer')). So, it looks like it's the service running on Linux. Is it x86_64? A bad glibc? wsgiref? Still looking...</p> <p>** Further testing - wsgiref looks flaky **</p> <p>We've gone to production with Apache and mod_wsgi, and the connection resets have gone away. See my answer below, but my advice is to log the connection reset and retry. This will let your server run OK in development mode, and solidly in production.</p>
20
2008-12-20T21:04:42Z
384,415
<p>Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).</p> <p>Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?</p>
1
2008-12-21T12:44:18Z
[ "python", "sockets", "wsgi", "httplib2", "werkzeug" ]
104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?
383,738
<p>We're developing a Python web service and a client web site in parallel. When we make an HTTP request from the client to the service, one call consistently raises a socket.error in socket.py, in read:</p> <pre>(104, 'Connection reset by peer')</pre> <p>When I listen in with wireshark, the "good" and "bad" responses look very similar:</p> <ul> <li>Because of the size of the OAuth header, the request is split into two packets. The service responds to both with ACK</li> <li>The service sends the response, one packet per header (HTTP/1.0 200 OK, then the Date header, etc.). The client responds to each with ACK.</li> <li>(Good request) the server sends a FIN, ACK. The client responds with a FIN, ACK. The server responds ACK.</li> <li>(Bad request) the server sends a RST, ACK, the client doesn't send a TCP response, the socket.error is raised on the client side.</li> </ul> <p>Both the web service and the client are running on a Gentoo Linux x86-64 box running glibc-2.6.1. We're using Python 2.5.2 inside the same virtual_env.</p> <p>The client is a Django 1.0.2 app that is calling httplib2 0.4.0 to make requests. We're signing requests with the OAuth signing algorithm, with the OAuth token always set to an empty string.</p> <p>The service is running Werkzeug 0.3.1, which is using Python's wsgiref.simple_server. I ran the WSGI app through wsgiref.validator with no issues.</p> <p>It seems like this should be easy to debug, but when I trace through a good request on the service side, it looks just like the bad request, in the socket._socketobject.close() function, turning delegate methods into dummy methods. When the send or sendto (can't remember which) method is switched off, the FIN or RST is sent, and the client starts processing.</p> <p>"Connection reset by peer" seems to place blame on the service, but I don't trust httplib2 either. Can the client be at fault?</p> <p>** Further debugging - Looks like server on Linux **</p> <p>I have a MacBook, so I tried running the service on one and the client website on the other. The Linux client calls the OS X server without the bug (FIN ACK). The OS X client calls the Linux service with the bug (RST ACK, and a (54, 'Connection reset by peer')). So, it looks like it's the service running on Linux. Is it x86_64? A bad glibc? wsgiref? Still looking...</p> <p>** Further testing - wsgiref looks flaky **</p> <p>We've gone to production with Apache and mod_wsgi, and the connection resets have gone away. See my answer below, but my advice is to log the connection reset and retry. This will let your server run OK in development mode, and solidly in production.</p>
20
2008-12-20T21:04:42Z
481,952
<p>Don't use wsgiref for production. Use Apache and mod_wsgi, or something else.</p> <p>We continue to see these connection resets, sometimes frequently, with wsgiref (the backend used by the werkzeug test server, and possibly others like the Django test server). Our solution was to log the error, retry the call in a loop, and give up after ten failures. httplib2 tries twice, but we needed a few more. They seem to come in bunches as well - adding a 1 second sleep might clear the issue.</p> <p>We've never seen a connection reset when running through Apache and mod_wsgi. I don't know what they do differently, (maybe they just mask them), but they don't appear.</p> <p>When we asked the local dev community for help, someone confirmed that they see a lot of connection resets with wsgiref that go away on the production server. There's a bug there, but it is going to be hard to find it.</p>
7
2009-01-27T00:37:29Z
[ "python", "sockets", "wsgi", "httplib2", "werkzeug" ]