title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Storing multiple arrays in Python
59,648
<p>I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: www.gallup.com and www.rassmussenreports.com</p> <p>I'm using a brute force method, where the computer generates some random daily polling data and then calculates three day averages to see if the average of...
1
2008-09-12T18:09:02Z
59,762
<p>I would strongly consider using <a href="http://numpy.scipy.org" rel="nofollow">NumPy</a> to do this. You get efficient N-dimensional arrays that you can quickly and easily process.</p>
1
2008-09-12T19:01:00Z
[ "python", "arrays" ]
Storing multiple arrays in Python
59,648
<p>I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: www.gallup.com and www.rassmussenreports.com</p> <p>I'm using a brute force method, where the computer generates some random daily polling data and then calculates three day averages to see if the average of...
1
2008-09-12T18:09:02Z
59,778
<p>Would something like this work?</p> <pre><code>from random import randint mcworks = [] for n in xrange(NUM_ITERATIONS): mctest = [randint(0, 100) for i in xrange(5)] if sum(mctest[:3])/3 == mcavg[2]: mcworks.append(mctest) # mcavg is real data </code></pre> <p>In the end, you are left with a ...
2
2008-09-12T19:08:38Z
[ "python", "arrays" ]
How to retrieve an element from a set without removing it?
59,825
<p>Suppose the following:</p> <pre><code>&gt;&gt;&gt;s = set([1, 2, 3]) </code></pre> <p>How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p> <p>Quick and ...
154
2008-09-12T19:58:33Z
59,841
<p>Two options that don't require copying the whole set:</p> <pre><code>for e in s: break # e is now an element from s </code></pre> <p>Or...</p> <pre><code>e = next(iter(s)) </code></pre> <p>But in general, sets don't support indexing or slicing.</p>
197
2008-09-12T20:08:10Z
[ "python", "set" ]
How to retrieve an element from a set without removing it?
59,825
<p>Suppose the following:</p> <pre><code>&gt;&gt;&gt;s = set([1, 2, 3]) </code></pre> <p>How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p> <p>Quick and ...
154
2008-09-12T19:58:33Z
59,928
<p>Another option is to use a dictionary with values you don't care about. E.g.,</p> <pre><code> poor_man_set = {} poor_man_set[1] = None poor_man_set[2] = None poor_man_set[3] = None ... </code></pre> <p>You can treat the keys as a set except that they're just an array:</p> <pre><code> keys = poor_man_set.keys() p...
1
2008-09-12T20:52:06Z
[ "python", "set" ]
How to retrieve an element from a set without removing it?
59,825
<p>Suppose the following:</p> <pre><code>&gt;&gt;&gt;s = set([1, 2, 3]) </code></pre> <p>How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p> <p>Quick and ...
154
2008-09-12T19:58:33Z
60,027
<p>Since you want a random element, this will also work:</p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; s = set([1,2,3]) &gt;&gt;&gt; random.sample(s, 1) [2] </code></pre> <p>The documentation doesn't seem to mention performance of <code>random.sample</code>. From a really quick empirical test with a huge lis...
15
2008-09-12T21:43:27Z
[ "python", "set" ]
How to retrieve an element from a set without removing it?
59,825
<p>Suppose the following:</p> <pre><code>&gt;&gt;&gt;s = set([1, 2, 3]) </code></pre> <p>How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p> <p>Quick and ...
154
2008-09-12T19:58:33Z
60,233
<p>Least code would be:</p> <pre><code>&gt;&gt;&gt; s = set([1, 2, 3]) &gt;&gt;&gt; list(s)[0] 1 </code></pre> <p>Obviously this would create a new list which contains each member of the set, so not great if your set is very large.</p>
37
2008-09-13T01:07:38Z
[ "python", "set" ]
How to retrieve an element from a set without removing it?
59,825
<p>Suppose the following:</p> <pre><code>&gt;&gt;&gt;s = set([1, 2, 3]) </code></pre> <p>How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p> <p>Quick and ...
154
2008-09-12T19:58:33Z
61,140
<p>I use a utility function I wrote. Its name is somewhat misleading because it kind of implies it might be a random item or something like that.</p> <pre><code>def anyitem(iterable): try: return iter(iterable).next() except StopIteration: return None </code></pre>
4
2008-09-14T04:57:51Z
[ "python", "set" ]
How to retrieve an element from a set without removing it?
59,825
<p>Suppose the following:</p> <pre><code>&gt;&gt;&gt;s = set([1, 2, 3]) </code></pre> <p>How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p> <p>Quick and ...
154
2008-09-12T19:58:33Z
1,612,654
<p>To provide some timing figures behind the different approaches, consider the following code. <em>The get() is my custom addition to Python's setobject.c, being just a pop() without removing the element.</em></p> <pre><code>from timeit import * stats = ["for i in xrange(1000): iter(s).next() ", "for i in...
28
2009-10-23T10:47:49Z
[ "python", "set" ]
How to retrieve an element from a set without removing it?
59,825
<p>Suppose the following:</p> <pre><code>&gt;&gt;&gt;s = set([1, 2, 3]) </code></pre> <p>How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p> <p>Quick and ...
154
2008-09-12T19:58:33Z
34,973,737
<p>Following @wr. post, I get similar results (for Python3.5)</p> <pre><code>from timeit import * stats = ["for i in range(1000): next(iter(s))", "for i in range(1000): \n\tfor x in s: \n\t\tbreak", "for i in range(1000): s.add(s.pop())"] for stat in stats: t = Timer(stat, setup="s=set(range(10...
2
2016-01-24T08:38:38Z
[ "python", "set" ]
How to retrieve an element from a set without removing it?
59,825
<p>Suppose the following:</p> <pre><code>&gt;&gt;&gt;s = set([1, 2, 3]) </code></pre> <p>How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p> <p>Quick and ...
154
2008-09-12T19:58:33Z
40,054,478
<h2>tl;dr</h2> <p><code>for first_item in muh_set: break</code> remains the optimal approach in Python 3.x. <sup><em>Curse you, Guido.</em></sup></p> <h2>y u do this</h2> <p>Welcome to yet another set of Python 3.x timings, extrapolated from <a href="https://stackoverflow.com/users/101430/wr">wr.</a>'s excellent <a ...
1
2016-10-15T03:00:43Z
[ "python", "set" ]
Automate firefox with python?
60,152
<p>Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions?</p>
9
2008-09-12T23:28:16Z
60,218
<p>The languages of choice of Firefox is Javascript. Unless you have a specific requirement that requires Python, I would advice you to use that.</p>
0
2008-09-13T00:46:40Z
[ "python", "linux", "firefox", "ubuntu", "automation" ]
Automate firefox with python?
60,152
<p>Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions?</p>
9
2008-09-12T23:28:16Z
60,219
<p>You could try <a href="http://selenium.openqa.org/">selenium</a>.</p>
5
2008-09-13T00:48:35Z
[ "python", "linux", "firefox", "ubuntu", "automation" ]
Automate firefox with python?
60,152
<p>Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions?</p>
9
2008-09-12T23:28:16Z
60,548
<p>See if <a href="http://twill.idyll.org/" rel="nofollow">twill</a> can help you. It can be used as a command line tool or as a python library.</p>
1
2008-09-13T13:51:57Z
[ "python", "linux", "firefox", "ubuntu", "automation" ]
Automate firefox with python?
60,152
<p>Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions?</p>
9
2008-09-12T23:28:16Z
60,552
<p>Install <a href="http://hyperstruct.net/projects/mozlab" rel="nofollow">Mozlab</a> in Firefox and enable the telnet server, then open a socket.</p>
0
2008-09-13T14:06:18Z
[ "python", "linux", "firefox", "ubuntu", "automation" ]
Automate firefox with python?
60,152
<p>Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions?</p>
9
2008-09-12T23:28:16Z
60,630
<p>I use <a href="http://selenium-rc.openqa.org/python.html" rel="nofollow">Selenium RC</a>. All my tests are written in Python and are run with test suite.</p> <p>One minor thing is that You either have to start selenium manually and point Your tests to it or start selenium from test suite which requires little bit o...
2
2008-09-13T15:48:18Z
[ "python", "linux", "firefox", "ubuntu", "automation" ]
Automate firefox with python?
60,152
<p>Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions?</p>
9
2008-09-12T23:28:16Z
69,867
<p>The <a href="https://developer.mozilla.org/en/PyXPCOM" rel="nofollow">PyXPCOM extension</a> is one possibility.</p> <p>But looking at what firewatir provides, I have to 2nd the suggestion for twill. It's based on <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a>, which might also be...
3
2008-09-16T06:41:51Z
[ "python", "linux", "firefox", "ubuntu", "automation" ]
Automate firefox with python?
60,152
<p>Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions?</p>
9
2008-09-12T23:28:16Z
2,223,726
<p>Many command line tools don't have a javascript interpreter so do not support web 2.0 functionality. <a href="http://code.google.com/p/juicedpyshell" rel="nofollow">juicedpyshell</a> is based on PyXPCOMext's PyShell example. It gives you a python shell window "inside" the browser, and simplifies access to both the...
0
2010-02-08T18:01:59Z
[ "python", "linux", "firefox", "ubuntu", "automation" ]
Automate firefox with python?
60,152
<p>Been scouring the net for something like firewatir but for python. I'm trying to automate firefox on linux. Any suggestions?</p>
9
2008-09-12T23:28:16Z
7,610,441
<p>I would suggest you to use Selenium instead of Mechanize/Twill because Mechanize would fail while handling Javascript.</p>
1
2011-09-30T12:35:43Z
[ "python", "linux", "firefox", "ubuntu", "automation" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
60,211
<p>You could use a dictionary:</p> <pre><code>def f(x): return { 'a': 1, 'b': 2, }[x] </code></pre>
616
2008-09-13T00:38:24Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
60,215
<p>I've always liked doing it this way</p> <pre><code>result = { 'a': lambda x: x * 5, 'b': lambda x: x + 7, 'c': lambda x: x - 2 }[value](x) </code></pre> <p><a href="http://blog.simonwillison.net/post/57956755106/switch">From here</a></p>
156
2008-09-13T00:41:46Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
60,216
<p>If you are really just returning a predetermined, fixed value, you could create a dictionary with all possible input indexes as the keys, along with their corresponding values. Also, you might not really want a function to do this - unless you're computing the return value somehow.</p> <p>Oh, and if you feel like d...
1
2008-09-13T00:43:49Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
60,236
<p>In addition to the dictionary methods (which I really like, BTW), you can also use if-elif-else to obtain the switch/case/default functionality:</p> <pre><code>if x == 'a': # Do the thing elif x == 'b': # Do the other thing if x in 'bc': # Fall-through by not using elif, but now the default case include...
127
2008-09-13T01:10:58Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
60,243
<p>There's a pattern that I learned from Twisted Python code.</p> <pre><code>class SMTP: def lookupMethod(self, command): return getattr(self, 'do_' + command.upper(), None) def do_HELO(self, rest): return 'Howdy ' + rest def do_QUIT(self, rest): return 'Bye' SMTP().lookupMethod('H...
32
2008-09-13T01:26:26Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
64,756
<p>The switch statement is just syntactical sugar which is probably why Python doesn't have it. You can use if else statements for this functionality easily.</p> <p>Like Matthew Schinckel said, you can use if and elif and else.</p> <p>It is also a simple matter to have "fall-through" capabilities like most switch sta...
-1
2008-09-15T17:06:26Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
67,450
<p>I would just use if/elif/else statements. I think that it's good enough to replace the switch statement.</p>
2
2008-09-15T22:00:13Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
102,990
<p>expanding on the "dict as switch" idea. if you want to use a default value for your switch:</p> <pre><code>def f(x): try: return { 'a': 1, 'b': 2, }[x] except KeyError: return 'default' </code></pre>
9
2008-09-19T15:37:15Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
103,081
<p>If you'd like defaults you could use the dictionary <a href="https://docs.python.org/2/library/stdtypes.html#dict.get"><code>get(key[, default])</code></a> method:</p> <pre><code>def f(x): return { 'a': 1, 'b': 2, }.get(x, 9) # 9 is default if x not found </code></pre>
674
2008-09-19T15:45:15Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
109,245
<p>A true <code>switch/case</code> in Python is going to be more difficult than a dictionary method or <code>if/elif/else</code> methods because the simple versions do not support fall through.</p> <p>Another downfall of the <code>if/elif/else</code> method is the need for repeated comparisons. </p> <p>The C implemen...
25
2008-09-20T20:20:05Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
322,922
<pre><code>def f(x): return {'a': 1,'b': 2,}.get(x) or "Default" </code></pre>
-2
2008-11-27T04:24:36Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
323,259
<p><a href="http://www.activestate.com/ASPN/Python/Cookbook/">Python Cookbook</a> has several recipes (implementations and corresponding discussions) for switch statement. Please visit the following links:</p> <ol> <li><p><a href="http://code.activestate.com/recipes/410692/">Readable switch construction without lambda...
341
2008-11-27T08:53:01Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
956,115
<p>I have made a (relatively) flexible and re-usable solution for this. It can be found at GitHub as <a href="http://gist.github.com/raw/23036/fd1fb6f05d4c654ff136a9f2545b9f83e9273fcc/switch.py" rel="nofollow">this gist</a>. If the result of the switch function is callable, it is automatically called.</p>
4
2009-06-05T14:20:52Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
3,129,619
<p>The solutions I use: </p> <p>A combination of 2 of the solutions posted here, which is relatively easy to read and supports defaults.</p> <pre><code>result = { 'a': lambda x: x * 5, 'b': lambda x: x + 7, 'c': lambda x: x - 2 }.get(whatToUse, lambda x: x - 22)(value) </code></pre> <p>where</p> <pre><code>.g...
5
2010-06-28T01:32:33Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
3,828,986
<p>Let's say you don't want to just return a value, but want to use methods that change something on an object. Using the approach stated here would be:</p> <pre><code>result = { 'a': obj.increment(x), 'b': obj.decrement(x) }.get(value, obj.default(x)) </code></pre> <p>What happens here is that python evaluates a...
16
2010-09-30T08:31:55Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
4,367,749
<p>If you're searching extra-statement, as "switch", I built a python module that extends Python. It's called <a href="http://elp.chronocv.fr/?lng=en">ESPY</a> as "Enhanced Structure for Python" and it's available for both Python 2.x and Python 3.x.</p> <p>For example, in this case, a switch statement could be perform...
9
2010-12-06T15:08:12Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
6,606,504
<pre><code>class switch(object): value = None def __new__(class_, value): class_.value = value return True def case(*args): return any((arg == switch.value for arg in args)) </code></pre> <p>Usage:</p> <pre><code>while switch(n): if case(0): print "You typed zero." bre...
56
2011-07-07T06:09:09Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
6,606,540
<p>My favorite one is a really nice <a href="http://code.activestate.com/recipes/410692/">recipe</a>. You'll really like it. It's the closest one I've seen to actual switch case statements, especially in features.</p> <p>Here's an example:</p> <pre><code># The following example is pretty much the exact use-case of a ...
32
2011-07-07T06:12:47Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
10,272,369
<p>If you have a complicated case block you can consider using a function dictionary lookup table... </p> <p>If you haven't done this before its a good idea to step into your debugger and view exactly how the dictionary looks up each function. </p> <p>NOTE: Do <em>not</em> use "()" inside the case/dictionary lookup ...
10
2012-04-22T21:43:03Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
12,642,509
<p>Greg's solutions will not work for unhashable entries. For example when indexing <code>lists</code>.</p> <pre><code># doesn't work def give_me_array(key) return { [1, 0]: "hello" }[key] </code></pre> <p>Luckily though <code>tuples</code> are hashable.</p> <pre><code># works def give_me_array(key) re...
0
2012-09-28T15:00:11Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
13,239,503
<pre><code>def f(x): return 1 if x == 'a' else\ 2 if x in 'bcd' else\ 0 #default </code></pre> <p>Short and easy to read, has a default value and supports expressions in both conditions and return values.</p> <p>However, it is less efficient than the solution with a dictionary. For exampl...
4
2012-11-05T20:05:12Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
14,688,688
<p>Just mapping some a key to some code is not really and issue as most people have shown using the dict. The real trick is trying to emulate the whole drop through and break thing. I don't think I've ever written a case statement where I used that "feature". Here's a go at drop through. </p> <pre><code>def case(list)...
0
2013-02-04T14:21:46Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
16,964,129
<p>also use the List for store the cases ,and call corresponding function by select-</p> <pre><code>cases = ['zero()','one()','two()','three()'] def zero(): print "method for 0 called..." def one(): print "method for 1 called..." def two(): print "method for 2 called..." def three(): print "method for 3 calle...
0
2013-06-06T14:01:46Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
17,865,871
<p>Defining:</p> <pre><code>def switch1(value, options): if value in options: options[value]() </code></pre> <p>allows you to use a fairly straightforward syntax, with the cases bundled into a map:</p> <pre><code>def sample1(x): local = 'betty' switch1(x, { 'a': lambda: print("hello"), 'b': lambda:...
3
2013-07-25T18:23:33Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
19,335,626
<p>I didn't find the simple answer I was looking for anywhere on Google search. But I figured it out anyway. It's really quite simple. Decided to post it, and maybe prevent a few less scratches on someone else's head. The key is simply "in" and tuples. Here is the switch statement behavior with fall-through, including ...
7
2013-10-12T15:04:01Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
27,212,138
<p>I liked <a href="http://stackoverflow.com/a/60215/1766716">Mark Bies's answer</a>, but I am getting error. So modified it to run in a comprehensible way.</p> <pre><code>In [1]: result = { ...: 'a': lambda x: 'A', ...: 'b': lambda x: 'B', ...: 'c': lambda x: 'C' ...: }['a'](x) ----------------...
2
2014-11-30T10:12:36Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
27,746,465
<p>I found that a common switch structure:</p> <pre><code>switch ...parameter... case p1: v1; break; case p2: v2; break; default: v3; </code></pre> <p>can be expressed in Python as follows:</p> <pre><code>(lambda x: v1 if p1(x) else v2 if p2(x) else v3) </code></pre> <p>or formatted in a clearer way:</p> <pre><cod...
7
2015-01-02T18:01:25Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
30,012,053
<pre><code>class Switch: def __init__(self, value): self._val = value def __enter__(self): return self def __exit__(self, type, value, traceback): return False # Allows traceback to occur def __call__(self, cond, *mconds): return self._val in (cond,)+mconds from datetime import datetime with Switch(dat...
8
2015-05-03T09:05:43Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
30,881,320
<p>My favorite Python recipe for switch/case is:</p> <pre><code>choices = {'a': 1, 'b': 2} result = choices.get(key, 'default') </code></pre> <p>Short and simple for simple scenarios. </p> <p>Compare to 11+ lines of C code:</p> <pre><code>// C Language version of a simple 'switch/case'. switch( key ) { case 'a...
34
2015-06-17T02:25:10Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
31,995,013
<pre><code># simple case alternative some_value = 5.0 # this while loop block simulates a case block # case while True: # case 1 if some_value &gt; 5: print ('Greater than five') break # case 2 if some_value == 5: print ('Equal to five') break # else case 3 ...
2
2015-08-13T17:40:47Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
34,639,742
<p>For the sake of completeness, here are some of my attempts back in stone-age:</p> <p><a href="http://code.activestate.com/recipes/269708-some-python-style-switches/?in=user-1521341" rel="nofollow">http://code.activestate.com/recipes/269708-some-python-style-switches/?in=user-1521341</a></p> <p>I especially enjoy t...
0
2016-01-06T18:05:24Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
36,079,070
<p>I think the best way is to <strong>use the python language idioms to keep your code testable</strong>. As showed in previous answers, I use dictionaries to <strong>take advantage of python structures and language</strong> and keep the "case" code isolated in different methods. Below there is a class, but you can use...
1
2016-03-18T08:01:35Z
[ "python", "switch-statement" ]
Replacements for switch statement in Python?
60,208
<p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p> <p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions ...
788
2008-09-13T00:36:30Z
37,448,954
<p>If you don't worry losing syntax highlight inside the case suites, you can do the following:</p> <pre><code>exec { 1: """ print ('one') """, 2: """ print ('two') """, 3: """ print ('three') """, }.get(value, """ print ('None') """) </code></pre> <p>Where <code>value</code> is the value. In C, this wo...
0
2016-05-25T22:56:30Z
[ "python", "switch-statement" ]
Can distutils create empty __init__.py files?
60,352
<p>If all of my <code>__init__.py</code> files are empty, do I have to store them into version control, or is there a way to make <code>distutils</code> create empty <code>__init__.py</code> files during installation?</p>
0
2008-09-13T05:51:17Z
60,431
<p>In Python, <code>__init__.py</code> files actually have a meaning! They mean that the folder they are in is a Python module. As such, they have a real role in your code and should most probably be stored in Version Control.</p> <p>You could well imagine a folder in your source tree that is NOT a Python module, for ...
7
2008-09-13T09:19:56Z
[ "python", "version-control", "distutils" ]
Can distutils create empty __init__.py files?
60,352
<p>If all of my <code>__init__.py</code> files are empty, do I have to store them into version control, or is there a way to make <code>distutils</code> create empty <code>__init__.py</code> files during installation?</p>
0
2008-09-13T05:51:17Z
60,506
<p>Is there a reason you want to <em>avoid</em> putting empty <code>__init__.py</code> files in version control? If you do this you won't be able to <code>import</code> your packages from the source directory wihout first running distutils.</p> <p>If you really want to, I suppose you can create <code>__init__.py</code...
4
2008-09-13T12:46:50Z
[ "python", "version-control", "distutils" ]
Windows Mobile development in Python
60,446
<p>What is the best way to start developing Windows Mobile Professional applications in Python? Is there a reasonable SDK including an emulator? Is it even possible without doing excessive amount of underlaying Windows API calls for UI for instance?</p>
3
2008-09-13T09:56:04Z
60,448
<p><H2>Python CE</H2> Python port for Windows CE (Pocket PC) devices. Intended to be as close to desktop version as possible (console, current directory support, testsuite passed). </p> <p><a href="http://pythonce.sourceforge.net/"><img src="http://pythonce.sourceforge.net/images/python-logo.jpg" alt="Python CE" /></a...
9
2008-09-13T10:03:55Z
[ "python", "windows-mobile" ]
Windows Mobile development in Python
60,446
<p>What is the best way to start developing Windows Mobile Professional applications in Python? Is there a reasonable SDK including an emulator? Is it even possible without doing excessive amount of underlaying Windows API calls for UI for instance?</p>
3
2008-09-13T09:56:04Z
60,460
<p>If the IronPython and .Net Compact Framework teams work together, Visual Studio may one day support Python for Windows Mobile development out-of-the-box. Unfortunately, <a href="http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=9191" rel="nofollow">this feature request has been sitting on their issue ...
1
2008-09-13T10:29:26Z
[ "python", "windows-mobile" ]
Windows Mobile development in Python
60,446
<p>What is the best way to start developing Windows Mobile Professional applications in Python? Is there a reasonable SDK including an emulator? Is it even possible without doing excessive amount of underlaying Windows API calls for UI for instance?</p>
3
2008-09-13T09:56:04Z
60,945
<p>(I used to write customer apps for Windows Mobile.)</p> <p>Forget about python. Even if it's technically possible:</p> <ul> <li>your app will be big (you'll have to bundle the whole python runtime with your app)</li> <li>your app will use lots of memory (python is a memory hog, relative to C/C++)</li> <li>your app...
9
2008-09-13T22:30:01Z
[ "python", "windows-mobile" ]
Windows Mobile development in Python
60,446
<p>What is the best way to start developing Windows Mobile Professional applications in Python? Is there a reasonable SDK including an emulator? Is it even possible without doing excessive amount of underlaying Windows API calls for UI for instance?</p>
3
2008-09-13T09:56:04Z
1,519,440
<p>Just found this: <a href="http://ejr44.blogspot.com/2008/05/python-for-windows-mobile-cab.html" rel="nofollow">http://ejr44.blogspot.com/2008/05/python-for-windows-mobile-cab.html</a></p> <p>Looks like a complete set of .CAB files to provide Python on Windows Mobile.</p>
1
2009-10-05T11:07:39Z
[ "python", "windows-mobile" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
60,660
<p>For C++, check out <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/interprocess.html">Boost IPC</a>.<br /> You can probably create or find some bindings for the scripting languages as well. </p> <p>Otherwise if it's really important to be able to interface with scripting languages your best bet is simply to...
13
2008-09-13T16:19:10Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
60,662
<p>How about <a href="http://incubator.apache.org/thrift/">Facebook's Thrift</a>?</p> <blockquote> <p>Thrift is a software framework for scalable cross-language services development. It combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, P...
5
2008-09-13T16:21:24Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
60,668
<p>It doesn't get more simple than using pipes, which are supported on every OS I know of, and can be accessed in pretty much every language.</p> <p>Check out <a href="http://web.archive.org/web/20080919054639/http://www.utdallas.edu/~kcooper/teaching/3375/Tutorial6a/tutorial6.htm" rel="nofollow">this</a> tutorial.</p...
4
2008-09-13T16:27:20Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
60,692
<p>TCP sockets to localhost FTW.</p>
2
2008-09-13T17:03:28Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
60,702
<p>I think you'll want something based on sockets. </p> <p>If you want RPC rather than just IPC I would suggest something like XML-RPC/SOAP which runs over HTTP, and can be used from any language.</p>
5
2008-09-13T17:17:20Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
65,924
<p>In terms of speed, the best cross-platform IPC mechanism will be pipes. That assumes, however, that you want cross-platform IPC on the same machine. If you want to be able to talk to processes on remote machines, you'll want to look at using sockets instead. Luckily, if you're talking about TCP at least, sockets ...
42
2008-09-15T19:22:37Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
66,069
<p>If you're willing to try something a little different, there's the <a href="http://zeroc.com/ice.html" rel="nofollow">ICE</a> platform from <a href="http://zeroc.com" rel="nofollow">ZeroC</a>. It's open source, and is supported on pretty much every OS you can think of, as well as having language support for C++, C#,...
4
2008-09-15T19:39:28Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
67,532
<p>You might want to try <a href="http://www.msobczak.com/prog/yami/">YAMI</a> , it's very simple yet functional, portable and comes with binding to few languages</p>
7
2008-09-15T22:11:03Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
74,590
<p>Why not D-Bus? It's a very simple message passing system that runs on almost all platforms and is designed for robustness. It's supported by pretty much every scripting language at this point.</p> <p><a href="http://freedesktop.org/wiki/Software/dbus">http://freedesktop.org/wiki/Software/dbus</a></p>
8
2008-09-16T17:04:46Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
74,615
<p>Python has a pretty good IPC library: see <a href="https://docs.python.org/2/library/ipc.html" rel="nofollow"><a href="https://docs.python.org/2/library/ipc.html" rel="nofollow">https://docs.python.org/2/library/ipc.html</a></a></p>
0
2008-09-16T17:07:42Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
351,256
<p>Distributed computing is usually complex and you are well advised to use existing libraries or frameworks instead of reinventing the wheel. Previous poster have already enumerated a couple of these libraries and frameworks. Depending on your needs you can pick either a very low level (like sockets) or high level fra...
3
2008-12-08T22:55:24Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
2,136,606
<p><a href="http://www.msobczak.com/prog/yami/" rel="nofollow">YAMI - Yet Another Messaging Infrastructure</a> is a lightweight messaging and networking framework.</p>
3
2010-01-25T23:52:16Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
5,375,042
<p>You might want to check out <a href="http://www.angryredplanet.com/~hackbod/openbinder/docs/html/" rel="nofollow">openbinder</a>.</p>
0
2011-03-21T07:52:53Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
19,100,365
<p>google protobufs are a really bad idea with you want easy to maintain and debug code. its too easy for people to abuse it and use it to pollute your code. the proto files are nice, but its basically the same thing as a structure header file, and the code it generates is complete crap making you wonder if it really ...
-2
2013-09-30T17:37:19Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
25,034,401
<p>I would use TCP sockets as other have suggested.</p> <p>But to add something different, if you want a portable, easy to use, multi-language and <a href="http://zeromq.org/intro:commercial-support" rel="nofollow">LGPL</a>ed solution, I would recommend you <a href="http://zeromq.org/" rel="nofollow">ZeroMQ</a>. ZeroM...
1
2014-07-30T10:22:40Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
cross platform IPC
60,649
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p> <ul> <li><strong>cross platform</strong> (WIN32 and Linux at least)</li> <li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby python etc).</li> <li>Finally, <strong>simple to u...
53
2008-09-13T16:10:34Z
37,910,705
<p>I can suggest you to use the <a href="https://github.com/saprykin/plibsys" rel="nofollow">plibsys</a> C library. It is very simple, lightweight and cross-platform. Released under the LGPL. It provides:</p> <ul> <li>named system-wide shared memory regions (System V, POSIX and Windows implementations);</li> <li>named...
0
2016-06-19T18:54:44Z
[ "c++", "python", "linux", "cross-platform", "ipc" ]
How do I write a python HTTP server to listen on multiple ports?
60,680
<p>I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?</p> <p>What I'm doing now:</p> <pre><code>class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...] clas...
14
2008-09-13T16:42:38Z
60,753
<p>Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both <a href="http://localhost:1111/">http://localhost:111...
27
2008-09-13T18:22:06Z
[ "python", "webserver" ]
How do I write a python HTTP server to listen on multiple ports?
60,680
<p>I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?</p> <p>What I'm doing now:</p> <pre><code>class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...] clas...
14
2008-09-13T16:42:38Z
60,754
<p>Not easily. You could have two ThreadingHTTPServer instances, write your own serve_forever() function (don't worry it's not a complicated function).</p> <p>The existing function:</p> <pre><code>def serve_forever(self, poll_interval=0.5): """Handle one request at a time until shutdown. Polls for shutdown e...
4
2008-09-13T18:23:10Z
[ "python", "webserver" ]
How do I write a python HTTP server to listen on multiple ports?
60,680
<p>I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?</p> <p>What I'm doing now:</p> <pre><code>class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...] clas...
14
2008-09-13T16:42:38Z
61,322
<p>I would say that threading for something this simple is overkill. You're better off using some form of asynchronous programming.</p> <p>Here is an example using <a href="http://twistedmatrix.com/">Twisted</a>:</p> <pre><code>from twisted.internet import reactor from twisted.web import resource, server class MyRe...
6
2008-09-14T13:15:51Z
[ "python", "webserver" ]
python regex to match multi-line preprocessor macro
60,685
<p>What follows is a regular expression I have written to match multi-line pre-processor macros in C / C++ code. I'm by no means a regular expressions guru, so I'd welcome any advice on how I can make this better.</p> <p>Here's the regex:</p> <pre><code>\s*#define(.*\\\n)+[\S]+(?!\\) </code></pre> <p>It should match...
5
2008-09-13T16:53:57Z
60,723
<p>This is a simple test program I knocked up:</p> <pre><code>#!/usr/bin/env python TEST1=""" #include "Foo.h" #define bar foo\\ x #include "Bar.h" """ TEST2=""" #define bar foo #define x 1 \\ 12 \\ 2 \\\\ 3 Foobar """ TEST3=""" #define foo(x) if(x) \\ doSomething(x) """ TEST4=""" #define foo(x) if(x) ...
5
2008-09-13T17:46:14Z
[ "python", "regex" ]
python regex to match multi-line preprocessor macro
60,685
<p>What follows is a regular expression I have written to match multi-line pre-processor macros in C / C++ code. I'm by no means a regular expressions guru, so I'd welcome any advice on how I can make this better.</p> <p>Here's the regex:</p> <pre><code>\s*#define(.*\\\n)+[\S]+(?!\\) </code></pre> <p>It should match...
5
2008-09-13T16:53:57Z
60,729
<pre><code>start = r"^\s*#define\s+" continuation = r"(?:.*\\\n)+" lastline = r".*$" re_multiline_macros = re.compile(start + continuation + lastline, re.MULTILINE) </code></pre>
3
2008-09-13T17:53:30Z
[ "python", "regex" ]
Getting random row through SQLAlchemy
60,805
<p>How do I select a(or some) random row(s) from a table using SQLAlchemy? </p>
49
2008-09-13T19:58:02Z
60,811
<p>Theres a couple of ways through SQL, depending on which data base is being used.</p> <p>(I think SQLAlchemy can use all these anyways)</p> <p>mysql:</p> <pre><code>SELECT colum FROM table ORDER BY RAND() LIMIT 1 </code></pre> <p>PostgreSQL:</p> <pre><code>SELECT column FROM table ORDER BY RANDOM() LIMIT 1 </cod...
-4
2008-09-13T20:04:11Z
[ "python", "sql", "database", "sqlalchemy" ]
Getting random row through SQLAlchemy
60,805
<p>How do I select a(or some) random row(s) from a table using SQLAlchemy? </p>
49
2008-09-13T19:58:02Z
60,815
<p>This is very much a database-specific issue.</p> <p>I know that PostgreSQL and MySQL have the ability to order by a random function, so you can use this in SQLAlchemy:</p> <pre><code>from sqlalchemy.sql.expression import func, select select.order_by(func.random()) # for PostgreSQL, SQLite select.order_by(func.r...
63
2008-09-13T20:09:28Z
[ "python", "sql", "database", "sqlalchemy" ]
Getting random row through SQLAlchemy
60,805
<p>How do I select a(or some) random row(s) from a table using SQLAlchemy? </p>
49
2008-09-13T19:58:02Z
390,676
<p>If you are using the orm and the table is not big (or you have its amount of rows cached) and you want it to be database independent the really simple approach is.</p> <pre><code>import random rand = random.randrange(0, session.query(Table).count()) row = session.query(Table)[rand] </code></pre> <p>This is cheati...
20
2008-12-24T03:22:30Z
[ "python", "sql", "database", "sqlalchemy" ]
Getting random row through SQLAlchemy
60,805
<p>How do I select a(or some) random row(s) from a table using SQLAlchemy? </p>
49
2008-09-13T19:58:02Z
782,514
<p>An enhanced version of Lukasz's example, in the case you need to select multiple rows at random:</p> <pre><code>import random # you must first select all the values of the primary key field for the table. # in some particular cases you can use xrange(session.query(Table).count()) instead ids = session.query(Table....
-2
2009-04-23T16:27:26Z
[ "python", "sql", "database", "sqlalchemy" ]
Getting random row through SQLAlchemy
60,805
<p>How do I select a(or some) random row(s) from a table using SQLAlchemy? </p>
49
2008-09-13T19:58:02Z
14,906,244
<p>There is a simple way to pull a random row that IS database independent. Just use .offset() . No need to pull all rows:</p> <pre class="lang-python prettyprint-override"><code>import random query = DBSession.query(Table) rowCount = int(query.count()) randomRow = query.offset(int(rowCount*random.random())).first() <...
10
2013-02-16T02:19:56Z
[ "python", "sql", "database", "sqlalchemy" ]
Getting random row through SQLAlchemy
60,805
<p>How do I select a(or some) random row(s) from a table using SQLAlchemy? </p>
49
2008-09-13T19:58:02Z
21,242,325
<h2>this solution will select a single random row</h2> <p>This solution requires that the primary key is named id, it should be if its not already: </p> <pre><code>import random max_model_id = YourModel.query.order_by(YourModel.id.desc())[0].id random_id = random.randrange(0,max_model_id) random_row = YourModel.que...
-1
2014-01-20T19:18:12Z
[ "python", "sql", "database", "sqlalchemy" ]
Getting random row through SQLAlchemy
60,805
<p>How do I select a(or some) random row(s) from a table using SQLAlchemy? </p>
49
2008-09-13T19:58:02Z
33,583,008
<p>Here's four different variations, ordered from slowest to fastest. <code>timeit</code> results at the bottom:</p> <pre><code>from sqlalchemy.sql import func from sqlalchemy.orm import load_only def simple_random(): return random.choice(model_name.query.all()) def load_only_random(): return random.choice(m...
3
2015-11-07T12:55:09Z
[ "python", "sql", "database", "sqlalchemy" ]
How do you retrieve items from a dictionary in the order that they're inserted?
60,848
<p>Is it possible to retrieve items from a Python dictionary in the order that they were inserted?</p>
44
2008-09-13T20:38:05Z
60,852
<p>You can't do this with the base dict class -- it's ordered by hash. You could build your own dictionary that is really a list of key,value pairs or somesuch, which would be ordered.</p>
6
2008-09-13T20:39:58Z
[ "python", "dictionary" ]
How do you retrieve items from a dictionary in the order that they're inserted?
60,848
<p>Is it possible to retrieve items from a Python dictionary in the order that they were inserted?</p>
44
2008-09-13T20:38:05Z
60,862
<p>The standard python <code>dict</code> isn't able to do this.</p> <p>There is a proposal (<a href="http://www.python.org/dev/peps/pep-0372/">PEP 372</a>) to add an "ordered dictionary" (that keeps track of the order of insertion) to the <code>collections</code> module in the standard library. It includes links to <a...
44
2008-09-13T20:48:36Z
[ "python", "dictionary" ]
How do you retrieve items from a dictionary in the order that they're inserted?
60,848
<p>Is it possible to retrieve items from a Python dictionary in the order that they were inserted?</p>
44
2008-09-13T20:38:05Z
61,031
<p>The other answers are correct; it's not possible, but you could write this yourself. However, in case you're unsure how to actually implement something like this, here's a complete and working implementation that subclasses dict which I've just written and tested. (Note that the order of values passed to the constr...
16
2008-09-14T00:58:30Z
[ "python", "dictionary" ]
How do you retrieve items from a dictionary in the order that they're inserted?
60,848
<p>Is it possible to retrieve items from a Python dictionary in the order that they were inserted?</p>
44
2008-09-13T20:38:05Z
64,266
<p>if you don't need the dict functionality, and only need to return tuples in the order you've inserted them, wouldn't a queue work better?</p>
0
2008-09-15T16:07:04Z
[ "python", "dictionary" ]
How do you retrieve items from a dictionary in the order that they're inserted?
60,848
<p>Is it possible to retrieve items from a Python dictionary in the order that they were inserted?</p>
44
2008-09-13T20:38:05Z
65,326
<p>I've used StableDict before with good success.</p> <p><a href="http://pypi.python.org/pypi/StableDict/0.2" rel="nofollow">http://pypi.python.org/pypi/StableDict/0.2</a></p>
4
2008-09-15T18:15:46Z
[ "python", "dictionary" ]
How do you retrieve items from a dictionary in the order that they're inserted?
60,848
<p>Is it possible to retrieve items from a Python dictionary in the order that they were inserted?</p>
44
2008-09-13T20:38:05Z
65,991
<p>Or, just make the key a tuple with time.now() as the first field in the tuple.</p> <p>Then you can retrieve the keys with dictname.keys(), sort, and voila!</p> <p>Gerry</p>
5
2008-09-15T19:31:43Z
[ "python", "dictionary" ]
How do you retrieve items from a dictionary in the order that they're inserted?
60,848
<p>Is it possible to retrieve items from a Python dictionary in the order that they were inserted?</p>
44
2008-09-13T20:38:05Z
103,211
<p>It's not possible unless you store the keys in a separate list for referencing later.</p>
1
2008-09-19T15:56:35Z
[ "python", "dictionary" ]
How do you retrieve items from a dictionary in the order that they're inserted?
60,848
<p>Is it possible to retrieve items from a Python dictionary in the order that they were inserted?</p>
44
2008-09-13T20:38:05Z
659,817
<p>Or use any of the implementations for the <a href="http://www.python.org/dev/peps/pep-0372/" rel="nofollow">PEP-372</a> described <a href="http://www.python.org/dev/peps/pep-0372/#reference-implementation" rel="nofollow">here</a>, like the <a href="http://www.voidspace.org.uk/python/odict.html" rel="nofollow">odict ...
2
2009-03-18T19:42:29Z
[ "python", "dictionary" ]
How do you retrieve items from a dictionary in the order that they're inserted?
60,848
<p>Is it possible to retrieve items from a Python dictionary in the order that they were inserted?</p>
44
2008-09-13T20:38:05Z
24,028,185
<p>What you can do is insert the values with a key representing the order inputted, and then call <code>sorted()</code> on the items.</p> <pre><code>&gt;&gt;&gt; obj = {} &gt;&gt;&gt; obj[1] = 'Bob' &gt;&gt;&gt; obj[2] = 'Sally' &gt;&gt;&gt; obj[3] = 'Joe' &gt;&gt;&gt; for k, v in sorted(obj.items()): ... print v ...
0
2014-06-04T02:50:06Z
[ "python", "dictionary" ]
How do you retrieve items from a dictionary in the order that they're inserted?
60,848
<p>Is it possible to retrieve items from a Python dictionary in the order that they were inserted?</p>
44
2008-09-13T20:38:05Z
26,637,218
<p>Use OrderedDict(), available since version 2.7</p> <p>Just a matter of curiosity: <br /></p> <pre><code>a = {} b = OrderedDict() c = OredredDict() a['key1'] = 'value1' a['key2'] = 'value2' b['key1'] = 'value1' b['key2'] = 'value2' c['key2'] = 'value2' c['key1'] = 'value1' print a == b #True print a == c #True ...
5
2014-10-29T17:42:25Z
[ "python", "dictionary" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p...
286
2008-09-14T05:41:11Z
61,168
<p>I don't believe there is an established "best practice".</p> <p>I put my tests in another directory outside of the app code. I then add the main app directory to sys.path (allowing you to import the modules from anywhere) in my test runner script (which does some other stuff as well) before running all the tests. T...
10
2008-09-14T06:46:03Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p...
286
2008-09-14T05:41:11Z
61,169
<p>A common practice is to put the tests directory in the same parent directory as your module/package. So if your module was called foo.py your directory layout would look like:</p> <pre><code>parent_dir/ foo.py tests/ </code></pre> <p>Of course there is no one way of doing it. You could also make a tests subdir...
36
2008-09-14T06:46:14Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p...
286
2008-09-14T05:41:11Z
61,518
<p>I've recently started to program in Python, so I've not really had chance to find out best practice yet. But, I've written a module that goes and finds all the tests and runs them.</p> <p>So, I have:</p> <pre> app/ appfile.py test/ appfileTest.py </pre> <p>I'll have to see how it goes as I progress to larger pr...
-1
2008-09-14T18:02:12Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p...
286
2008-09-14T05:41:11Z
61,531
<p>I use a <code>tests/</code> directory, and then import the main application modules using relative imports. So in MyApp/tests/foo.py, there might be:</p> <pre><code>from .. import foo </code></pre> <p>to import the <code>MyApp.foo</code> module.</p>
13
2008-09-14T18:18:58Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p...
286
2008-09-14T05:41:11Z
61,820
<p>In C#, I've generally separated the tests into a separate assembly.</p> <p>In Python -- so far -- I've tended to either write doctests, where the test is in the docstring of a function, or put them in the <code>if __name__ == "__main__"</code> block at the bottom of the module.</p>
1
2008-09-15T03:09:29Z
[ "python", "unit-testing", "code-organization" ]