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
What is the sqlalchemy equivalent column type for 'money' and 'OID' in Postgres?
359,409
<p>What is the sqlalchemy equivalent column type for 'money' and 'OID' column types in Postgres?</p>
1
2008-12-11T13:52:21Z
373,062
<p>This is all I could find: <a href="http://docs.sqlalchemy.org/en/rel_0_9/core/types.html" rel="nofollow">http://docs.sqlalchemy.org/en/rel_0_9/core/types.html</a></p> <p>You can make your own type if you want as well.</p>
1
2008-12-16T22:51:45Z
[ "python", "postgresql", "sqlalchemy" ]
What is the sqlalchemy equivalent column type for 'money' and 'OID' in Postgres?
359,409
<p>What is the sqlalchemy equivalent column type for 'money' and 'OID' column types in Postgres?</p>
1
2008-12-11T13:52:21Z
405,923
<p>we've never had an "OID" type specifically, though we've supported the concept of an implicit "OID" column on every table through the 0.4 series, primarily for the benefit of postgres. However since user-table defined OID columns are deprecated in Postgres, and we in fact never really used the OID feature that was present, we've removed this feature from the library.</p> <p>If a particular type is not supplied in SQLA, as an alternative to specifying a custom type, you can always use the NullType which just means SQLA doesn't know anything in particular about that type. If psycopg2 sends/receives a useful Python type for the column already, there's not really any need for a SQLA type object, save for issuing CREATE TABLE statements.</p>
2
2009-01-02T02:49:08Z
[ "python", "postgresql", "sqlalchemy" ]
What is the sqlalchemy equivalent column type for 'money' and 'OID' in Postgres?
359,409
<p>What is the sqlalchemy equivalent column type for 'money' and 'OID' column types in Postgres?</p>
1
2008-12-11T13:52:21Z
37,580,913
<p>from the argument on this <a href="https://groups.google.com/forum/#!topic/sqlalchemy/USD3cdng9-s" rel="nofollow">link</a> The final conclusion was:</p> <p>Using FLOAT for monetary amounts is an extremely bad idea because of the inexactness of storage and arithmetic .. Using MONEY is discouraged because it is too locale-sensitive NUMERIC should be used instead</p>
0
2016-06-02T00:37:12Z
[ "python", "postgresql", "sqlalchemy" ]
How can I unload a DLL using ctypes in Python?
359,498
<p>I'm using ctypes to load a DLL in Python. This works great.</p> <p>Now we'd like to be able to reload that DLL at runtime. </p> <p>The straightforward approach would seem to be: 1. Unload DLL 2. Load DLL</p> <p>Unfortunately I'm not sure what the correct way to unload the DLL is.</p> <p>_ctypes.FreeLibrary is available, but private.</p> <p>Is there some other way to unload the DLL?</p>
10
2008-12-11T14:21:06Z
359,570
<p>you should be able to do it by disposing the object</p> <pre><code>mydll = ctypes.CDLL('...') del mydll mydll = ctypes.CDLL('...') </code></pre> <p><strong>EDIT:</strong> Hop's comment is right, this unbinds the name, but garbage collection doesn't happen that quickly, in fact I even doubt it even releases the loaded library. </p> <p>Ctypes doesn't seem to provide a clean way to release resources, it does only provide a <code>_handle</code> field to the dlopen handle...</p> <p>So the only way I see, a really, <strong>really non-clean way</strong>, is to system dependently dlclose the handle, but it is very very unclean, as moreover ctypes keeps internally references to this handle. So unloading takes something of the form:</p> <pre><code>mydll = ctypes.CDLL('./mylib.so') handle = mydll._handle del mydll while isLoaded('./mylib.so'): dlclose(handle) </code></pre> <p>It's so unclean that I only checked it works using:</p> <pre><code>def isLoaded(lib): libp = os.path.abspath(lib) ret = os.system("lsof -p %d | grep %s &gt; /dev/null" % (os.getpid(), libp)) return (ret == 0) def dlclose(handle) libdl = ctypes.CDLL("libdl.so") libdl.dlclose(handle) </code></pre>
10
2008-12-11T14:41:16Z
[ "python", "dll", "ctypes" ]
How can I unload a DLL using ctypes in Python?
359,498
<p>I'm using ctypes to load a DLL in Python. This works great.</p> <p>Now we'd like to be able to reload that DLL at runtime. </p> <p>The straightforward approach would seem to be: 1. Unload DLL 2. Load DLL</p> <p>Unfortunately I'm not sure what the correct way to unload the DLL is.</p> <p>_ctypes.FreeLibrary is available, but private.</p> <p>Is there some other way to unload the DLL?</p>
10
2008-12-11T14:21:06Z
28,610,285
<p>It is helpful to be able to unload the DLL so that you can rebuild the DLL without having to restart the session if you are using iPython or similar work flow. Working in windows I have only attempted to work with the windows DLL related methods.</p> <pre><code>REBUILD = True if REBUILD: from subprocess import call call('g++ -c -DBUILDING_EXAMPLE_DLL test.cpp') call('g++ -shared -o test.dll test.o -Wl,--out-implib,test.a') import ctypes import numpy # Simplest way to load the DLL mydll = ctypes.cdll.LoadLibrary('test.dll') # Call a function in the DLL print mydll.test(10) # Unload the DLL so that it can be rebuilt libHandle = mydll._handle del mydll ctypes.windll.kernel32.FreeLibrary(libHandle) </code></pre> <p>I don't know much of the internals so I'm not really sure how clean this is. I think that deleting mydll releases the Python resources and the FreeLibrary call tells windows to free it. I had assumed that freeing with FreeLibary first would have produced problems so I saved a copy of the library handle and freed it in the order shown in the example.</p> <p>I based this method on <a href="http://stackoverflow.com/questions/13128995/ctypes-unload-dll">ctypes unload dll</a> which loaded the handle explicitly up front. The loading convention however does not work as cleanly as the simple "ctypes.cdll.LoadLibrary('test.dll')" so I opted for the method shown.</p>
2
2015-02-19T15:31:41Z
[ "python", "dll", "ctypes" ]
Comparing List of Arguments to it self?
359,903
<p>Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same.</p> <p>E.g:</p> <pre><code>a = ['foo', 'foo', 'boo'] #not valid b = ['foo', 'foo', 'foo'] #valid </code></pre> <p>Whats the best way to go about doing that?</p> <p>FYI, i don't know how many strings are going to be in the list. Also this is a super easy question, but i am just too tired to think straight.</p>
2
2008-12-11T16:14:25Z
359,945
<p>Use list.count to get the number of items in a list that match a value. If that number doesn't match the number of items, you know they aren't all the same.</p> <pre><code>if a.count( "foo" ) != len(a) </code></pre> <p>Which would look like...</p> <pre><code>if a.count( a[0] ) != len(a) </code></pre> <p>...in production code.</p>
5
2008-12-11T16:21:34Z
[ "python" ]
Comparing List of Arguments to it self?
359,903
<p>Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same.</p> <p>E.g:</p> <pre><code>a = ['foo', 'foo', 'boo'] #not valid b = ['foo', 'foo', 'foo'] #valid </code></pre> <p>Whats the best way to go about doing that?</p> <p>FYI, i don't know how many strings are going to be in the list. Also this is a super easy question, but i am just too tired to think straight.</p>
2
2008-12-11T16:14:25Z
359,949
<p>No matter what function you use you have to iterate over the entire array at least once. </p> <p>So just use a for loop and compare the first value to each subsequent value. Nothing else could be faster, and it'll be three lines. Anything that does it in less lines will probably be more computationally complex actually.</p>
1
2008-12-11T16:22:17Z
[ "python" ]
Comparing List of Arguments to it self?
359,903
<p>Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same.</p> <p>E.g:</p> <pre><code>a = ['foo', 'foo', 'boo'] #not valid b = ['foo', 'foo', 'foo'] #valid </code></pre> <p>Whats the best way to go about doing that?</p> <p>FYI, i don't know how many strings are going to be in the list. Also this is a super easy question, but i am just too tired to think straight.</p>
2
2008-12-11T16:14:25Z
359,952
<p>try (if the lists are not too long):</p> <pre><code>b == [b[0]] * len(b) #valid a == [a[0]] * len(a) #not valid </code></pre> <p>this lets you compare the list to a list of the same size that is all of the same first element</p>
0
2008-12-11T16:22:51Z
[ "python" ]
Comparing List of Arguments to it self?
359,903
<p>Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same.</p> <p>E.g:</p> <pre><code>a = ['foo', 'foo', 'boo'] #not valid b = ['foo', 'foo', 'foo'] #valid </code></pre> <p>Whats the best way to go about doing that?</p> <p>FYI, i don't know how many strings are going to be in the list. Also this is a super easy question, but i am just too tired to think straight.</p>
2
2008-12-11T16:14:25Z
359,963
<p>Try creating a set from that list:</p> <pre><code>if len(set(my_list)) != 1: return False </code></pre> <p>Sets can't have duplicate items.</p> <p>EDIT: S.Lott's suggestion is cleaner:</p> <pre><code>all_items_are_same = len(set(my_list)) == 1 </code></pre> <p>Think of it like this:</p> <pre><code># Equality returns True or False all_items_are_same = (len(set(my_list)) == 1) </code></pre>
2
2008-12-11T16:27:04Z
[ "python" ]
Comparing List of Arguments to it self?
359,903
<p>Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same.</p> <p>E.g:</p> <pre><code>a = ['foo', 'foo', 'boo'] #not valid b = ['foo', 'foo', 'foo'] #valid </code></pre> <p>Whats the best way to go about doing that?</p> <p>FYI, i don't know how many strings are going to be in the list. Also this is a super easy question, but i am just too tired to think straight.</p>
2
2008-12-11T16:14:25Z
360,069
<p>Perhaps</p> <pre><code>all(a[0] == x for x in a) </code></pre> <p>is the most readable way.</p>
5
2008-12-11T16:54:36Z
[ "python" ]
Comparing List of Arguments to it self?
359,903
<p>Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same.</p> <p>E.g:</p> <pre><code>a = ['foo', 'foo', 'boo'] #not valid b = ['foo', 'foo', 'foo'] #valid </code></pre> <p>Whats the best way to go about doing that?</p> <p>FYI, i don't know how many strings are going to be in the list. Also this is a super easy question, but i am just too tired to think straight.</p>
2
2008-12-11T16:14:25Z
360,107
<p>I think that this should be something you do with a reduce function...</p> <pre><code>&gt;&gt;&gt; a = ['foo', 'foo', 'boo'] #not valid &gt;&gt;&gt; b = ['foo', 'foo', 'foo'] #valid &gt;&gt;&gt; reduce(lambda x,y:x==y and x,a) False &gt;&gt;&gt; reduce(lambda x,y:x==y and x,b) 'foo' </code></pre> <p>I'm not sure if this has any advantages over the turning it into a set solution, though. It fails if you want to test if every value in the array is False.</p>
0
2008-12-11T17:00:51Z
[ "python" ]
Comparing List of Arguments to it self?
359,903
<p>Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same.</p> <p>E.g:</p> <pre><code>a = ['foo', 'foo', 'boo'] #not valid b = ['foo', 'foo', 'foo'] #valid </code></pre> <p>Whats the best way to go about doing that?</p> <p>FYI, i don't know how many strings are going to be in the list. Also this is a super easy question, but i am just too tired to think straight.</p>
2
2008-12-11T16:14:25Z
360,253
<p>FYI. 5000 iterations of both matching and unmatching versions of a test on different sizes of the input list.</p> <pre><code>List Size 10 0.00530 aList.count(aList[0] ) == len(aList) 0.00699 for with return False if no match found. 0.00892 aList == [aList[0]] * len(aList) 0.00974 len(set(aList)) == 1 0.02334 all(aList[0] == x for x in aList) 0.02693 reduce(lambda x,y:x==y and x,aList) List Size 100 0.01547 aList.count(aList[0] ) == len(aList) 0.01623 aList == [aList[0]] * len(aList) 0.03525 for with return False if no match found. 0.05122 len(set(aList)) == 1 0.08079 all(aList[0] == x for x in aList) 0.22797 reduce(lambda x,y:x==y and x,aList) List Size 1000 0.09198 aList == [aList[0]] * len(aList) 0.11862 aList.count(aList[0] ) == len(aList) 0.31874 for with return False if no match found. 0.36145 len(set(aList)) == 1 0.65861 all(aList[0] == x for x in aList) 2.24386 reduce(lambda x,y:x==y and x,aList) </code></pre> <p>Clear winners and losers. count rules.</p> <p>Here's the quickExit version that runs pretty quickly, but isn't a one-liner.</p> <pre><code>def quickExit( aList ): """for with return False if no match found.""" value= aList[0] for x in aList: if x != value: return False return True </code></pre>
3
2008-12-11T17:49:23Z
[ "python" ]
Split HTML after N words in python
360,036
<p>Is there any way to split a long string of HTML after N words? Obviously I could use:</p> <pre><code>' '.join(foo.split(' ')[:n]) </code></pre> <p>to get the first n words of a plain text string, but that might split in the middle of an html tag, and won't produce valid html because it won't close the tags that have been opened.</p> <p>I need to do this in a zope / plone site - if there is something as standard in those products that can do it, that would be ideal.</p> <p>For example, say I have the text:</p> <pre><code>&lt;p&gt;This is some text with a &lt;a href="http://www.example.com/" title="Example link"&gt; bit of linked text in it &lt;/a&gt;. &lt;/p&gt; </code></pre> <p>And I ask it to split after 5 words, it should return:</p> <pre><code>&lt;p&gt;This is some text with&lt;/p&gt; </code></pre> <p>7 words:</p> <pre><code>&lt;p&gt;This is some text with a &lt;a href="http://www.example.com/" title="Example link"&gt; bit &lt;/a&gt; &lt;/p&gt; </code></pre>
7
2008-12-11T16:47:38Z
360,099
<p>I've heard that <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> is very good at parsing html. It will probably be able to help you get correct html out.</p>
3
2008-12-11T16:58:58Z
[ "python", "html", "plone", "zope" ]
Split HTML after N words in python
360,036
<p>Is there any way to split a long string of HTML after N words? Obviously I could use:</p> <pre><code>' '.join(foo.split(' ')[:n]) </code></pre> <p>to get the first n words of a plain text string, but that might split in the middle of an html tag, and won't produce valid html because it won't close the tags that have been opened.</p> <p>I need to do this in a zope / plone site - if there is something as standard in those products that can do it, that would be ideal.</p> <p>For example, say I have the text:</p> <pre><code>&lt;p&gt;This is some text with a &lt;a href="http://www.example.com/" title="Example link"&gt; bit of linked text in it &lt;/a&gt;. &lt;/p&gt; </code></pre> <p>And I ask it to split after 5 words, it should return:</p> <pre><code>&lt;p&gt;This is some text with&lt;/p&gt; </code></pre> <p>7 words:</p> <pre><code>&lt;p&gt;This is some text with a &lt;a href="http://www.example.com/" title="Example link"&gt; bit &lt;/a&gt; &lt;/p&gt; </code></pre>
7
2008-12-11T16:47:38Z
360,123
<p>I was going to mention the base <a href="http://docs.python.org/library/htmlparser.html#module-HTMLParser" rel="nofollow">HTMLParser</a> that's built in Python, since I'm not sure what the end-result your trying to get to is, it may or may not get you there, you'll work with the handlers primarily</p>
0
2008-12-11T17:07:16Z
[ "python", "html", "plone", "zope" ]
Split HTML after N words in python
360,036
<p>Is there any way to split a long string of HTML after N words? Obviously I could use:</p> <pre><code>' '.join(foo.split(' ')[:n]) </code></pre> <p>to get the first n words of a plain text string, but that might split in the middle of an html tag, and won't produce valid html because it won't close the tags that have been opened.</p> <p>I need to do this in a zope / plone site - if there is something as standard in those products that can do it, that would be ideal.</p> <p>For example, say I have the text:</p> <pre><code>&lt;p&gt;This is some text with a &lt;a href="http://www.example.com/" title="Example link"&gt; bit of linked text in it &lt;/a&gt;. &lt;/p&gt; </code></pre> <p>And I ask it to split after 5 words, it should return:</p> <pre><code>&lt;p&gt;This is some text with&lt;/p&gt; </code></pre> <p>7 words:</p> <pre><code>&lt;p&gt;This is some text with a &lt;a href="http://www.example.com/" title="Example link"&gt; bit &lt;/a&gt; &lt;/p&gt; </code></pre>
7
2008-12-11T16:47:38Z
360,300
<p>Take a look at the <a href="http://code.djangoproject.com/browser/django/trunk/django/utils/text.py">truncate_html_words</a> function in django.utils.text. Even if you aren't using Django, the code there does exactly what you want.</p>
6
2008-12-11T18:03:44Z
[ "python", "html", "plone", "zope" ]
Split HTML after N words in python
360,036
<p>Is there any way to split a long string of HTML after N words? Obviously I could use:</p> <pre><code>' '.join(foo.split(' ')[:n]) </code></pre> <p>to get the first n words of a plain text string, but that might split in the middle of an html tag, and won't produce valid html because it won't close the tags that have been opened.</p> <p>I need to do this in a zope / plone site - if there is something as standard in those products that can do it, that would be ideal.</p> <p>For example, say I have the text:</p> <pre><code>&lt;p&gt;This is some text with a &lt;a href="http://www.example.com/" title="Example link"&gt; bit of linked text in it &lt;/a&gt;. &lt;/p&gt; </code></pre> <p>And I ask it to split after 5 words, it should return:</p> <pre><code>&lt;p&gt;This is some text with&lt;/p&gt; </code></pre> <p>7 words:</p> <pre><code>&lt;p&gt;This is some text with a &lt;a href="http://www.example.com/" title="Example link"&gt; bit &lt;/a&gt; &lt;/p&gt; </code></pre>
7
2008-12-11T16:47:38Z
360,356
<p>You can use a mix of regex, BeautifulSoup or Tidy (I prefer BeautifulSoup). The idea is simple - strip all the HTML tags first. Find the nth word (n=7 here), find the number of times the nth word appears in the string till n words - coz u are looking only for the last occurrence to be used for truncation.</p> <p>Here is a piece of code, though a bit messy but works</p> <pre><code>import re from BeautifulSoup import BeautifulSoup import tidy def remove_html_tags(data): p = re.compile(r'&lt;.*?&gt;') return p.sub('', data) input_string='&lt;p&gt;This is some text with a &lt;a href="http://www.example.com/" '\ 'title="Example link"&gt;bit of linked text in it&lt;/a&gt;&lt;/p&gt;' s=remove_html_tags(input_string).split(' ')[:7] ###required to ensure that only the last occurrence of the nth word is # taken into account for truncating. # coz if the nth word could be 'a'/'and'/'is'....etc # which may occur multiple times within n words temp=input_string k=s.count(s[-1]) i=1 j=0 while i&lt;=k: j+=temp.find(s[-1]) temp=temp[j+len(s[-1]):] i+=1 #### output_string=input_string[:j+len(s[-1])] print "\nBeautifulSoup\n", BeautifulSoup(output_string) print "\nTidy\n", tidy.parseString(output_string) </code></pre> <p>The output is what u want</p> <pre><code>BeautifulSoup &lt;p&gt;This is some text with a &lt;a href="http://www.example.com/" title="Example link"&gt;bit&lt;/a&gt;&lt;/p&gt; Tidy &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"&gt; &lt;html&gt; &lt;head&gt; &lt;meta name="generator" content= "HTML Tidy for Linux/x86 (vers 6 November 2007), see www.w3.org"&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;This is some text with a &lt;a href="http://www.example.com/" title="Example link"&gt;bit&lt;/a&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Hope this helps</p> <p><strong>Edit:</strong> A better regex </p> <pre><code>`p = re.compile(r'&lt;[^&lt;]*?&gt;')` </code></pre>
0
2008-12-11T18:24:11Z
[ "python", "html", "plone", "zope" ]
Lambda function for classes in python?
360,368
<p>There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that I'd like to be able to dynamically create versions of the class, to pass to the library, but I can't figure out how to do it since the library expects an uninstantiated version. The code below describes the problem:</p> <pre><code>class Double: def run(self,x): return x*2 class Triple: def run(self,x): return x*3 class Multiply: def __init__(self,mult): self.mult = mult def run(self,x): return x*self.mult class Library: def __init__(self,c): self.c = c() def Op(self,val): return self.c.run(val) op1 = Double op2 = Triple #op3 = Multiply(5) lib1 = Library(op1) lib2 = Library(op2) #lib3 = Library(op3) print lib1.Op(2) print lib2.Op(2) #print lib3.Op(2) </code></pre> <p>I can't use the generic Multiply class, because I must instantiate it first which breaks the library "AttributeError: Multiply instance has no <strong>call</strong> method". Without changing the Library class, is there a way I can do this?</p>
6
2008-12-11T18:27:21Z
360,403
<p>This is sort of cheating, but you could give your Multiply class a <code>__call__</code> method that returns itself:</p> <pre><code>class Multiply: def __init__(self,mult): self.mult = mult def __call__(self): return self def run(self,x): return x*self.mult </code></pre> <p>That way when the library calls <code>c()</code> it actually calls <code>c.__call__()</code> which returns the object you want.</p>
1
2008-12-11T18:39:04Z
[ "python", "lambda" ]
Lambda function for classes in python?
360,368
<p>There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that I'd like to be able to dynamically create versions of the class, to pass to the library, but I can't figure out how to do it since the library expects an uninstantiated version. The code below describes the problem:</p> <pre><code>class Double: def run(self,x): return x*2 class Triple: def run(self,x): return x*3 class Multiply: def __init__(self,mult): self.mult = mult def run(self,x): return x*self.mult class Library: def __init__(self,c): self.c = c() def Op(self,val): return self.c.run(val) op1 = Double op2 = Triple #op3 = Multiply(5) lib1 = Library(op1) lib2 = Library(op2) #lib3 = Library(op3) print lib1.Op(2) print lib2.Op(2) #print lib3.Op(2) </code></pre> <p>I can't use the generic Multiply class, because I must instantiate it first which breaks the library "AttributeError: Multiply instance has no <strong>call</strong> method". Without changing the Library class, is there a way I can do this?</p>
6
2008-12-11T18:27:21Z
360,415
<pre><code>def mult(x): def f(): return Multiply(x) return f op3 = mult(5) lib3 = Library(op3) print lib3.Op(2) </code></pre>
1
2008-12-11T18:42:25Z
[ "python", "lambda" ]
Lambda function for classes in python?
360,368
<p>There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that I'd like to be able to dynamically create versions of the class, to pass to the library, but I can't figure out how to do it since the library expects an uninstantiated version. The code below describes the problem:</p> <pre><code>class Double: def run(self,x): return x*2 class Triple: def run(self,x): return x*3 class Multiply: def __init__(self,mult): self.mult = mult def run(self,x): return x*self.mult class Library: def __init__(self,c): self.c = c() def Op(self,val): return self.c.run(val) op1 = Double op2 = Triple #op3 = Multiply(5) lib1 = Library(op1) lib2 = Library(op2) #lib3 = Library(op3) print lib1.Op(2) print lib2.Op(2) #print lib3.Op(2) </code></pre> <p>I can't use the generic Multiply class, because I must instantiate it first which breaks the library "AttributeError: Multiply instance has no <strong>call</strong> method". Without changing the Library class, is there a way I can do this?</p>
6
2008-12-11T18:27:21Z
360,425
<p>Does the library really specify that it wants an "uninitialized version" (i.e. a class reference)?</p> <p>It looks to me as if the library actually wants an object factory. In that case, it's acceptable to type:</p> <pre><code>lib3 = Library(lambda: Multiply(5)) </code></pre> <p>To understand how the lambda works, consider the following:</p> <pre><code>Multiply5 = lambda: Multiply(5) assert Multiply5().run(3) == Multiply(5).run(3) </code></pre>
11
2008-12-11T18:44:54Z
[ "python", "lambda" ]
Lambda function for classes in python?
360,368
<p>There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that I'd like to be able to dynamically create versions of the class, to pass to the library, but I can't figure out how to do it since the library expects an uninstantiated version. The code below describes the problem:</p> <pre><code>class Double: def run(self,x): return x*2 class Triple: def run(self,x): return x*3 class Multiply: def __init__(self,mult): self.mult = mult def run(self,x): return x*self.mult class Library: def __init__(self,c): self.c = c() def Op(self,val): return self.c.run(val) op1 = Double op2 = Triple #op3 = Multiply(5) lib1 = Library(op1) lib2 = Library(op2) #lib3 = Library(op3) print lib1.Op(2) print lib2.Op(2) #print lib3.Op(2) </code></pre> <p>I can't use the generic Multiply class, because I must instantiate it first which breaks the library "AttributeError: Multiply instance has no <strong>call</strong> method". Without changing the Library class, is there a way I can do this?</p>
6
2008-12-11T18:27:21Z
360,443
<p>If I understand your problem space correctly, you have a general interface that takes 1 argument which is called using the <code>Library</code> class. Unfortunately, rather than calling a function, <code>Library</code> assumes that the function is wrapped in a class with a <code>run</code> method.</p> <p>You can certainly create these classes programatically. Classes may be returned by methods, and thanks to the concept of closures you should be able to wrap any function in a Class that meets your needs. Something like:</p> <pre><code>def make_op(f): class MyOp(object): def run(self, x): return f(x) return MyOp op1 = make_op(lambda x: return x*2) op2 = make_op(lambda x: return x*3) def multiply_op(y): return make_op(lambda x: return x*y) op3 = multiply_op(3) lib1 = Library(op1) lib2 = Library(op2) lib3 = Library(op3) print( lib1.Op(2) ) print( lib2.Op(2) ) print( lib3.Op(2) ) </code></pre> <p>That being said, changing Library to take a function and then providing functions is probably the stronger way to do this.</p>
1
2008-12-11T18:50:19Z
[ "python", "lambda" ]
Lambda function for classes in python?
360,368
<p>There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that I'd like to be able to dynamically create versions of the class, to pass to the library, but I can't figure out how to do it since the library expects an uninstantiated version. The code below describes the problem:</p> <pre><code>class Double: def run(self,x): return x*2 class Triple: def run(self,x): return x*3 class Multiply: def __init__(self,mult): self.mult = mult def run(self,x): return x*self.mult class Library: def __init__(self,c): self.c = c() def Op(self,val): return self.c.run(val) op1 = Double op2 = Triple #op3 = Multiply(5) lib1 = Library(op1) lib2 = Library(op2) #lib3 = Library(op3) print lib1.Op(2) print lib2.Op(2) #print lib3.Op(2) </code></pre> <p>I can't use the generic Multiply class, because I must instantiate it first which breaks the library "AttributeError: Multiply instance has no <strong>call</strong> method". Without changing the Library class, is there a way I can do this?</p>
6
2008-12-11T18:27:21Z
360,456
<p>There's no need for lambda at all. lambda is just syntatic sugar to define a function and use it at the same time. Just like any lambda call can be replaced with an explicit def, we can solve your problem by creating a real class that meets your needs and returning it. </p> <pre><code>class Double: def run(self,x): return x*2 class Triple: def run(self,x): return x*3 def createMultiplier(n): class Multiply: def run(self,x): return x*n return Multiply class Library: def __init__(self,c): self.c = c() def Op(self,val): return self.c.run(val) op1 = Double op2 = Triple op3 = createMultiplier(5) lib1 = Library(op1) lib2 = Library(op2) lib3 = Library(op3) print lib1.Op(2) print lib2.Op(2) print lib3.Op(2) </code></pre>
8
2008-12-11T18:53:30Z
[ "python", "lambda" ]
Regular Expressions in unicode strings
360,600
<p>I have some unicode text that I want to clean up using regular expressions. For example I have cases where u'(2'. This exists because for formatting reasons the closing paren ends up in an adjacent html cell. My initial solution to this problem was to look ahead at the contents of the next cell and using a string function determine if it held the closing paren. I knew this was not a great solution but it worked. Now I want to fix it but I can't seem to make the regular expression work. </p> <pre><code>missingParen=re.compile(r"^\(\d[^\)]$") </code></pre> <p>My understanding of what I think I am doing:<br /> ^ at the beginning of the string I want to find<br /> ( an open paren, the paren has to be backslashed because it is a special character<br /> \d I also want to find a single digit<br /> [ I am creating a special character class<br /> ^ I don't want to find what follows<br /> ) which is a close paren<br /> $ at the end of the string </p> <p>And of course the plot thickens I made a silly assumption that because I placed a \d I would not find (33 but I am wrong so I added a {1} to my regular expression and that did not help, it matched (3333, so my problem is more complicated than I thought. I want the string to be only an open paren and a single digit. Is this the more clever approach </p> <pre><code>missingParen=re.compile(r"^\(\d$") </code></pre> <p>And note S Lott _I already tagged it beginner so you can't pick up any cheap points Not that I don't appreciate your insights I keep meaning to read your book, it probably has the answer</p>
1
2008-12-11T19:37:45Z
360,733
<p>Okay sorry for using this a a stream of consciousness thinking stimulator but it appears that writing out my original question got me on the path. It seems to me that this is a solution for what I am trying to do:</p> <pre><code> missingParen=re.compile(r"^\(\d$") </code></pre>
1
2008-12-11T20:13:47Z
[ "python", "regex" ]
What GUI toolkit looks best for a native LAF for Python in Windows and Linux?
360,602
<p>I need to decide on a GUI/Widget toolkit to use with Python for a new project. The target platforms will be Linux with KDE and Windows XP (and probably Vista). What Python GUI toolkit looks best and consistent with the native look and feel of the run time platform?</p> <p>If possible, cite strengths and weaknesses of the suggested toolkit.</p> <p>Thank you,</p> <p>Luis</p>
4
2008-12-11T19:38:02Z
361,549
<p>For KDE and Windows, <a href="http://www.trolltech.com/" rel="nofollow">Qt</a> is the best option. Qt is fine for Gnome/Windows too, but in that case you might prefer <a href="http://wxwidgets.org" rel="nofollow">WxWidgets</a>.</p> <p>Qt bindings for python are <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">here</a>.</p> <p>Remember that for closed source development you need a Qt license, <em>plus</em> a PyQt license. For open source it should be free, but I'm not very familiar with the PyQt licensing.</p>
2
2008-12-12T00:33:32Z
[ "python", "windows", "linux", "native", "gui-toolkit" ]
What GUI toolkit looks best for a native LAF for Python in Windows and Linux?
360,602
<p>I need to decide on a GUI/Widget toolkit to use with Python for a new project. The target platforms will be Linux with KDE and Windows XP (and probably Vista). What Python GUI toolkit looks best and consistent with the native look and feel of the run time platform?</p> <p>If possible, cite strengths and weaknesses of the suggested toolkit.</p> <p>Thank you,</p> <p>Luis</p>
4
2008-12-11T19:38:02Z
361,672
<p>Python binding of Wx is very strong since at least one of the core developer is a python guy itself. WxWdgets is robust, time proven stable, mature, but also bit more than just GUI. Even is a lot is left out in WxPython - because Python itself offers that already - you might find that extra convenient for your project. Wx is the fastest especially on Win, because it lets render the OS and yes WxLicense is de facto LGPL. With XRC you have also a way like Glade to click you to a UI that you can reuse by different projects and languages. What is one major reason for me to use Wx is the fast and helping mailing list, never seen a flamewar, you get even often answers from core developers there, like the notorious vadim zeitlin++. The only thing con to Wx is the API that once grew out of MS MFC and has still its darker(unelegant) corners, but with every version you have some improvements on that as well.</p> <p>QT done some nice stuff, especially warping the language but under python that don't count. They invented also a lot of extra widgets. In wx you have also combined, more complex widgets like e.g. for config dialog, but that goes not that far as in QT. </p> <p>And you could of course use GTK. almost no difference under linux to Wx but a bit alien and slower under win. but also free.</p>
8
2008-12-12T01:48:15Z
[ "python", "windows", "linux", "native", "gui-toolkit" ]
What GUI toolkit looks best for a native LAF for Python in Windows and Linux?
360,602
<p>I need to decide on a GUI/Widget toolkit to use with Python for a new project. The target platforms will be Linux with KDE and Windows XP (and probably Vista). What Python GUI toolkit looks best and consistent with the native look and feel of the run time platform?</p> <p>If possible, cite strengths and weaknesses of the suggested toolkit.</p> <p>Thank you,</p> <p>Luis</p>
4
2008-12-11T19:38:02Z
361,996
<p>Like others said, PyQt or wxPython... The technical difference between the two is more or less imaginary - it's a question of your comfort with the toolkit that matters, really.</p>
0
2008-12-12T05:49:18Z
[ "python", "windows", "linux", "native", "gui-toolkit" ]
Extract ipv6 prefix in python
360,782
<p>Given either the binary or string representation of an IPv6 address and its prefix length, what's the best way to extract the prefix in Python?</p> <p>Is there a library that would do this for me, or would I have to:</p> <ol> <li>convert the address from string to an int (inet_ntop)</li> <li>Mask out the prefix</li> <li>Convert prefix back to binary </li> <li>Convert binary to string (inet_ntop)</li> </ol>
1
2008-12-11T20:33:39Z
360,989
<p>See <a href="http://code.google.com/p/ipaddr-py/" rel="nofollow">http://code.google.com/p/ipaddr-py/</a></p> <p>With this, you can do</p> <pre><code>py&gt; p=ipaddr.IPv6("2001:888:2000:d::a2") py&gt; p.SetPrefix(64) py&gt; p IPv6('2001:888:2000:d::a2/64') py&gt; p.network_ext '2001:888:2000:d::' </code></pre> <p>etc.</p>
2
2008-12-11T21:21:41Z
[ "python", "ipv6" ]
Extract ipv6 prefix in python
360,782
<p>Given either the binary or string representation of an IPv6 address and its prefix length, what's the best way to extract the prefix in Python?</p> <p>Is there a library that would do this for me, or would I have to:</p> <ol> <li>convert the address from string to an int (inet_ntop)</li> <li>Mask out the prefix</li> <li>Convert prefix back to binary </li> <li>Convert binary to string (inet_ntop)</li> </ol>
1
2008-12-11T20:33:39Z
7,661,089
<p>Using the python <a href="https://github.com/drkjam/netaddr" rel="nofollow">netaddr</a> library:</p> <pre><code>&gt;&gt;&gt; from netaddr.ip import IPNetwork, IPAddress &gt;&gt;&gt; IPNetwork('2001:888:2000:d::a2/64').network 2001:888:2000:d:: </code></pre>
0
2011-10-05T12:10:32Z
[ "python", "ipv6" ]
Access CVS through Apache service using SSPI
360,911
<p>I'm running an Apache server (v2.2.10) with mod_python, Python 2.5 and Django. I have a small web app that will show the current projects we have in CVS and allow users to make a build of the different projects (the build checks out the project, and copies certain files over with the source stripped out).</p> <p>On the Django dev server, everything works fine. I can see the list of projects in cvs, check out, etc. On the production server (the Apache one) I get the following error:</p> <p>[8009030d] The credentials supplied to the package were not recognized </p> <p>I'm trying to log in to the CVS server using SSPI. Entering the same command into a shell will execute properly.</p> <p>This is the code I'm using:</p> <pre> <code> def __execute(self, command = ''): command = 'cvs.exe -d :sspi:user:[email protected]:/Projects ls' p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr = subprocess.STDOUT, shell=True) return p.communicate() </code> </pre> <p>I've tried a number of different variations of things, and I can't seem to get it to work. Right now I believe that Apache is the culprit.</p> <p>Any help would be appreciated </p>
0
2008-12-11T21:05:20Z
361,235
<p>Usage of SSPI make me think you are using CVSNT, thus a Windows system; what is the user you are running Apache into? Default user for services is SYSTEM, which does not share the same registry as your current user.</p>
0
2008-12-11T22:28:00Z
[ "python", "apache", "cvs", "sspi" ]
Need Help Understanding how to use less complex regex in Python
361,443
<p>I am trying to learn more about regular expressions I have one below that I believe finds cases where there is a missing close paren on a number up to 999 billion. The one below it I thought should do the same but I do not get similar results</p> <pre><code> missingParenReg=re.compile(r"^\([$]*[0-9]{1,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}[.]*[0-9]*[^)]$") missingParenReg2=re.compile(r"^\([$]?([0-9]{1,3}[,]?)+[.]*[0-9]*[^)]$") </code></pre> <p>I think the second one says: There must be an open paren to start<br /> There may or may not be as many as one dollar sign<br /> The next group must exist at least once but can exist an unlimited number of times<br /> The group should have at least one digit but may have as many as three<br /> The group may have as few as 0 and as many as 1 commas<br /> Following this group there may or may not be a decimal point<br /> If there is a decimal point it will be followed by as many as 0 but as many as uncounted occurences of digits<br /> At the end there should not be a closing paren.</p> <p>I am trying to understand this magic stuff so I would appreciate a correction to my regex (if it can be corrected) in addition to a more elegant solution if you have it.</p>
1
2008-12-11T23:41:55Z
361,475
<p>Are there nested parentheses (your regexps assume there are not)? If not:</p> <pre><code>whether_paren_is_missing = (astring[0] == '(' and not astring[-1] == ')') </code></pre> <p>To validate a dollar amount part:</p> <pre><code>import re cents = r"(?:\.\d\d)" # cents re_dollar_amount = re.compile(r"""(?x) ^ # match at the very begining of the string \$? # optional dollar sign (?: # followed by (?: # integer part 0 # zero | # or [1-9]\d{,2} # 1 to 3 digits (no leading zero) (?: # followed by (?:,\d{3})* # zero or more three-digits groups with commas | # or \d* # zero or more digits without commas (no leading zero) ) ) (?:\.|%(cents)s)? # optional f.p. part | # or %(cents)s # pure f.p. '$.01' ) $ # match end of string """ % vars()) </code></pre> <p>Allow:</p> <pre> $0 0 $234 22 $0.01 10000.12 $99.90 2,010,123 1.00 2,103.45 $.10 $1. </pre> <p>Forbid:</p> <pre> 01234 00 123.4X 1.001 . </pre>
4
2008-12-11T23:57:50Z
[ "python", "regex" ]
Need Help Understanding how to use less complex regex in Python
361,443
<p>I am trying to learn more about regular expressions I have one below that I believe finds cases where there is a missing close paren on a number up to 999 billion. The one below it I thought should do the same but I do not get similar results</p> <pre><code> missingParenReg=re.compile(r"^\([$]*[0-9]{1,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}[.]*[0-9]*[^)]$") missingParenReg2=re.compile(r"^\([$]?([0-9]{1,3}[,]?)+[.]*[0-9]*[^)]$") </code></pre> <p>I think the second one says: There must be an open paren to start<br /> There may or may not be as many as one dollar sign<br /> The next group must exist at least once but can exist an unlimited number of times<br /> The group should have at least one digit but may have as many as three<br /> The group may have as few as 0 and as many as 1 commas<br /> Following this group there may or may not be a decimal point<br /> If there is a decimal point it will be followed by as many as 0 but as many as uncounted occurences of digits<br /> At the end there should not be a closing paren.</p> <p>I am trying to understand this magic stuff so I would appreciate a correction to my regex (if it can be corrected) in addition to a more elegant solution if you have it.</p>
1
2008-12-11T23:41:55Z
361,485
<p>One difference I see at a glance is that your regex will not find strings like:</p> <pre><code>(123,,, </code></pre> <p>That's because the corrected version requires at least one digit between commas. (A reasonable requirement, I'd say.) </p>
-1
2008-12-12T00:02:56Z
[ "python", "regex" ]
Need Help Understanding how to use less complex regex in Python
361,443
<p>I am trying to learn more about regular expressions I have one below that I believe finds cases where there is a missing close paren on a number up to 999 billion. The one below it I thought should do the same but I do not get similar results</p> <pre><code> missingParenReg=re.compile(r"^\([$]*[0-9]{1,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}[.]*[0-9]*[^)]$") missingParenReg2=re.compile(r"^\([$]?([0-9]{1,3}[,]?)+[.]*[0-9]*[^)]$") </code></pre> <p>I think the second one says: There must be an open paren to start<br /> There may or may not be as many as one dollar sign<br /> The next group must exist at least once but can exist an unlimited number of times<br /> The group should have at least one digit but may have as many as three<br /> The group may have as few as 0 and as many as 1 commas<br /> Following this group there may or may not be a decimal point<br /> If there is a decimal point it will be followed by as many as 0 but as many as uncounted occurences of digits<br /> At the end there should not be a closing paren.</p> <p>I am trying to understand this magic stuff so I would appreciate a correction to my regex (if it can be corrected) in addition to a more elegant solution if you have it.</p>
1
2008-12-11T23:41:55Z
361,512
<p>The trickier part about regular expressions isn't making them accept valid input, it's making them reject invalid input. For example, the second expression accepts input that is clearly wrong, including:</p> <ul> <li><code>(1,2,3,4</code> -- one digit between each comma</li> <li><code>(12,34,56</code> -- two digits between each comma</li> <li><code>(1234......5</code> -- unlimited number of decimal points</li> <li><code>(1234,.5</code> -- comma before decimal point</li> <li><code>(123,456789,012</code> -- if there are some commas, they should be between each triple</li> <li><code>(01234</code> -- leading zero is not conventional</li> <li><code>(123.4X</code> -- last char is not a closing paren</li> </ul> <p>Here's an alternative regular expression that should reject the examples above:</p> <p><code>[-+]?[$]?(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})*)(\.\d+)?</code></p> <ul> <li>Optional leading plus/minus.</li> <li>Optional dollar sign.</li> <li>Three choices separated by <code>|</code>: <ul> <li>Single zero digit (for numbers like 0.5 or simply 0).</li> <li>Any number of digits with no commas. The first digit must not be zero.</li> <li>Comma-separated digits. The first digit must not be zero. Up to three digits before the first comma. Each comma must be followed by exactly three digits. </li> </ul></li> <li>Optional single decimal point, which must be followed by one or more digits.</li> </ul> <p>Regarding the parens, if all you care about is whether the parens are balanced, then you can disregard parsing out the numeric format precisely; just trust that any combination of digits, decimal points, and commas between the parens are valid. Then use the <code>(?!...)</code> construct that evaluates as a match if the input <em>doesn't</em> match the regular expression inside.</p> <p><code>(?!\([$\d.,]+\))</code></p>
3
2008-12-12T00:14:10Z
[ "python", "regex" ]
Need Help Understanding how to use less complex regex in Python
361,443
<p>I am trying to learn more about regular expressions I have one below that I believe finds cases where there is a missing close paren on a number up to 999 billion. The one below it I thought should do the same but I do not get similar results</p> <pre><code> missingParenReg=re.compile(r"^\([$]*[0-9]{1,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}[.]*[0-9]*[^)]$") missingParenReg2=re.compile(r"^\([$]?([0-9]{1,3}[,]?)+[.]*[0-9]*[^)]$") </code></pre> <p>I think the second one says: There must be an open paren to start<br /> There may or may not be as many as one dollar sign<br /> The next group must exist at least once but can exist an unlimited number of times<br /> The group should have at least one digit but may have as many as three<br /> The group may have as few as 0 and as many as 1 commas<br /> Following this group there may or may not be a decimal point<br /> If there is a decimal point it will be followed by as many as 0 but as many as uncounted occurences of digits<br /> At the end there should not be a closing paren.</p> <p>I am trying to understand this magic stuff so I would appreciate a correction to my regex (if it can be corrected) in addition to a more elegant solution if you have it.</p>
1
2008-12-11T23:41:55Z
867,212
<p>I've found very helpful to use <a href="http://code.google.com/p/kiki-re/" rel="nofollow">kiki</a> when tailoring a regex. It shows you visually what's going on with your regexes. It is a huge time-saver.</p>
0
2009-05-15T06:16:29Z
[ "python", "regex" ]
Techniques for data comparison between different schemas
361,945
<p>Are there techniques for comparing the same data stored in different schemas? The situation is something like this. If I have a db with schema A and it stores data for a feature in say, 5 tables. Schema A -> Schema B is done during an upgrade process. During the upgrade process some transformation logic is applied and the data is stored in 7 tables in Schema B. What i'm after is some way to verify data integrity, basically i would have to compare different schemas while factoring in the transformation logic. Short of writing some custom t-sql sprocs to compare the data, is there an alternate method? I'm leaning towards python to automate this, are there any python modules that would help me out? To better illustrate my question the following diagram is a rough picture of one of the many data sets i would need to compare, Properties 1,2,3 and 4 are migrated from Schema source to destination, but they are spread across different tables.</p> <pre><code>Table1Src Table1Dest | | --ID(Primary Key) --ID(Primary Key) --Property1 --Property1 --Property2 --Property5 --Property3 --Property6 Table2Src Table2Dest | | --ID(Foreign Key-&gt;Table1Src) --ID(Foreign Key-&gt;Table1Dest) --Property4 --Property2 --Property3 Table3Dest | --ID(Foreign Key-&gt;Table1Dest) --Property4 --Property7 </code></pre>
0
2008-12-12T05:09:04Z
361,988
<p>Basically, you should create object representations for both schema versions, and then compare objects. This is best done if they all fit into memory simultaneously; if not, you need to iterate over all objects in one representation, fetch the corresponding object in the other representation, compare them, and then do the same vice versa.</p> <p>The difficult part may be to obtain object representations; you can see whether <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> can be used conveniently for your tables. SQLAlchemy is, in principle, capable of mapping existing schema definitions onto objects.</p>
1
2008-12-12T05:43:31Z
[ "python", "sql", "database" ]
Techniques for data comparison between different schemas
361,945
<p>Are there techniques for comparing the same data stored in different schemas? The situation is something like this. If I have a db with schema A and it stores data for a feature in say, 5 tables. Schema A -> Schema B is done during an upgrade process. During the upgrade process some transformation logic is applied and the data is stored in 7 tables in Schema B. What i'm after is some way to verify data integrity, basically i would have to compare different schemas while factoring in the transformation logic. Short of writing some custom t-sql sprocs to compare the data, is there an alternate method? I'm leaning towards python to automate this, are there any python modules that would help me out? To better illustrate my question the following diagram is a rough picture of one of the many data sets i would need to compare, Properties 1,2,3 and 4 are migrated from Schema source to destination, but they are spread across different tables.</p> <pre><code>Table1Src Table1Dest | | --ID(Primary Key) --ID(Primary Key) --Property1 --Property1 --Property2 --Property5 --Property3 --Property6 Table2Src Table2Dest | | --ID(Foreign Key-&gt;Table1Src) --ID(Foreign Key-&gt;Table1Dest) --Property4 --Property2 --Property3 Table3Dest | --ID(Foreign Key-&gt;Table1Dest) --Property4 --Property7 </code></pre>
0
2008-12-12T05:09:04Z
362,068
<p>I've used SQLAlchemy successfully for migration between one schema and another - that's a similar process (as indicated by Martin v. Löwis) as comparison. Especially if you use an .equals(other) method.</p>
0
2008-12-12T06:52:54Z
[ "python", "sql", "database" ]
Techniques for data comparison between different schemas
361,945
<p>Are there techniques for comparing the same data stored in different schemas? The situation is something like this. If I have a db with schema A and it stores data for a feature in say, 5 tables. Schema A -> Schema B is done during an upgrade process. During the upgrade process some transformation logic is applied and the data is stored in 7 tables in Schema B. What i'm after is some way to verify data integrity, basically i would have to compare different schemas while factoring in the transformation logic. Short of writing some custom t-sql sprocs to compare the data, is there an alternate method? I'm leaning towards python to automate this, are there any python modules that would help me out? To better illustrate my question the following diagram is a rough picture of one of the many data sets i would need to compare, Properties 1,2,3 and 4 are migrated from Schema source to destination, but they are spread across different tables.</p> <pre><code>Table1Src Table1Dest | | --ID(Primary Key) --ID(Primary Key) --Property1 --Property1 --Property2 --Property5 --Property3 --Property6 Table2Src Table2Dest | | --ID(Foreign Key-&gt;Table1Src) --ID(Foreign Key-&gt;Table1Dest) --Property4 --Property2 --Property3 Table3Dest | --ID(Foreign Key-&gt;Table1Dest) --Property4 --Property7 </code></pre>
0
2008-12-12T05:09:04Z
362,074
<p>Make "views" on both the schemas that translate to the same buisness representation of data. Export these views to flat files and then you can use any plain vanilla file diff utility to compare and point out differences. </p>
2
2008-12-12T06:56:48Z
[ "python", "sql", "database" ]
Python: Finding partial string matches in a large corpus of strings
362,231
<p>I'm interested in implementing autocomplete in Python. For example, as the user types in a string, I'd like to show the subset of files on disk whose names start with that string. </p> <p>What's an efficient algorithm for finding strings that match some condition in a large corpus (say a few hundred thousand strings)? Something like:</p> <pre><code>matches = [s for s in allfiles if s.startswith(input)] </code></pre> <p>I'd like to have the condition be flexible; eg. instead of a strict startswith, it'd be a match so long as all letters in input appears in s in the same order. What's better than the brute-force method I'm showing here?</p>
1
2008-12-12T08:49:03Z
362,264
<p>I used <a href="http://pylucene.osafoundation.org/" rel="nofollow">Lucene</a> to autocomplete a text field with more then a hundred thousand possibilities and I perceived it as instantaneous.</p>
3
2008-12-12T09:05:15Z
[ "python", "search" ]
Python: Finding partial string matches in a large corpus of strings
362,231
<p>I'm interested in implementing autocomplete in Python. For example, as the user types in a string, I'd like to show the subset of files on disk whose names start with that string. </p> <p>What's an efficient algorithm for finding strings that match some condition in a large corpus (say a few hundred thousand strings)? Something like:</p> <pre><code>matches = [s for s in allfiles if s.startswith(input)] </code></pre> <p>I'd like to have the condition be flexible; eg. instead of a strict startswith, it'd be a match so long as all letters in input appears in s in the same order. What's better than the brute-force method I'm showing here?</p>
1
2008-12-12T08:49:03Z
362,266
<p>The flexibility you want for matching your string is called <em>Fuzzy Matching</em> or <em>Fuzzy Searching</em> . I am not aware of any python implementation (but I haven't looked deeply in the subject) but there are C/C++ implementations that you can reuse, like the <a href="http://laurikari.net/tre/" rel="nofollow">TRE packaged</a> that supports regexp with fuzzy parameters.</p> <p>Apart from that, there is always the question of whether the total list of your words fits in memory or not. If not, keeping them in a list is not feasible and will have to cache something to disk or to a database.</p>
0
2008-12-12T09:05:57Z
[ "python", "search" ]
Python: Finding partial string matches in a large corpus of strings
362,231
<p>I'm interested in implementing autocomplete in Python. For example, as the user types in a string, I'd like to show the subset of files on disk whose names start with that string. </p> <p>What's an efficient algorithm for finding strings that match some condition in a large corpus (say a few hundred thousand strings)? Something like:</p> <pre><code>matches = [s for s in allfiles if s.startswith(input)] </code></pre> <p>I'd like to have the condition be flexible; eg. instead of a strict startswith, it'd be a match so long as all letters in input appears in s in the same order. What's better than the brute-force method I'm showing here?</p>
1
2008-12-12T08:49:03Z
362,285
<p>Maybe the readline module is what you are looking for. It is an interface to the GNU readline library <a href="http://docs.python.org/library/readline.html#module-readline" rel="nofollow">Python Documentation</a>. Maybe you can supply your own completition function with <code>set_completer()</code>.</p>
1
2008-12-12T09:15:52Z
[ "python", "search" ]
Python: Finding partial string matches in a large corpus of strings
362,231
<p>I'm interested in implementing autocomplete in Python. For example, as the user types in a string, I'd like to show the subset of files on disk whose names start with that string. </p> <p>What's an efficient algorithm for finding strings that match some condition in a large corpus (say a few hundred thousand strings)? Something like:</p> <pre><code>matches = [s for s in allfiles if s.startswith(input)] </code></pre> <p>I'd like to have the condition be flexible; eg. instead of a strict startswith, it'd be a match so long as all letters in input appears in s in the same order. What's better than the brute-force method I'm showing here?</p>
1
2008-12-12T08:49:03Z
362,288
<p>(addressing just the string matching part of the question)</p> <p>If you want to try something quickly yourself, why not create a few dictionaries, each mapping initial patterns to lists of strings where</p> <ul> <li>Each dictionary is keyed on initial patterns of a particular length</li> <li>All the strings in a string list start with the initial pattern</li> <li>An initial pattern/string list pair is only created if there are <em>less than</em> a certain number (say 10) of strings in the list</li> </ul> <p>So, when the user has typed three characters, for example, you look in the dictionary with keys of length 3. If there is a match, it means you have between 1 and 10 possibilities immediately available.</p>
0
2008-12-12T09:18:05Z
[ "python", "search" ]
Python: Finding partial string matches in a large corpus of strings
362,231
<p>I'm interested in implementing autocomplete in Python. For example, as the user types in a string, I'd like to show the subset of files on disk whose names start with that string. </p> <p>What's an efficient algorithm for finding strings that match some condition in a large corpus (say a few hundred thousand strings)? Something like:</p> <pre><code>matches = [s for s in allfiles if s.startswith(input)] </code></pre> <p>I'd like to have the condition be flexible; eg. instead of a strict startswith, it'd be a match so long as all letters in input appears in s in the same order. What's better than the brute-force method I'm showing here?</p>
1
2008-12-12T08:49:03Z
362,433
<p>For exact matching, generally the way to implement something like this is to store your corpus in a <a href="http://en.wikipedia.org/wiki/Trie" rel="nofollow">trie</a>. The idea is that you store each letter as a node in the tree, linking to the next letter in a word. Finding the matches is simply walking the tree, and showing all children of your current location. eg. "cat", "cow" and "car" would be stored as:</p> <pre><code> a--t / \ c r \ o--w </code></pre> <p>When you get a c, you start at the c node, an a will then take you to the c/a node (children "t" and "r", making cat and car as your completions).</p> <p>Note that you'll also need to mark nodes that are complete words to handle names that are substrings of others (eg "car" and "cart")</p> <p>To get the desired fuzzy matching, you may need to make some changes however.</p>
6
2008-12-12T10:37:07Z
[ "python", "search" ]
Is there a standalone alternative to activerecord-like database schema migrations?
362,334
<p>Is there any standalone alternative to activerecord-like migrations. Something like a script that is able to track current schema version and apply outstanding migrations. Basically, these migration files could be just a plain SQL files, something like:</p> <pre> [timestamp]_create_users.sql reverse_[timestamp]_create_users.sql </pre> <p>Language of implementation isn't very important — it could be anything that is usually installed/pre-installed on *nix systems.</p> <p>I tried to find something out — but failed. I can certainly develop my own in an hour or two, but I am just curious — may be something nice is out there already.</p>
1
2008-12-12T09:46:31Z
362,353
<p>Not a linux option, but might answer this question for some people:</p> <p>SQLYog can do this for MySQL - its a windows GUI tool:</p> <p><a href="http://www.webyog.com/en/" rel="nofollow">http://www.webyog.com/en/</a></p> <p>It can (amongst other things) compare schemas and make one schema look like another, or generate the sql required to do this if you want to do that instead. We use it for making sql patch files that we can use for upgrades. Its easier than manually maintaining a file as you make changes in development.</p>
0
2008-12-12T10:01:20Z
[ "php", "python", "sql", "mysql", "shell" ]
Is there a standalone alternative to activerecord-like database schema migrations?
362,334
<p>Is there any standalone alternative to activerecord-like migrations. Something like a script that is able to track current schema version and apply outstanding migrations. Basically, these migration files could be just a plain SQL files, something like:</p> <pre> [timestamp]_create_users.sql reverse_[timestamp]_create_users.sql </pre> <p>Language of implementation isn't very important — it could be anything that is usually installed/pre-installed on *nix systems.</p> <p>I tried to find something out — but failed. I can certainly develop my own in an hour or two, but I am just curious — may be something nice is out there already.</p>
1
2008-12-12T09:46:31Z
362,656
<p>Try <a href="http://freshmeat.net/projects/liquibase/" rel="nofollow">http://freshmeat.net/projects/liquibase/</a></p> <p>If you are using MySQL specifically, have a look at: <a href="http://www.mysqldiff.org/" rel="nofollow">http://www.mysqldiff.org/</a> I used this to synchronize the schema of two databases (so you would have to apply the changes to a "master").</p> <p>There's also <a href="http://phpmyversion.sourceforge.net/" rel="nofollow">http://phpmyversion.sourceforge.net/</a></p>
2
2008-12-12T12:54:19Z
[ "php", "python", "sql", "mysql", "shell" ]
Is there a standalone alternative to activerecord-like database schema migrations?
362,334
<p>Is there any standalone alternative to activerecord-like migrations. Something like a script that is able to track current schema version and apply outstanding migrations. Basically, these migration files could be just a plain SQL files, something like:</p> <pre> [timestamp]_create_users.sql reverse_[timestamp]_create_users.sql </pre> <p>Language of implementation isn't very important — it could be anything that is usually installed/pre-installed on *nix systems.</p> <p>I tried to find something out — but failed. I can certainly develop my own in an hour or two, but I am just curious — may be something nice is out there already.</p>
1
2008-12-12T09:46:31Z
362,662
<p>Check out <a href="http://autopatch.sourceforge.net/" rel="nofollow">AutoPatch</a></p>
0
2008-12-12T12:59:02Z
[ "php", "python", "sql", "mysql", "shell" ]
Is there a standalone alternative to activerecord-like database schema migrations?
362,334
<p>Is there any standalone alternative to activerecord-like migrations. Something like a script that is able to track current schema version and apply outstanding migrations. Basically, these migration files could be just a plain SQL files, something like:</p> <pre> [timestamp]_create_users.sql reverse_[timestamp]_create_users.sql </pre> <p>Language of implementation isn't very important — it could be anything that is usually installed/pre-installed on *nix systems.</p> <p>I tried to find something out — but failed. I can certainly develop my own in an hour or two, but I am just curious — may be something nice is out there already.</p>
1
2008-12-12T09:46:31Z
362,705
<p>The ezComponents library has a <a href="http://www.ezcomponents.org/docs/api/latest/introduction_DatabaseSchema.html" rel="nofollow">database schema component</a> that can compare and apply schema differences between two databases (or a database and a file).</p>
0
2008-12-12T13:20:26Z
[ "php", "python", "sql", "mysql", "shell" ]
Is there a standalone alternative to activerecord-like database schema migrations?
362,334
<p>Is there any standalone alternative to activerecord-like migrations. Something like a script that is able to track current schema version and apply outstanding migrations. Basically, these migration files could be just a plain SQL files, something like:</p> <pre> [timestamp]_create_users.sql reverse_[timestamp]_create_users.sql </pre> <p>Language of implementation isn't very important — it could be anything that is usually installed/pre-installed on *nix systems.</p> <p>I tried to find something out — but failed. I can certainly develop my own in an hour or two, but I am just curious — may be something nice is out there already.</p>
1
2008-12-12T09:46:31Z
364,122
<p><a href="http://code.google.com/p/sqlalchemy-migrate/" rel="nofollow">http://code.google.com/p/sqlalchemy-migrate/</a></p>
1
2008-12-12T20:59:27Z
[ "php", "python", "sql", "mysql", "shell" ]
Is there a standalone alternative to activerecord-like database schema migrations?
362,334
<p>Is there any standalone alternative to activerecord-like migrations. Something like a script that is able to track current schema version and apply outstanding migrations. Basically, these migration files could be just a plain SQL files, something like:</p> <pre> [timestamp]_create_users.sql reverse_[timestamp]_create_users.sql </pre> <p>Language of implementation isn't very important — it could be anything that is usually installed/pre-installed on *nix systems.</p> <p>I tried to find something out — but failed. I can certainly develop my own in an hour or two, but I am just curious — may be something nice is out there already.</p>
1
2008-12-12T09:46:31Z
953,940
<p><a href="https://sourceforge.net/projects/migrations/" rel="nofollow">https://sourceforge.net/projects/migrations/</a></p> <p>This is a tool for managing structural changes to database schemas based on Active Record migrations from Rails. Features multiple schema interactions, runtime substitution of values, script generations, and more.</p> <p>Plus it has both a command line interface and a graphical interface. Also is actively developed and our company has been using it for over a year now and it has greatly improved the lives of everyone from development to dbas to operations to streamlined deployments and rollbacks. Management takes db changes for granted now (sometimes not a good thing) because it is so automated now thanks to this tool.</p>
0
2009-06-05T01:50:25Z
[ "php", "python", "sql", "mysql", "shell" ]
Implementing a "[command] [action] [parameter]" style command-line interfaces?
362,426
<p>What is the "cleanest" way to implement an command-line UI, similar to git's, for example:</p> <pre><code>git push origin/master git remote add origin git://example.com master </code></pre> <p>Ideally also allowing the more flexible parsing, for example,</p> <pre><code>jump_to_folder app theappname v2 jump_to_folder app theappname source jump_to_folder app theappname source v2 jump_to_folder app theappname build v1 jump_to_folder app theappname build 1 jump_to_folder app theappname v2 build </code></pre> <p><code>jump_to_folder</code> is the scripts name, <code>app</code> is the command, <code>theappname</code> is a "fixed-location" parameter, "build" and "v2" etc are arguments (For example, possible arguments would be any number/any number prefixed with a v, or build/source/tmp/config)</p> <p>I could just manually parse the arguments with a series of <code>if</code>/<code>else</code>/<code>elifs</code>, but there must be a more elegant way to do this?</p> <p>As an entirely theoretically example, I could describe the UI schema..</p> <pre><code>app: fixed: application_name optional params: arg subsection: "build" "source" "tmp" "config" arg version: integer "v" + integer </code></pre> <p>Then parse the supplied arguments though the above schema, and get a dictionary:</p> <pre><code>&gt;&gt;&gt; print schema.parse(["app", "theappname", "v1", "source"]) { "application_name": "theappname", "params":{ "subsection": "source", "version":"v1" } } </code></pre> <p>Does such a system exist? If not, how would I go about implementing something along these lines?</p>
9
2008-12-12T10:35:03Z
362,475
<p>Straight from one of my scripts:</p> <pre><code>import sys def prog1_func1_act1(): print "pfa1" def prog2_func2_act2(): print "pfa2" commands = { "prog1 func1 act1": prog1_func1_act1, "prog2 func2 act2": prog2_func2_act2 } try: commands[" ".join(sys.argv[1:])]() except KeyError: print "Usage: ", commands.keys() </code></pre> <p>It's a pretty quick and dirty solution, but works great for my usage. If I were to clean it up a bit, I would probably add <a href="http://argparse.python-hosting.com/" rel="nofollow">argparse</a> to the mix for parsing positional and keyword arguments.</p>
2
2008-12-12T11:04:19Z
[ "python", "command-line", "user-interface" ]
Implementing a "[command] [action] [parameter]" style command-line interfaces?
362,426
<p>What is the "cleanest" way to implement an command-line UI, similar to git's, for example:</p> <pre><code>git push origin/master git remote add origin git://example.com master </code></pre> <p>Ideally also allowing the more flexible parsing, for example,</p> <pre><code>jump_to_folder app theappname v2 jump_to_folder app theappname source jump_to_folder app theappname source v2 jump_to_folder app theappname build v1 jump_to_folder app theappname build 1 jump_to_folder app theappname v2 build </code></pre> <p><code>jump_to_folder</code> is the scripts name, <code>app</code> is the command, <code>theappname</code> is a "fixed-location" parameter, "build" and "v2" etc are arguments (For example, possible arguments would be any number/any number prefixed with a v, or build/source/tmp/config)</p> <p>I could just manually parse the arguments with a series of <code>if</code>/<code>else</code>/<code>elifs</code>, but there must be a more elegant way to do this?</p> <p>As an entirely theoretically example, I could describe the UI schema..</p> <pre><code>app: fixed: application_name optional params: arg subsection: "build" "source" "tmp" "config" arg version: integer "v" + integer </code></pre> <p>Then parse the supplied arguments though the above schema, and get a dictionary:</p> <pre><code>&gt;&gt;&gt; print schema.parse(["app", "theappname", "v1", "source"]) { "application_name": "theappname", "params":{ "subsection": "source", "version":"v1" } } </code></pre> <p>Does such a system exist? If not, how would I go about implementing something along these lines?</p>
9
2008-12-12T10:35:03Z
362,476
<p>Python has a module for parsing command line options, <a href="http://docs.python.org/library/optparse.html" rel="nofollow">optparse</a>.</p>
1
2008-12-12T11:04:58Z
[ "python", "command-line", "user-interface" ]
Implementing a "[command] [action] [parameter]" style command-line interfaces?
362,426
<p>What is the "cleanest" way to implement an command-line UI, similar to git's, for example:</p> <pre><code>git push origin/master git remote add origin git://example.com master </code></pre> <p>Ideally also allowing the more flexible parsing, for example,</p> <pre><code>jump_to_folder app theappname v2 jump_to_folder app theappname source jump_to_folder app theappname source v2 jump_to_folder app theappname build v1 jump_to_folder app theappname build 1 jump_to_folder app theappname v2 build </code></pre> <p><code>jump_to_folder</code> is the scripts name, <code>app</code> is the command, <code>theappname</code> is a "fixed-location" parameter, "build" and "v2" etc are arguments (For example, possible arguments would be any number/any number prefixed with a v, or build/source/tmp/config)</p> <p>I could just manually parse the arguments with a series of <code>if</code>/<code>else</code>/<code>elifs</code>, but there must be a more elegant way to do this?</p> <p>As an entirely theoretically example, I could describe the UI schema..</p> <pre><code>app: fixed: application_name optional params: arg subsection: "build" "source" "tmp" "config" arg version: integer "v" + integer </code></pre> <p>Then parse the supplied arguments though the above schema, and get a dictionary:</p> <pre><code>&gt;&gt;&gt; print schema.parse(["app", "theappname", "v1", "source"]) { "application_name": "theappname", "params":{ "subsection": "source", "version":"v1" } } </code></pre> <p>Does such a system exist? If not, how would I go about implementing something along these lines?</p>
9
2008-12-12T10:35:03Z
362,700
<p>The <code>cmd</code> module would probably work well for this.</p> <p>Example:</p> <pre><code>import cmd class Calc(cmd.Cmd): def do_add(self, arg): print sum(map(int, arg.split())) if __name__ == '__main__': Calc().cmdloop() </code></pre> <p>Run it:</p> <pre><code>$python calc.py (Cmd) add 4 5 9 (Cmd) help Undocumented commands: ====================== add help (Cmd) </code></pre> <p>See the <a href="http://docs.python.org/library/cmd.html">Python docs</a> or <a href="http://blog.doughellmann.com/2008/05/pymotw-cmd.html">PyMOTW site</a> for more info.</p>
9
2008-12-12T13:17:11Z
[ "python", "command-line", "user-interface" ]
Implementing a "[command] [action] [parameter]" style command-line interfaces?
362,426
<p>What is the "cleanest" way to implement an command-line UI, similar to git's, for example:</p> <pre><code>git push origin/master git remote add origin git://example.com master </code></pre> <p>Ideally also allowing the more flexible parsing, for example,</p> <pre><code>jump_to_folder app theappname v2 jump_to_folder app theappname source jump_to_folder app theappname source v2 jump_to_folder app theappname build v1 jump_to_folder app theappname build 1 jump_to_folder app theappname v2 build </code></pre> <p><code>jump_to_folder</code> is the scripts name, <code>app</code> is the command, <code>theappname</code> is a "fixed-location" parameter, "build" and "v2" etc are arguments (For example, possible arguments would be any number/any number prefixed with a v, or build/source/tmp/config)</p> <p>I could just manually parse the arguments with a series of <code>if</code>/<code>else</code>/<code>elifs</code>, but there must be a more elegant way to do this?</p> <p>As an entirely theoretically example, I could describe the UI schema..</p> <pre><code>app: fixed: application_name optional params: arg subsection: "build" "source" "tmp" "config" arg version: integer "v" + integer </code></pre> <p>Then parse the supplied arguments though the above schema, and get a dictionary:</p> <pre><code>&gt;&gt;&gt; print schema.parse(["app", "theappname", "v1", "source"]) { "application_name": "theappname", "params":{ "subsection": "source", "version":"v1" } } </code></pre> <p>Does such a system exist? If not, how would I go about implementing something along these lines?</p>
9
2008-12-12T10:35:03Z
362,936
<p>Here's my suggestion.</p> <ol> <li><p>Change your grammar slightly.</p></li> <li><p>Use optparse.</p></li> </ol> <p>Ideally also allowing the more flexible parsing, for example,</p> <pre><code>jump_to_folder -n theappname -v2 cmd jump_to_folder -n theappname cmd source jump_to_folder -n theappname -v2 cmd source jump_to_folder -n theappname -v1 cmd build jump_to_folder -n theappname -1 cmd build jump_to_folder -n theappname -v2 cmd build </code></pre> <p>Then you have 1 or 2 args: the command is always the first arg. It's optional argument is always the second arg.</p> <p>Everything else is options, in no particular order.</p>
0
2008-12-12T14:41:32Z
[ "python", "command-line", "user-interface" ]
Implementing a "[command] [action] [parameter]" style command-line interfaces?
362,426
<p>What is the "cleanest" way to implement an command-line UI, similar to git's, for example:</p> <pre><code>git push origin/master git remote add origin git://example.com master </code></pre> <p>Ideally also allowing the more flexible parsing, for example,</p> <pre><code>jump_to_folder app theappname v2 jump_to_folder app theappname source jump_to_folder app theappname source v2 jump_to_folder app theappname build v1 jump_to_folder app theappname build 1 jump_to_folder app theappname v2 build </code></pre> <p><code>jump_to_folder</code> is the scripts name, <code>app</code> is the command, <code>theappname</code> is a "fixed-location" parameter, "build" and "v2" etc are arguments (For example, possible arguments would be any number/any number prefixed with a v, or build/source/tmp/config)</p> <p>I could just manually parse the arguments with a series of <code>if</code>/<code>else</code>/<code>elifs</code>, but there must be a more elegant way to do this?</p> <p>As an entirely theoretically example, I could describe the UI schema..</p> <pre><code>app: fixed: application_name optional params: arg subsection: "build" "source" "tmp" "config" arg version: integer "v" + integer </code></pre> <p>Then parse the supplied arguments though the above schema, and get a dictionary:</p> <pre><code>&gt;&gt;&gt; print schema.parse(["app", "theappname", "v1", "source"]) { "application_name": "theappname", "params":{ "subsection": "source", "version":"v1" } } </code></pre> <p>Does such a system exist? If not, how would I go about implementing something along these lines?</p>
9
2008-12-12T10:35:03Z
10,888,310
<p>You might want to take a look at <a href="http://readthedocs.org/docs/cliff/en/latest/" rel="nofollow">cliff – Command Line Interface Formulation Framework</a></p>
1
2012-06-04T21:02:44Z
[ "python", "command-line", "user-interface" ]
Implementing a "[command] [action] [parameter]" style command-line interfaces?
362,426
<p>What is the "cleanest" way to implement an command-line UI, similar to git's, for example:</p> <pre><code>git push origin/master git remote add origin git://example.com master </code></pre> <p>Ideally also allowing the more flexible parsing, for example,</p> <pre><code>jump_to_folder app theappname v2 jump_to_folder app theappname source jump_to_folder app theappname source v2 jump_to_folder app theappname build v1 jump_to_folder app theappname build 1 jump_to_folder app theappname v2 build </code></pre> <p><code>jump_to_folder</code> is the scripts name, <code>app</code> is the command, <code>theappname</code> is a "fixed-location" parameter, "build" and "v2" etc are arguments (For example, possible arguments would be any number/any number prefixed with a v, or build/source/tmp/config)</p> <p>I could just manually parse the arguments with a series of <code>if</code>/<code>else</code>/<code>elifs</code>, but there must be a more elegant way to do this?</p> <p>As an entirely theoretically example, I could describe the UI schema..</p> <pre><code>app: fixed: application_name optional params: arg subsection: "build" "source" "tmp" "config" arg version: integer "v" + integer </code></pre> <p>Then parse the supplied arguments though the above schema, and get a dictionary:</p> <pre><code>&gt;&gt;&gt; print schema.parse(["app", "theappname", "v1", "source"]) { "application_name": "theappname", "params":{ "subsection": "source", "version":"v1" } } </code></pre> <p>Does such a system exist? If not, how would I go about implementing something along these lines?</p>
9
2008-12-12T10:35:03Z
10,913,734
<p><a href="http://docs.python.org/library/argparse.html#sub-commands">argparse</a> is perfect for this, specifically <a href="http://docs.python.org/library/argparse.html#sub-commands">"sub-commands"</a> and positional args</p> <pre><code>import argparse def main(): arger = argparse.ArgumentParser() # Arguments for top-level, e.g "subcmds.py -v" arger.add_argument("-v", "--verbose", action="count", default=0) subparsers = arger.add_subparsers(dest="command") # Make parser for "subcmds.py info ..." info_parser = subparsers.add_parser("info") info_parser.add_argument("-m", "--moo", dest="moo") # Make parser for "subcmds.py create ..." create_parser = subparsers.add_parser("create") create_parser.add_argument("name") create_parser.add_argument("additional", nargs="*") # Parse opts = arger.parse_args() # Print option object for debug print opts if opts.command == "info": print "Info command" print "--moo was %s" % opts.moo elif opts.command == "create": print "Creating %s" % opts.name print "Additional: %s" % opts.additional else: # argparse will error on unexpected commands, but # in case we mistype one of the elif statements... raise ValueError("Unhandled command %s" % opts.command) if __name__ == '__main__': main() </code></pre> <p>This can be used like so:</p> <pre><code>$ python subcmds.py create myapp v1 blah Namespace(additional=['v1', 'blah'], command='create', name='myapp', verbose=0) Creating myapp Additional: ['v1', 'blah'] $ python subcmds.py info --moo usage: subcmds.py info [-h] [-m MOO] subcmds.py info: error: argument -m/--moo: expected one argument $ python subcmds.py info --moo 1 Namespace(command='info', moo='1', verbose=0) Info command --moo was 1 </code></pre>
7
2012-06-06T11:56:29Z
[ "python", "command-line", "user-interface" ]
Serializing a Python object to/from a S60 phone
362,484
<p>I'm looking for a way to serialize <strong>generic</strong> Python objects between a CherryPy-based server and a Python client running on a Symbian phone.. Since pyS60 doesn't implement the pickle module, how would you do it?</p> <p>I know about <a href="http://home.gna.org/oomadness/en/cerealizer" rel="nofollow">Cerealizer</a> but it requires you to register classes before use (which I'd like to avoid) and doesn't look very mature.. So, what would you use? Python 2.2's pickle module maybe, extracted from the sources? XML, JSON? Which one of the several libraries? :)</p>
1
2008-12-12T11:11:00Z
362,579
<p>What's wrong with using the pickle module?</p>
2
2008-12-12T12:09:24Z
[ "python", "serialization", "pickle", "pys60" ]
Serializing a Python object to/from a S60 phone
362,484
<p>I'm looking for a way to serialize <strong>generic</strong> Python objects between a CherryPy-based server and a Python client running on a Symbian phone.. Since pyS60 doesn't implement the pickle module, how would you do it?</p> <p>I know about <a href="http://home.gna.org/oomadness/en/cerealizer" rel="nofollow">Cerealizer</a> but it requires you to register classes before use (which I'd like to avoid) and doesn't look very mature.. So, what would you use? Python 2.2's pickle module maybe, extracted from the sources? XML, JSON? Which one of the several libraries? :)</p>
1
2008-12-12T11:11:00Z
363,355
<p>There is a json module someone wrote for PyS60. I'd simply grab that, serialize things into json and use that as the transfer method between the web/client app. </p> <p>For the json lib and a decent book on PyS60: <a href="http://www.mobilepythonbook.org/" rel="nofollow">http://www.mobilepythonbook.org/</a></p>
1
2008-12-12T16:48:31Z
[ "python", "serialization", "pickle", "pys60" ]
Serializing a Python object to/from a S60 phone
362,484
<p>I'm looking for a way to serialize <strong>generic</strong> Python objects between a CherryPy-based server and a Python client running on a Symbian phone.. Since pyS60 doesn't implement the pickle module, how would you do it?</p> <p>I know about <a href="http://home.gna.org/oomadness/en/cerealizer" rel="nofollow">Cerealizer</a> but it requires you to register classes before use (which I'd like to avoid) and doesn't look very mature.. So, what would you use? Python 2.2's pickle module maybe, extracted from the sources? XML, JSON? Which one of the several libraries? :)</p>
1
2008-12-12T11:11:00Z
965,984
<p>The last versions of Python (>1.9) have the module pickle and cPickle are available</p> <p>Another alternative to JSON serialization is to use the netstring (look on wikipedia) format to serialize. It's actually more effective than JSON for binary objects.</p> <p>You can find a good netstring module here <a href="http://github.com/tuulos/aino/blob/d78c92985ff1d701ddf99c3445b97f452d4f7fe2/wp/node/netstring.py" rel="nofollow">http://github.com/tuulos/aino/blob/d78c92985ff1d701ddf99c3445b97f452d4f7fe2/wp/node/netstring.py</a> (or aino/wp/node/netstring.py)</p>
1
2009-06-08T17:19:45Z
[ "python", "serialization", "pickle", "pys60" ]
How do I add a guard ring to a matrix in NumPy?
362,489
<p>Using <a href="http://numpy.scipy.org/" rel="nofollow">NumPy</a>, a matrix A has n rows and m columns, and I want add a guard ring to matrix A. That guard ring is all zero.</p> <p>What should I do? Use Reshape? But the element is not enough to make a n+1 m+1 matrix.</p> <p>Or etc.?</p> <p>Thanks in advance</p> I mean an extra ring of cells that always contain 0 surround matrix A.Basically there is a Matrix B has n+2rows m+2columns where the first row and columns and the last row and columns are all zero,and the rest of it are same as matrix A.
2
2008-12-12T11:15:15Z
363,040
<p>Following up on your <a href="http://stackoverflow.com/questions/362489/how-do-i-add-a-guard-ring-to-a-matrix-in-numpy#362576">comment</a>: </p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.array(range(9)).reshape((3,3)) &gt;&gt;&gt; b = numpy.zeros(tuple(s+2 for s in a.shape), a.dtype) &gt;&gt;&gt; b[tuple(slice(1,-1) for s in a.shape)] = a &gt;&gt;&gt; b array([[0, 0, 0, 0, 0], [0, 0, 1, 2, 0], [0, 3, 4, 5, 0], [0, 6, 7, 8, 0], [0, 0, 0, 0, 0]]) </code></pre>
6
2008-12-12T15:12:04Z
[ "python", "numpy" ]
How do I add a guard ring to a matrix in NumPy?
362,489
<p>Using <a href="http://numpy.scipy.org/" rel="nofollow">NumPy</a>, a matrix A has n rows and m columns, and I want add a guard ring to matrix A. That guard ring is all zero.</p> <p>What should I do? Use Reshape? But the element is not enough to make a n+1 m+1 matrix.</p> <p>Or etc.?</p> <p>Thanks in advance</p> I mean an extra ring of cells that always contain 0 surround matrix A.Basically there is a Matrix B has n+2rows m+2columns where the first row and columns and the last row and columns are all zero,and the rest of it are same as matrix A.
2
2008-12-12T11:15:15Z
365,974
<p>This is a less general but easier to understand version of <a href="http://stackoverflow.com/questions/362489/how-do-i-add-a-guard-ring-to-a-matrix-in-numpy#363040">Alex's answer</a>:</p> <pre><code>&gt;&gt;&gt; a = numpy.array(range(9)).reshape((3,3)) &gt;&gt;&gt; a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) &gt;&gt;&gt; b = numpy.zeros(a.shape + numpy.array(2), a.dtype) &gt;&gt;&gt; b array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) &gt;&gt;&gt; b[1:-1,1:-1] = a &gt;&gt;&gt; b array([[0, 0, 0, 0, 0], [0, 0, 1, 2, 0], [0, 3, 4, 5, 0], [0, 6, 7, 8, 0], [0, 0, 0, 0, 0]]) </code></pre>
5
2008-12-14T00:10:02Z
[ "python", "numpy" ]
Switching from python-mode.el to python.el
362,522
<p>I recently tried switching from using <code>python-mode.el</code> to <code>python.el</code> for editing python files in emacs, found the experience a little alien and unproductive, and scurried back. I've been using <code>python-mode.el</code> for something like ten years, so perhaps I'm a little set in my ways. I'd be interested in hearing from anyone who's carefully evaluated the two modes, in particular of the pros and cons they perceive of each and how their work generally interacts with the features specific to <code>python.el</code>.</p> <p>The two major issues for me with <code>python.el</code> were </p> <ol> <li><p>Each buffer visiting a python file gets its own inferior interactive python shell. I am used to doing development in one interactive shell and sharing data between python files. (Might seem like bad practice from a software-engineering perspective, but I'm usually working with huge datasets which take a while to load into memory.)</p></li> <li><p>The skeleton-mode support in python.el, which seemed absolutely gratuitous (python's syntax makes such automation unnecessary) and badly designed (for instance, it has no knowledge of "<code>for</code>" loop generator expressions or "<code>&lt;expr 1&gt; if &lt;cond&gt; else &lt;expr 2&gt;</code>" expressions, so you have to go back and remove the colons it helpfully inserts after insisting that you enter the expression clauses in the minibuffer.) I couldn't figure out how to turn it off. There was a <code>python.el</code> variable which claimed to control this, but it didn't seem to work. It could be that the version of <code>python.el</code> I was using was broken (it came from the debian emacs-snapshot package) so if anyone knows of an up-to-date version of it, I'd like to hear about it. (I had the same problem with the version in CVS emacs as of approximately two weeks ago.)</p></li> </ol>
29
2008-12-12T11:37:05Z
362,596
<p>python-mode.el is written by the Python community. python.el is written by the emacs community. I've used python-mode.el for as long as I can remember and python.el doesn't even come close to the standards of python-mode.el. I trust the Python community better than the Emacs community to come up with a decent mode file. Just stick with python-mode.el, is there really a reason not to?</p>
1
2008-12-12T12:20:43Z
[ "python", "emacs", "editing" ]
Switching from python-mode.el to python.el
362,522
<p>I recently tried switching from using <code>python-mode.el</code> to <code>python.el</code> for editing python files in emacs, found the experience a little alien and unproductive, and scurried back. I've been using <code>python-mode.el</code> for something like ten years, so perhaps I'm a little set in my ways. I'd be interested in hearing from anyone who's carefully evaluated the two modes, in particular of the pros and cons they perceive of each and how their work generally interacts with the features specific to <code>python.el</code>.</p> <p>The two major issues for me with <code>python.el</code> were </p> <ol> <li><p>Each buffer visiting a python file gets its own inferior interactive python shell. I am used to doing development in one interactive shell and sharing data between python files. (Might seem like bad practice from a software-engineering perspective, but I'm usually working with huge datasets which take a while to load into memory.)</p></li> <li><p>The skeleton-mode support in python.el, which seemed absolutely gratuitous (python's syntax makes such automation unnecessary) and badly designed (for instance, it has no knowledge of "<code>for</code>" loop generator expressions or "<code>&lt;expr 1&gt; if &lt;cond&gt; else &lt;expr 2&gt;</code>" expressions, so you have to go back and remove the colons it helpfully inserts after insisting that you enter the expression clauses in the minibuffer.) I couldn't figure out how to turn it off. There was a <code>python.el</code> variable which claimed to control this, but it didn't seem to work. It could be that the version of <code>python.el</code> I was using was broken (it came from the debian emacs-snapshot package) so if anyone knows of an up-to-date version of it, I'd like to hear about it. (I had the same problem with the version in CVS emacs as of approximately two weeks ago.)</p></li> </ol>
29
2008-12-12T11:37:05Z
368,719
<p>For what it's worth, I do not see the behavior you are seeing in issue #1, "Each buffer visiting a python file gets its own inferior interactive python shell."</p> <p>This is what I did using python.el from Emacs 22.2.</p> <p>C-x C-f foo.py [insert: print "foo"]</p> <p>C-x C-f bar.py [insert: print "bar"]</p> <p>C-c C-z [*Python* buffer appears]</p> <p>C-x o</p> <p>C-c C-l RET ["bar" is printed in *Python*]</p> <p>C-x b foo.py RET</p> <p>C-c C-l RET ["foo" is printed in the same *Python* buffer]</p> <p>Therefore the two files are sharing the same inferior python shell. Perhaps there is some unforeseen interaction between your personal customizations of python-mode and the default behaviors of python.el. Have you tried using python.el without your .emacs customizations and checking if it behaves the same way?</p> <p>The major feature addition of python.el over python-mode is the symbol completion function python-complete-symbol. You can add something like this</p> <pre><code>(define-key inferior-python-mode-map "\C-c\t" 'python-complete-symbol) </code></pre> <p>Then typing</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.f[C-c TAB] </code></pre> <p>you'll get a *Completions* buffer containing</p> <pre><code>Click &lt;mouse-2&gt; on a completion to select it. In this buffer, type RET to select the completion near point. Possible completions are: os.fchdir os.fdatasync os.fdopen os.fork os.forkpty os.fpathconf os.fstat os.fstatvfs os.fsync os.ftruncate </code></pre> <p>It'll work in .py file buffers too.</p>
4
2008-12-15T15:34:00Z
[ "python", "emacs", "editing" ]
Switching from python-mode.el to python.el
362,522
<p>I recently tried switching from using <code>python-mode.el</code> to <code>python.el</code> for editing python files in emacs, found the experience a little alien and unproductive, and scurried back. I've been using <code>python-mode.el</code> for something like ten years, so perhaps I'm a little set in my ways. I'd be interested in hearing from anyone who's carefully evaluated the two modes, in particular of the pros and cons they perceive of each and how their work generally interacts with the features specific to <code>python.el</code>.</p> <p>The two major issues for me with <code>python.el</code> were </p> <ol> <li><p>Each buffer visiting a python file gets its own inferior interactive python shell. I am used to doing development in one interactive shell and sharing data between python files. (Might seem like bad practice from a software-engineering perspective, but I'm usually working with huge datasets which take a while to load into memory.)</p></li> <li><p>The skeleton-mode support in python.el, which seemed absolutely gratuitous (python's syntax makes such automation unnecessary) and badly designed (for instance, it has no knowledge of "<code>for</code>" loop generator expressions or "<code>&lt;expr 1&gt; if &lt;cond&gt; else &lt;expr 2&gt;</code>" expressions, so you have to go back and remove the colons it helpfully inserts after insisting that you enter the expression clauses in the minibuffer.) I couldn't figure out how to turn it off. There was a <code>python.el</code> variable which claimed to control this, but it didn't seem to work. It could be that the version of <code>python.el</code> I was using was broken (it came from the debian emacs-snapshot package) so if anyone knows of an up-to-date version of it, I'd like to hear about it. (I had the same problem with the version in CVS emacs as of approximately two weeks ago.)</p></li> </ol>
29
2008-12-12T11:37:05Z
1,005,515
<p>python-mode.el has no support triple-quoted strings, so if your program contains long docstrings, all the syntax coloring (and associated syntaxic features) tends to break down.</p> <p>my .02</p>
1
2009-06-17T07:08:48Z
[ "python", "emacs", "editing" ]
Switching from python-mode.el to python.el
362,522
<p>I recently tried switching from using <code>python-mode.el</code> to <code>python.el</code> for editing python files in emacs, found the experience a little alien and unproductive, and scurried back. I've been using <code>python-mode.el</code> for something like ten years, so perhaps I'm a little set in my ways. I'd be interested in hearing from anyone who's carefully evaluated the two modes, in particular of the pros and cons they perceive of each and how their work generally interacts with the features specific to <code>python.el</code>.</p> <p>The two major issues for me with <code>python.el</code> were </p> <ol> <li><p>Each buffer visiting a python file gets its own inferior interactive python shell. I am used to doing development in one interactive shell and sharing data between python files. (Might seem like bad practice from a software-engineering perspective, but I'm usually working with huge datasets which take a while to load into memory.)</p></li> <li><p>The skeleton-mode support in python.el, which seemed absolutely gratuitous (python's syntax makes such automation unnecessary) and badly designed (for instance, it has no knowledge of "<code>for</code>" loop generator expressions or "<code>&lt;expr 1&gt; if &lt;cond&gt; else &lt;expr 2&gt;</code>" expressions, so you have to go back and remove the colons it helpfully inserts after insisting that you enter the expression clauses in the minibuffer.) I couldn't figure out how to turn it off. There was a <code>python.el</code> variable which claimed to control this, but it didn't seem to work. It could be that the version of <code>python.el</code> I was using was broken (it came from the debian emacs-snapshot package) so if anyone knows of an up-to-date version of it, I'd like to hear about it. (I had the same problem with the version in CVS emacs as of approximately two weeks ago.)</p></li> </ol>
29
2008-12-12T11:37:05Z
2,554,201
<ol> <li><p>I can't reproduce this behavior on Emacs v23.1, this must have been changed since then.</p></li> <li><p>Forget about any mode's skeleton support and use the hyper-advanced and extensible <a href="http://code.google.com/p/yasnippet/" rel="nofollow">yasnippet</a> instead, it's really worth a try!</p></li> </ol>
3
2010-03-31T15:24:02Z
[ "python", "emacs", "editing" ]
Switching from python-mode.el to python.el
362,522
<p>I recently tried switching from using <code>python-mode.el</code> to <code>python.el</code> for editing python files in emacs, found the experience a little alien and unproductive, and scurried back. I've been using <code>python-mode.el</code> for something like ten years, so perhaps I'm a little set in my ways. I'd be interested in hearing from anyone who's carefully evaluated the two modes, in particular of the pros and cons they perceive of each and how their work generally interacts with the features specific to <code>python.el</code>.</p> <p>The two major issues for me with <code>python.el</code> were </p> <ol> <li><p>Each buffer visiting a python file gets its own inferior interactive python shell. I am used to doing development in one interactive shell and sharing data between python files. (Might seem like bad practice from a software-engineering perspective, but I'm usually working with huge datasets which take a while to load into memory.)</p></li> <li><p>The skeleton-mode support in python.el, which seemed absolutely gratuitous (python's syntax makes such automation unnecessary) and badly designed (for instance, it has no knowledge of "<code>for</code>" loop generator expressions or "<code>&lt;expr 1&gt; if &lt;cond&gt; else &lt;expr 2&gt;</code>" expressions, so you have to go back and remove the colons it helpfully inserts after insisting that you enter the expression clauses in the minibuffer.) I couldn't figure out how to turn it off. There was a <code>python.el</code> variable which claimed to control this, but it didn't seem to work. It could be that the version of <code>python.el</code> I was using was broken (it came from the debian emacs-snapshot package) so if anyone knows of an up-to-date version of it, I'd like to hear about it. (I had the same problem with the version in CVS emacs as of approximately two weeks ago.)</p></li> </ol>
29
2008-12-12T11:37:05Z
13,267,654
<p>Note nearly everything said here is obsolete meanwhile as things changed.</p> <p>python-mode.el commands are prefixed "py-" basically, you should be able to use commands from both, nonewithstanding which one was loaded first.</p> <p>python-mode.el does not unload python.el; beside of python-mode-map, which is re-defined. </p> <p>The diff is in the menu displayed and keysetting however, the last one loaded will determine.</p>
2
2012-11-07T10:21:47Z
[ "python", "emacs", "editing" ]
django is very slow on my machine
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
12
2008-12-12T13:53:04Z
362,855
<p>Disable AV Scanning &amp; see if that makes a difference. It could also be caused by Vista. Upgrade to the latest service pack and try again. </p>
0
2008-12-12T14:09:54Z
[ "python", "django", "dns" ]
django is very slow on my machine
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
12
2008-12-12T13:53:04Z
362,895
<p>I think it's the development server, it's not optimized for speed nor security. I noticed that specially serving static files (i.e. media) is slow.</p>
2
2008-12-12T14:25:51Z
[ "python", "django", "dns" ]
django is very slow on my machine
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
12
2008-12-12T13:53:04Z
363,563
<p>Since you report your friend's machine has no delays, and I assume yours and his are comparable computers, it could be a DNS related issue. Try to add both the client's and the server's IP address to the server's hosts file.</p> <p>If you run Django on *nix, it's the <code>/etc/hosts</code> file. If run it on MS Windows, it's the <code>%WINDIR%\SYSTEM32\DRIVERS\ETC\HOSTS</code> file. (They are text files and can be edited by your favourite text editor.)</p>
3
2008-12-12T17:41:00Z
[ "python", "django", "dns" ]
django is very slow on my machine
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
12
2008-12-12T13:53:04Z
363,587
<p>And if all else fails, you can always <a href="http://docs.python.org/library/profile.html" rel="nofollow">cProfile</a> your application and see where exactly is the bottleneck.</p>
1
2008-12-12T17:46:33Z
[ "python", "django", "dns" ]
django is very slow on my machine
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
12
2008-12-12T13:53:04Z
368,583
<p>Firefox has a problem browsing to localhost on some Windows machines. You can solve it by switching off ipv6, which isn't really recommended. Using 127.0.0.1 directly is another way round the problem.</p>
17
2008-12-15T14:46:40Z
[ "python", "django", "dns" ]
django is very slow on my machine
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
12
2008-12-12T13:53:04Z
662,541
<p>I have had the same problem in the past. It can be solved by removing the following line from your hosts file.</p> <pre><code>::1 localhost </code></pre> <p>Once that's gone you should be able to use localhost again, quickly.</p>
1
2009-03-19T15:04:52Z
[ "python", "django", "dns" ]
django is very slow on my machine
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
12
2008-12-12T13:53:04Z
2,135,240
<p>Had the same problem too, I've noticed it with Firefox on Vista and Windows 7 machines. Accessing the development server 127.0.0.1:8000 solved the problem.</p>
2
2010-01-25T20:07:24Z
[ "python", "django", "dns" ]
django is very slow on my machine
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
12
2008-12-12T13:53:04Z
2,209,435
<p>To completely bypass localhost without altering the hosts file or any settings in Firefox you can install the addon <a href="https://addons.mozilla.org/en-US/firefox/addon/5064" rel="nofollow">Redirector</a> and make a rule to redirect from localhost to 127.0.0.1. Use these settings</p> <pre><code>Include pattern : http://localhost* Redirect to : http://127.0.0.1$1 </code></pre> <p>Leave the other fields empty.</p>
0
2010-02-05T18:30:11Z
[ "python", "django", "dns" ]
django is very slow on my machine
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
12
2008-12-12T13:53:04Z
7,123,271
<p>None of these posts helped me. In my specific case, <a href="http://www.justincarmony.com/blog/2011/07/27/mac-os-x-lion-etc-hosts-bugs-and-dns-resolution/" rel="nofollow">Justin Carmony</a> gave me the answer.</p> <p><strong>Problem</strong></p> <p>I was mapping [hostname].local to 127.0.0.1 in my /etc/hosts file for easy development purposes and dns requests were taking 5 seconds at to resolve. Sometimes they would resolve quickly, other times they wouldn't.</p> <p><strong>Solution</strong></p> <p>Apple is using .local to do some bonjour magic on newer Snow Leopard builds (I think i started noticing it after updating to 10.6.8) and Mac OS X Lion. If you change your dev hostname to start with local instead of end with local you should be all set. Additionally, you can pretty much use any TLD besides local and it will work without conflict.</p> <p><strong>Example</strong></p> <p>test.local could become:</p> <ul> <li>local.test.com</li> <li>test.dev</li> <li>test.[anything but local]</li> </ul> <p>and your hosts file entry would read:</p> <pre><code>local.test.com 127.0.0.1 </code></pre> <p><em>Note: This solution has the added benefit of being a subdomain of [hostname].com which makes it easier to specify an app domain name for Facebook APIs, etc.</em></p> <p>Might also want to run <code>dscacheutil -flushcache</code> in the terminal for good measure after you update /etc/hosts</p>
6
2011-08-19T14:43:11Z
[ "python", "django", "dns" ]
django is very slow on my machine
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
12
2008-12-12T13:53:04Z
7,158,170
<p>I had the same problem but it was caused by mysqld. </p> <p>The app worked pretty fast on production with wsgi and a mysql server in the same host but slow in the development environtment with the django runserver option and a remote mysql server.</p> <p>I noticed using "show processlist" that connections in database where stuck in the state "login" with user "unauthenticated user" and this make me notice that the problem where in the authentication process.</p> <p>Looking for the real problem, I finally noticed that mysqld was trying to get the dns name of my ip and disabling the name dns resolution, I fixed the problem.</p> <p>To do that, you can add this line into my.cnf file:</p> <blockquote> <p>skip-name-resolve</p> </blockquote>
1
2011-08-23T08:29:06Z
[ "python", "django", "dns" ]
django is very slow on my machine
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
12
2008-12-12T13:53:04Z
7,612,815
<p>i got the same problem.</p> <p>the solution was :</p> <ul> <li>I was trying to start localy a version that was usualy deployed on a webserver in production.</li> <li>The static files in production were served by an apache config and not with django static serve</li> </ul> <p>so I <strong>just uncommented back my static serve urls</strong> :/</p>
0
2011-09-30T15:41:17Z
[ "python", "django", "dns" ]
django is very slow on my machine
362,808
<p>I have a fresh install of django 1.0 and a simple page served from it takes 5 secs to load. On my colleague's computer it takes almost no time.</p> <p>I start the server using </p> <pre> python manage.py testserver </pre> <p>I can see each GET request (PNGs and style sheets) take about half a second.</p> <p>Another weird thing, which I think is related, is that the functional tests for the app run much slower on my machine with MySQL (on order of 100 times slower than on my colleague's machine). When I set the app to use sqlite, they run pretty quickly. I would like to exclaim that sqlite doesn't much change the time it takes to load a page, but it does speed up server startup.</p> <p>It looks like IO problem, but I don't see general performance problems on my machine, apart from django at least.</p> <p>Django runs on python2.4, I'm running Vista. I have also checked python2.5.</p> <p>Thanks ΤΖΩΤΖΙΟΥ, It must totaly be a DNS problem, because the page loads up quickly as soon as instead of <a href="http://localhost:8000/app">http://localhost:8000/app</a> I go to <a href="http://127.0.0.1:8000/app">http://127.0.0.1:8000/app</a>.</p> <p>But what could it be caused by? My host file has only two entries:</p> <pre> 127.0.0.1 localhost ::1 localhost </pre>
12
2008-12-12T13:53:04Z
9,872,341
<p>Upgrade to Django 1.3 or newer.</p> <p>If you still have this problem in 2012 (using Chrome), make sure you're upgrading. In 1.3, a <a href="https://code.djangoproject.com/ticket/16099" rel="nofollow">bug</a> was fixed related to slowness when the dev server was single threaded. </p> <p>Upgrading solved my issues. I was running Django 1.2 since that's the default on Debian Squeeze.</p>
1
2012-03-26T12:43:31Z
[ "python", "django", "dns" ]
Best way to organize the folders containing the SQLAlchemy models
362,998
<p>I use SQLAlchemy at work and it does the job really fine. Now I am thinking about best practices.</p> <p>For now, I create a module holding all the SQLA stuff :</p> <pre><code>my_model |__ __init__.py |__ _config.py &lt;&lt;&lt;&lt;&lt; contains LOGIN, HOST, and a MetaData instance |__ table1.py &lt;&lt;&lt;&lt;&lt; contains the class, the model and the mapper for table1 |__ table2.py &lt;&lt;&lt;&lt;&lt; contains the class, the model and the mapper for table2 [...] </code></pre> <p>Now, I really don't know if it's the best way to do it. I would like to load the classes with a fine granularity and be sure to create one connection only with the db, etc.</p> <p>Here, all the classes are separated, but all import _config and I am wondering if it's a good thing.</p> <p>What's more, I would like to be able to create subclasses of the model classes that could be stored independently without messing up with the mapper every time. How can I do that ? </p> <p>For now I just put them in the same file and I have to create another mapper, but the first mapper is still called every time. The same would go if I'd have to import the parent class because the mapper is triggered at import. If I don't use the class to access data, isn't it overheat to map it each time ?</p> <p>I'd like to avoid using Elixir too, please.</p>
6
2008-12-12T15:02:25Z
403,362
<p>Personally I like to keep the database / ORM logic out of the model classes. It makes them easier to test. I typically have something like a <code>types.py</code> which defines the types used in my application, but independent of the database.</p> <p>Then typically there is a <code>db.py</code> or something similar which has the <code>Session</code> class and the rest of the code required to set up the database, including all the mappers etc.</p> <p>None of the other modules except those which perform database operations need to import the <code>db</code> module and the existence of the database is totally hidden from most of the application classes.</p> <p>As far as I know, you can't easily make subclasses without changing the mapper. SQLAlchemy will have no way to know which subclass to retrieve from the database when you perform a query and you need to be able to indicate the subclass when you are storing the data anyway.</p> <p>I haven't really seen any problems arise from calling all the mappers at once from the main <code>db</code> module, so I don't think initializing them all the time is really a concern unless you actually identify it as a bottleneck. In my experience, other processing is a far larger factor than the minor mapper overhead.</p>
3
2008-12-31T16:21:32Z
[ "python", "orm", "sqlalchemy" ]
Regex Problem Group Name Redefinition?
363,171
<p>So I have this regex:</p> <pre><code>(^(\s+)?(?P&lt;NAME&gt;(\w)(\d{7}))((01f\.foo)|(\.bar|\.goo\.moo\.roo))$|(^(\s+)?(?P&lt;NAME2&gt;R1_\d{6}_\d{6}_)((01f\.foo)|(\.bar|\.goo\.moo\.roo))$)) </code></pre> <p>Now if I try and do a match against this:</p> <pre> B048661501f.foo </pre> <p>I get this error:</p> <pre> File "C:\Python25\lib\re.py", line 188, in compile return _compile(pattern, flags) File "C:\Python25\lib\re.py", line 241, in _compile raise error, v # invalid expression sre_constants.error: redefinition of group name 'NAME' as group 9; was group 3 </pre> <p>If I can't define the same group twice in the same regex expression for two different cases, what do I do?</p>
4
2008-12-12T15:58:50Z
363,264
<p>No, you can't have two groups of the same name, this would somehow defy the purpose, wouldn't it?</p> <p>What you probably <em>really</em> want is this:</p> <pre><code>^\s*(?P&lt;NAME&gt;\w\d{7}|R1_(?:\d{6}_){2})(01f\.foo|\.(?:bar|goo|moo|roo))$ </code></pre> <p>I refactored your regex as far as possible. I made the following assumptions:</p> <p>You want to (correct me if I'm wrong):</p> <ul> <li>ignore white space at the start of the string</li> <li>match either of the following into a group named "NAME": <ul> <li>a letter followed by 7 digits, or</li> <li><code>"R1_"</code>, and two times (6 digits + <code>"_"</code>)</li> </ul></li> <li>followed by either: <ul> <li><code>"01f.foo"</code> or</li> <li><code>"."</code> and (<code>"bar"</code> or <code>"goo"</code> or <code>"moo"</code> or <code>"roo"</code>)</li> </ul></li> <li>followed by the end of the string</li> </ul> <p><hr /></p> <p>You could also have meant:</p> <pre><code>^\s*(?P&lt;NAME&gt;\w\d{7}01f|R1_(?:\d{6}_){2})\.(?:foo|bar|goo|moo|roo)$ </code></pre> <p>Which is:</p> <ul> <li>ignore white space at the start of the string</li> <li>match either of the following into a group named "NAME": <ul> <li>a letter followed by 7 digits and "01f"</li> <li><code>"R1_"</code>, and two times (6 digits + <code>"_"</code>)</li> </ul></li> <li>a dot</li> <li><code>"foo"</code>, <code>"bar"</code>, <code>"goo"</code>, <code>"moo"</code> or <code>"roo"</code></li> <li>the end of the string</li> </ul>
6
2008-12-12T16:27:22Z
[ "python", "regex" ]
Regex Problem Group Name Redefinition?
363,171
<p>So I have this regex:</p> <pre><code>(^(\s+)?(?P&lt;NAME&gt;(\w)(\d{7}))((01f\.foo)|(\.bar|\.goo\.moo\.roo))$|(^(\s+)?(?P&lt;NAME2&gt;R1_\d{6}_\d{6}_)((01f\.foo)|(\.bar|\.goo\.moo\.roo))$)) </code></pre> <p>Now if I try and do a match against this:</p> <pre> B048661501f.foo </pre> <p>I get this error:</p> <pre> File "C:\Python25\lib\re.py", line 188, in compile return _compile(pattern, flags) File "C:\Python25\lib\re.py", line 241, in _compile raise error, v # invalid expression sre_constants.error: redefinition of group name 'NAME' as group 9; was group 3 </pre> <p>If I can't define the same group twice in the same regex expression for two different cases, what do I do?</p>
4
2008-12-12T15:58:50Z
14,286,839
<p>Reusing the same name makes sense in your case, contrary to Tamalak's reply.</p> <p>Your regex compiles with python2.7 and also re2. Maybe this problem has been resolved.</p>
6
2013-01-11T21:21:35Z
[ "python", "regex" ]
Equivalent of an HTML multiple SELECT box in wxPython
363,907
<p>I'd like to create a <code>ListBox</code> in wxPython with the same semantics as a multiple <code>select</code> box in HTML. Specifically I'd like the following semantics</p> <ul> <li> When the user clicks on an entry in the list, all other entries become de-selected and the clicked entry becomes selected. If the entry was already selected then it stays selected. </li> <li> When the user holds down the Ctrl key while clicking on an entry, all other entries stay unchanged, but it toggles whether the clicked entry is selected. </li> <li> When the user holds down shift and clicks on an entry, that entry and every entry between it and the last clicked entry become selected. </li> </ul> <p>In Java I get this by using the <code>JList</code> class in Swing and setting the selection mode to <code>MULTIPLE_INTERVAL_SELECTED</code>. I assume that there's a way to do this with the wxPython toolkit, but I can't figure out how to get a <code>ListBox</code> or <code>ListCtrl</code> or any other class to do this short of doing an enormous amount of event-driven programming myself.</p>
3
2008-12-12T19:45:11Z
363,918
<p>I think what you're looking for is the <a href="http://docs.wxwidgets.org/2.6/wx_wxlistbox.html" rel="nofollow">wxLB_EXTENDED</a> list box style. Specify <code>style = wx.LB_EXTENDED</code> when you create the <code>ListBox</code>.</p> <p>You can then use the <code>GetSelections</code> method to obtain a list of the selected items.</p>
3
2008-12-12T19:49:51Z
[ "python", "wxpython" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
363,955
<pre><code>(get_list() or [None])[0] </code></pre> <p>That should work.</p> <p>BTW I didn't use the variable <code>list</code>, because that overwrites the builtin <code>list()</code> function.</p> <p>Edit: I had a slightly simpler, but wrong version here earlier.</p>
35
2008-12-12T20:00:03Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
363,984
<p>You could use <a href="http://www.refactoring.com/catalog/extractMethod.html" rel="nofollow">Extract Method</a>. In other words extract that code into a method which you'd then call.</p> <p>I wouldn't try to compress it much more, the one liners seem harder to read than the verbose version. And if you use Extract Method, it's a one liner ;)</p>
-1
2008-12-12T20:10:04Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
363,995
<p>The best way is this:</p> <pre><code>a = get_list() return a[0] if a else None </code></pre> <p>You could also do it in one line, but it's much harder for the programmer to read:</p> <pre><code>return (get_list()[:1] or [None])[0] </code></pre>
134
2008-12-12T20:12:27Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
364,048
<pre><code>try: return a[0] except IndexError: return None </code></pre>
0
2008-12-12T20:30:19Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
364,244
<p>For the heck of it, here's yet another possibility.</p> <pre><code>return None if not get_list() else get_list()[0] </code></pre> <p>Benefit: This method handles the case where get_list is None, without using try/except or assignment. To my knowledge, none of the implementations above can handle this possibility</p> <p>Downfalls: get_list() is called twice, quite unnecessarily, especially if the list is long and/or created when the function is called.</p> <p>The truth is, it's more "Pythonic" in my opinion, to provide code that is readable than it is to make a one-liner just because you can :) I have to admit I am guilty many times of unnecessarily compacting Python code just because I'm so impressed how small I can make a complex function look :)</p> <p>Edit: As user "hasen j" commented below, the conditional expression above is new in Python 2.5, as described here: <a href="https://docs.python.org/whatsnew/2.5.html#pep-308" rel="nofollow">https://docs.python.org/whatsnew/2.5.html#pep-308</a>. Thanks, hasen!</p>
2
2008-12-12T21:48:11Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
364,249
<pre><code>for item in get_list(): return item </code></pre>
3
2008-12-12T21:48:57Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
364,274
<p>isn't the idiomatic python equivalent to C-style ternary operators </p> <pre><code>cond and true_expr or false_expr </code></pre> <p>ie. </p> <pre><code>list = get_list() return list and list[0] or None </code></pre>
-2
2008-12-12T21:55:53Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
364,405
<p>The OP's solution is nearly there, there are just a few things to make it more Pythonic.</p> <p>For one, there's no need to get the length of the list. Empty lists in Python evaluate to False in an if check. Just simply say</p> <pre><code>if list: </code></pre> <p>Additionally, it's a very Bad Idea to assign to variables that overlap with reserved words. "list" is a reserved word in Python.</p> <p>So let's change that to</p> <pre><code>some_list = get_list() if some_list: </code></pre> <p>A really important point that a lot of solutions here miss is that <strong>all Python functions/methods return None by default</strong>. Try the following below.</p> <pre><code>def does_nothing(): pass foo = does_nothing() print foo </code></pre> <p>Unless you need to return None to terminate a function early, it's unnecessary to explicitly return None. Quite succinctly, just return the first entry, should it exist.</p> <pre><code>some_list = get_list() if some_list: return list[0] </code></pre> <p>And finally, perhaps this was implied, but just to be explicit (because <a href="http://www.python.org/dev/peps/pep-0020/">explicit is better than implicit</a>), you should not have your function get the list from another function; just pass it in as a parameter. So, the final result would be</p> <pre><code>def get_first_item(some_list): if some_list: return list[0] my_list = get_list() first_item = get_first_item(my_list) </code></pre> <p>As I said, the OP was nearly there, and just a few touches give it the Python flavor you're looking for.</p>
9
2008-12-12T22:41:48Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
364,470
<p>Frankly speaking, I do not think there is a better idiom: your is clear and terse - no need for anything "better". Maybe, but this is really a matter of taste, you could change <code>if len(list) &gt; 0:</code> with <code>if list:</code> - an empty list will always evaluate to False.</p> <p>On a related note, Python is <strong>not</strong> Perl (no pun intended!), you do not have to get the coolest code possible.<br> Actually, the worst code I have seen in Python, was also very cool :-) and completely unmaintainable.</p> <p>By the way, most of the solution I have seen here do not take into consideration when list[0] evaluates to False (e.g. empty string, or zero) - in this case, they all return None and not the correct element.</p>
1
2008-12-12T23:14:19Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
364,511
<p>Using the and-or trick:</p> <pre><code>a = get_list() return a and a[0] or None</code></pre>
-1
2008-12-12T23:48:00Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
364,570
<p>Several people have suggested doing something like this:</p> <pre><code>list = get_list() return list and list[0] or None </code></pre> <p>That works in many cases, but it will only work if list[0] is not equal to 0, False, or an empty string. If list[0] is 0, False, or an empty string, the method will incorrectly return None.</p> <p>(I've created this bug in my own code one too many times!)</p>
-1
2008-12-13T00:35:13Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
365,934
<pre><code>def get_first(iterable, default=None): if iterable: for item in iterable: return item return default </code></pre> <p>Example:</p> <pre><code>x = get_first(get_first_list()) if x: ... y = get_first(get_second_list()) if y: ... </code></pre> <p>Another option is to inline the above function:</p> <pre><code>for x in get_first_list() or []: # process x break # process at most one item for y in get_second_list() or []: # process y break </code></pre> <p>To avoid <code>break</code> you could write:</p> <pre><code>for x in yield_first(get_first_list()): x # process x for y in yield_first(get_second_list()): y # process y </code></pre> <p>Where:</p> <pre><code>def yield_first(iterable): for item in iterable or []: yield item return </code></pre>
32
2008-12-13T23:31:55Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
370,621
<p>Out of curiosity, I ran timings on two of the solutions. The solution which uses a return statement to prematurely end a for loop is slightly more costly on my machine with Python 2.5.1, I suspect this has to do with setting up the iterable.</p> <pre><code>import random import timeit def index_first_item(some_list): if some_list: return some_list[0] def return_first_item(some_list): for item in some_list: return item empty_lists = [] for i in range(10000): empty_lists.append([]) assert empty_lists[0] is not empty_lists[1] full_lists = [] for i in range(10000): full_lists.append(list([random.random() for i in range(10)])) mixed_lists = empty_lists[:50000] + full_lists[:50000] random.shuffle(mixed_lists) if __name__ == '__main__': ENV = 'import firstitem' test_data = ('empty_lists', 'full_lists', 'mixed_lists') funcs = ('index_first_item', 'return_first_item') for data in test_data: print "%s:" % data for func in funcs: t = timeit.Timer('firstitem.%s(firstitem.%s)' % ( func, data), ENV) times = t.repeat() avg_time = sum(times) / len(times) print " %s:" % func for time in times: print " %f seconds" % time print " %f seconds avg." % avg_time </code></pre> <p>These are the timings I got:</p> <pre> empty_lists: index_first_item: 0.748353 seconds 0.741086 seconds 0.741191 seconds 0.743543 seconds avg. return_first_item: 0.785511 seconds 0.822178 seconds 0.782846 seconds 0.796845 seconds avg. full_lists: index_first_item: 0.762618 seconds 0.788040 seconds 0.786849 seconds 0.779169 seconds avg. return_first_item: 0.802735 seconds 0.878706 seconds 0.808781 seconds 0.830074 seconds avg. mixed_lists: index_first_item: 0.791129 seconds 0.743526 seconds 0.744441 seconds 0.759699 seconds avg. return_first_item: 0.784801 seconds 0.785146 seconds 0.840193 seconds 0.803380 seconds avg. </pre>
1
2008-12-16T07:07:33Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
371,270
<pre><code>def head(iterable): try: return iter(iterable).next() except StopIteration: return None print head(xrange(42, 1000) # 42 print head([]) # None </code></pre> <p>BTW: I'd rework your general program flow into something like this:</p> <pre><code>lists = [ ["first", "list"], ["second", "list"], ["third", "list"] ] def do_something(element): if not element: return else: # do something pass for li in lists: do_something(head(li)) </code></pre> <p>(Avoiding repetition whenever possible)</p>
0
2008-12-16T13:17:12Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
15,665,310
<p>And what about: <code>next(iter(get_list()), None)</code>? Might not be the fastest one here, but is standard (starting from Python 2.6) and succinct.</p>
-1
2013-03-27T17:21:42Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
21,560,637
<p>Probably not the fastest solution, but nobody mentioned this option:</p> <pre><code>dict(enumerate(get_list())).get(0) </code></pre> <p>if <code>get_list()</code> can return <code>None</code> you can use:</p> <pre><code>dict(enumerate(get_list() or [])).get(0) </code></pre> <p>Advantages:</p> <p>-one line</p> <p>-you just call <code>get_list()</code> once</p> <p>-easy to understand</p>
-1
2014-02-04T18:37:07Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
25,398,201
<p>The most python idiomatic way is to use the next() on a iterator since list is <em>iterable</em>. just like what @J.F.Sebastian put in the comment on Dec 13, 2011.</p> <p><code>next(iter(the_list), None)</code> This returns None if <code>the_list</code> is empty. see <a href="https://docs.python.org/2/library/functions.html#next">next() Python 2.6+ </a></p> <p>or if you know for sure <code>the_list</code> is not empty:</p> <p><code>iter(the_list).next()</code> see <a href="https://docs.python.org/2/library/stdtypes.html#iterator.next">iterator.next() Python 2.2+ </a></p>
20
2014-08-20T06:36:29Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
31,097,387
<p>How about this:</p> <p><code>(my_list and my_list[0]) or None</code></p>
2
2015-06-28T07:57:26Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
31,487,813
<blockquote> <p><strong>Python idiom to return first item or None?</strong></p> </blockquote> <p>The most Pythonic approach is what the most upvoted answer demonstrated, and it was the first thing to come to my mind when I read the question. Here's how to use it, first if the possibly empty list is passed into a function:</p> <pre><code>def get_first(l): return l[0] if l else None </code></pre> <p>And if the list is returned from a <code>get_list</code> function:</p> <pre><code>l = get_list() return l[0] if l else None </code></pre> <h2>Other ways demonstrated to do this here, with explanations</h2> <h3><code>for</code></h3> <p>When I began trying to think of clever ways to do this, this is the second thing I thought of:</p> <pre><code>for item in get_list(): return item </code></pre> <p>This presumes the function ends here, implicitly returning <code>None</code> if <code>get_list</code> returns an empty list. The below explicit code is exactly equivalent:</p> <pre><code>for item in get_list(): return item return None </code></pre> <h3><code>if some_list</code></h3> <p>The following was also proposed (I corrected the incorrect variable name) which also uses the implicit <code>None</code>. This would be preferable to the above, as it uses the logical check instead of an iteration that may not happen. This should be easier to understand immediately what is happening. But if we're writing for readability and maintainability, we should also add the explicit <code>return None</code> at the end:</p> <pre><code>some_list = get_list() if some_list: return some_list[0] </code></pre> <h3>slice <code>or [None]</code> and select zeroth index</h3> <p>This one is also in the most up-voted answer:</p> <pre><code>return (get_list()[:1] or [None])[0] </code></pre> <p>The slice is unnecessary, and creates an extra one-item list in memory. The following should be more performant. To explain, <code>or</code> returns the second element if the first is <code>False</code> in a boolean context, so if <code>get_list</code> returns an empty list, the expression contained in the parentheses will return a list with 'None', which will then be accessed by the <code>0</code> index:</p> <pre><code>return (get_list() or [None])[0] </code></pre> <p>The next one uses the fact that and returns the second item if the first is <code>True</code> in a boolean context, and since it references my_list twice, it is no better than the ternary expression (and technically not a one-liner):</p> <pre><code>my_list = get_list() return (my_list and my_list[0]) or None </code></pre> <h3><code>next</code></h3> <p>Then we have the following clever use of the builtin <code>next</code> and <code>iter</code></p> <pre><code>return next(iter(get_list()), None) </code></pre> <p>To explain, <code>iter</code> returns an iterator with a <code>.next</code> method. (<code>.__next__</code> in Python 3.) Then the builtin <code>next</code> calls that <code>.next</code> method, and if the iterator is exhausted, returns the default we give, <code>None</code>.</p> <h3>redundant ternary expression (<code>a if b else c</code>) and circling back</h3> <p>The below was proposed, but the inverse would be preferable, as logic is usually better understood in the positive instead of the negative. Since <code>get_list</code> is called twice, unless the result is memoized in some way, this would perform poorly:</p> <pre><code>return None if not get_list() else get_list()[0] </code></pre> <p>The better inverse:</p> <pre><code>return get_list()[0] if get_list() else None </code></pre> <p>Even better, use a local variable so that <code>get_list</code> is only called one time, and you have the recommended Pythonic solution first discussed:</p> <pre><code>l = get_list() return l[0] if l else None </code></pre>
2
2015-07-18T04:33:11Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
31,510,450
<p>My use case was only to set the value of a local variable.</p> <p>Personally I found the try and except style cleaner to read</p> <pre><code>items = [10, 20] try: first_item = items[0] except IndexError: first_item = None print first_item </code></pre> <p>than slicing a list.</p> <pre><code>items = [10, 20] first_item = (items[:1] or [None, ])[0] print first_item </code></pre>
-1
2015-07-20T07:00:51Z
[ "python", "idioms", "python-2.4" ]
Python idiom to return first item or None
363,944
<p>I'm sure there's a simpler way of doing this that's just not occurring to me.</p> <p>I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:</p> <pre><code>my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None </code></pre> <p>It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?</p> <p><strong>Edit:</strong></p> <p>The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:</p> <pre><code>x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix </code></pre> <p>What I'd like to be doing can certainly be accomplished with a function (and probably will be):</p> <pre><code>def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y </code></pre> <p>I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function <em>is</em> the simple solution.</p>
110
2008-12-12T19:56:02Z
35,702,414
<p>If you find yourself trying to pluck the first thing (or None) from a list comprehension you can switch to a generator to do it like:</p> <pre><code>next((x for x in blah if cond), None) </code></pre> <p>Pro: works if blah isn't indexable Con: it's unfamiliar syntax. It's useful while hacking around and filtering stuff in ipython though.</p>
4
2016-02-29T14:43:44Z
[ "python", "idioms", "python-2.4" ]
Best way to monitor services on a few servers with python
363,968
<p>What would be the best way to monitor services like HTTP/FTP/IMAP/POP3/SMTP for a few servers from python? Using sockets and trying to connect to service port http-80, ftp-21, etc... and if connection successful assume service is ok or use python libs to connect to specified services and handle exceptions/return codes/etc...</p> <p>For example for ftp is it better to</p> <pre><code>import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(("ftp.domain.tld", 21)) print "ok" except: print "failed" s.close() </code></pre> <p>or to</p> <pre><code>from ftplib import FTP try: ftp = FTP('ftp.domain.tld') print "FTP service OK" ftp.close() except: print "FTP err" </code></pre> <p>same goes for the rest, socket vs urllib2, imaplib, etc... and if i go the lib way how do i test for smtp?</p>
1
2008-12-12T20:02:13Z
364,021
<p><strong>update 1:</strong></p> <p>Actually, In your code there is no difference between the two option ( in FTP ). The second option should be Preferred for code readability. But way not login to the ftp server, And maybe read some file?</p> <p><strong>update 0:</strong></p> <p>When monitoring, testing the full stack is better. Because otherwise you can miss problems that don't manifest themselves in the socket level. The smtp can be tested with the smtplib. The best way is actually send mail with it. And read it from the target with the imaplib. Or, You can just use the smtplib to converse with the smtp server. It is better to do the whole end to end thing. But development and configuration resources should be considered against the impact of missing problems.</p>
2
2008-12-12T20:23:45Z
[ "python" ]