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
listlengths
1
5
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
18,252,518
<p>A 0-d array of None looks like None but it is not the same:</p> <pre><code>In [1]: print None None In [2]: import numpy In [3]: print numpy.array(None) None In [4]: numpy.array(None) is None Out[4]: False In [5]: numpy.array(None) == None Out[5]: False In [6]: print repr(numpy.array(None)) array(None, dtype=object) </code></pre>
1
2013-08-15T12:21:21Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
28,183,264
<p>A surprise with the <code>*=</code> assignment in combination with <code>numpy.array</code>:</p> <pre><code>&gt;&gt;&gt; from numpy import array &gt;&gt;&gt; a = array([1, 2, 3]) &gt;&gt;&gt; a *= 1.1 &gt;&gt;&gt; print(a) [1 2 3] # not quite what we expect or would like to see &gt;&gt;&gt; print(a.dtype) int64 # and this is why &gt;&gt;&gt; a = 1.1 * a # here, a new array is created &gt;&gt;&gt; print(a, a.dtype) [ 1.1 2.2 3.3] float64 # with the expected outcome </code></pre> <p>Surprising, annoying, but understandable. The <code>*=</code> operator will not change the type of the <code>array</code> data, thereby multiplication of an <code>int</code> <code>array</code> by a <code>float</code> will fail in the conventional meaning of this multiplication. The Python version <code>a = 1; a *= 1.1</code> in the other hand works as expected.</p>
2
2015-01-28T01:43:25Z
[ "python", "numpy" ]
Django Admin - Bulk editing data?
1,322,425
<p>Are there any admin extensions to let bulk editing data in Django Admin? (ie. Changing the <em>picture</em> fields of all <em>product</em> models at once. Note that this is needed for a users POV so scripting doesn't count.) Any thoughts on subject welcome.</p>
3
2009-08-24T13:30:04Z
1,322,450
<p>You have SQL. You can write SQL UPDATE statements.</p> <p>You have Python for writing batch scripts that interact with the Django ORM. This works really, really well for bulk changes.</p>
-1
2009-08-24T13:33:31Z
[ "python", "django", "django-models", "django-admin" ]
Django Admin - Bulk editing data?
1,322,425
<p>Are there any admin extensions to let bulk editing data in Django Admin? (ie. Changing the <em>picture</em> fields of all <em>product</em> models at once. Note that this is needed for a users POV so scripting doesn't count.) Any thoughts on subject welcome.</p>
3
2009-08-24T13:30:04Z
1,322,459
<p>With Django 1.1, you can create admin actions which can be applied to multiple entries at once. See <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#ref-contrib-admin-actions">the documentation</a> on this subject.</p>
8
2009-08-24T13:34:59Z
[ "python", "django", "django-models", "django-admin" ]
Django Admin - Bulk editing data?
1,322,425
<p>Are there any admin extensions to let bulk editing data in Django Admin? (ie. Changing the <em>picture</em> fields of all <em>product</em> models at once. Note that this is needed for a users POV so scripting doesn't count.) Any thoughts on subject welcome.</p>
3
2009-08-24T13:30:04Z
6,698,899
<p><a href="http://algoholic.eu/django-mass-change-admin-site-extension/" rel="nofollow">Django "Mass Change" Admin Site Extension</a>.</p>
4
2011-07-14T19:32:00Z
[ "python", "django", "django-models", "django-admin" ]
python time format check
1,322,464
<p>I want to check if the input string is in "HH:MM" such as 01:16 or 23:16 or 24:00. Giving true or false by the result.</p> <p>How can I achieve this by using regular expression ?</p>
5
2009-08-24T13:36:10Z
1,322,524
<p>You can achieve this without regular expressions:</p> <pre><code>import time def isTimeFormat(input): try: time.strptime(input, '%H:%M') return True except ValueError: return False &gt;&gt;&gt;isTimeFormat('12:12') True &gt;&gt;&gt;isTimeFormat('012:12') False </code></pre>
14
2009-08-24T13:45:51Z
[ "python", "regex" ]
python time format check
1,322,464
<p>I want to check if the input string is in "HH:MM" such as 01:16 or 23:16 or 24:00. Giving true or false by the result.</p> <p>How can I achieve this by using regular expression ?</p>
5
2009-08-24T13:36:10Z
1,322,529
<p>This will give you the regexp object which will check it. However, depending on who you ask 24:00 might not be a valid time (it's 00:00). But I guess this is easy to modify to suit your needs.</p> <pre><code>import re regexp = re.compile("(24:00|2[0-3]:[0-5][0-9]|[0-1][0-9]:[0-5][0-9])") </code></pre>
1
2009-08-24T13:46:20Z
[ "python", "regex" ]
python time format check
1,322,464
<p>I want to check if the input string is in "HH:MM" such as 01:16 or 23:16 or 24:00. Giving true or false by the result.</p> <p>How can I achieve this by using regular expression ?</p>
5
2009-08-24T13:36:10Z
1,322,532
<pre><code>import re time_re = re.compile(r'^(([01]\d|2[0-3]):([0-5]\d)|24:00)$') def is_time_format(s): return bool(time_re.match(s)) </code></pre> <p>Matches everything from 00:00 to 24:00.</p>
2
2009-08-24T13:46:31Z
[ "python", "regex" ]
python time format check
1,322,464
<p>I want to check if the input string is in "HH:MM" such as 01:16 or 23:16 or 24:00. Giving true or false by the result.</p> <p>How can I achieve this by using regular expression ?</p>
5
2009-08-24T13:36:10Z
1,322,533
<p>This patters will help you: <a href="http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&amp;categoryId=5" rel="nofollow">http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&amp;categoryId=5</a></p> <p>BTW, you should use google before asking this kind of questions...</p>
3
2009-08-24T13:46:40Z
[ "python", "regex" ]
Python - How to edit hexadecimal file byte by byte
1,322,508
<p>I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library i need to use, specific methods i can google, or tutorials/guides?</p>
5
2009-08-24T13:42:53Z
1,322,542
<p>The Hachoir framework is a set of Python library and tools to parse and edit binary files:</p> <p><a href="http://pypi.python.org/pypi/hachoir-core" rel="nofollow">http://pypi.python.org/pypi/hachoir-core</a></p> <p>It has knowledge of common file types, so this could just be what you need.</p>
4
2009-08-24T13:47:51Z
[ "python", "byte", "hex", "filereader" ]
Python - How to edit hexadecimal file byte by byte
1,322,508
<p>I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library i need to use, specific methods i can google, or tutorials/guides?</p>
5
2009-08-24T13:42:53Z
1,322,570
<p>Python standard library has mmap module, which can be used to do exactly this. Take a look on <a href="http://docs.python.org/library/mmap.html">the documentation</a> for further information.</p>
7
2009-08-24T13:50:13Z
[ "python", "byte", "hex", "filereader" ]
Python - How to edit hexadecimal file byte by byte
1,322,508
<p>I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library i need to use, specific methods i can google, or tutorials/guides?</p>
5
2009-08-24T13:42:53Z
1,322,579
<p>Depending on what you want to do it might be enough to <a href="http://docs.python.org/library/functions.html#open" rel="nofollow">open the file in binary mode</a> and read the data with the normal <a href="http://docs.python.org/library/stdtypes.html#bltin-file-objects" rel="nofollow">file</a> functions:</p> <pre><code># load it f = open("somefile", 'rb') data = f.read() f.close() # do something with data data.reverse() # save it f = open("somefile.new", 'wb') f.write(data) f.close() </code></pre> <p>Python doesn't really care if the <code>data</code> string contains "binary" or "text" data. If you just want to do simple modifications to a file of reasonable size this is probably good enough.</p>
9
2009-08-24T13:51:39Z
[ "python", "byte", "hex", "filereader" ]
Python - How to edit hexadecimal file byte by byte
1,322,508
<p>I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library i need to use, specific methods i can google, or tutorials/guides?</p>
5
2009-08-24T13:42:53Z
1,323,602
<p>Check out the <a href="http://docs.python.org/library/struct.html" rel="nofollow">stuct</a> module.</p> <blockquote> <p>This module performs conversions between Python values and C structs represented as Python strings. It uses format strings (explained below) as compact descriptions of the lay-out of the C structs and the intended conversion to/from Python values. This can be used in handling binary data stored in files or from network connections, among other sources.</p> </blockquote>
1
2009-08-24T17:09:37Z
[ "python", "byte", "hex", "filereader" ]
Ipython common problems
1,322,569
<p>I love iPython's so many features, magic functions.</p> <p>I recently upgraded to the latest 0.10 version. But I face following common problems:</p> <ul> <li><code>%hist</code> one of the most frequently used magic functions, doesn't exist.</li> <li><code>dreload</code> doesn't seems to work (works only for modules?).</li> <li><code>run -d</code> for debugging doesn't work</li> <li>At times, typed characters are not displayed on the console*</li> <li>By default even the ? and ?? didn't work. I had to hack for that to work*</li> </ul> <p>*The last 2 problems are true for the previous versions too.</p> <p>I am on Ubuntu 9.04 with Python 2.6.2 and IPython 0.10</p>
2
2009-08-24T13:50:06Z
1,322,837
<p>sounds like an issue with your particular setup. ? and ?? have always worked on my machine, hist is still a magic function, and dreload has always only worked for modules--what else would it do?</p> <p>as for the debug thing, it's a known issue with python 2.6: <a href="https://bugs.launchpad.net/ipython/+bug/381069" rel="nofollow">https://bugs.launchpad.net/ipython/+bug/381069</a></p>
1
2009-08-24T14:46:39Z
[ "python", "django", "command-line", "ipython" ]
What numbers can you pass as verbosity in running Python Unit Test Suites?
1,322,575
<p>The Python unittest framework has a concept of verbosity that I can't seem to find defined anywhere. For instance, I'm running test cases like this (<a href="http://docs.python.org/library/unittest.html#basic-example">like in the documentation</a>):</p> <pre><code>suite = unittest.TestLoader().loadTestsFromTestCase(MyAwesomeTest) unittest.TextTestRunner(verbosity=2).run(suite) </code></pre> <p>The only number I've ever seen passed as verbosity is 2. What is this magic number, what does it mean, what what else can I pass?</p>
26
2009-08-24T13:51:20Z
1,322,648
<p>You only have 3 different levels:</p> <ul> <li>0 <strong><em>(quiet)</em></strong>: you just get the total numbers of tests executed and the global result</li> <li>1 <strong><em>(default)</em></strong>: you get the same plus a dot for every successful test or a F for every failure</li> <li>2 <strong><em>(verbose)</em></strong>: you get the help string of every test and the result</li> </ul> <p>You can use command line args rather than the verbosity argument: <code>--quiet</code> and <code>--verbose</code> which would do something similar to passing 0 or 2 to the runner.</p>
43
2009-08-24T14:08:36Z
[ "python", "unit-testing", "verbosity" ]
What would be the best way to use python's functions from excel?
1,322,787
<p><em>Somebody really needs to fix this "subjective questions evaluator"</em></p> <p>I usually compile my functions in a DLL and call them from excel. That works fine (well, let's just say it works)</p> <p>Unfortunatelly, python cannot be compiled. I know of py2exe but I don't know that it can make a DLL.</p> <p>So, ..., is there any other way ? I appreciate all ideas and suggestions on the matter.</p>
3
2009-08-24T14:37:40Z
1,322,962
<p>One way is to write a COM server in Python, and call that from Excel. There are tutorials describing <a href="http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/QuickStartServerCom.html">Win32 COM servers</a>, and <a href="http://showmedo.com/videotutorials/video?name=2190050&amp;fromSeriesID=219">screencasts on calling such servers from Excel</a>.</p>
6
2009-08-24T15:08:42Z
[ "python", "excel" ]
What would be the best way to use python's functions from excel?
1,322,787
<p><em>Somebody really needs to fix this "subjective questions evaluator"</em></p> <p>I usually compile my functions in a DLL and call them from excel. That works fine (well, let's just say it works)</p> <p>Unfortunatelly, python cannot be compiled. I know of py2exe but I don't know that it can make a DLL.</p> <p>So, ..., is there any other way ? I appreciate all ideas and suggestions on the matter.</p>
3
2009-08-24T14:37:40Z
1,322,983
<p>I don't know any py2dll similar to py2exe.</p> <p>However, you could create a dll in C and use the <a href="http://docs.python.org/c-api/veryhigh.html" rel="nofollow">Very High Level Layer</a> to call your script. I don't know it is an acceptable solution for you. Just an idea. </p>
0
2009-08-24T15:12:57Z
[ "python", "excel" ]
What would be the best way to use python's functions from excel?
1,322,787
<p><em>Somebody really needs to fix this "subjective questions evaluator"</em></p> <p>I usually compile my functions in a DLL and call them from excel. That works fine (well, let's just say it works)</p> <p>Unfortunatelly, python cannot be compiled. I know of py2exe but I don't know that it can make a DLL.</p> <p>So, ..., is there any other way ? I appreciate all ideas and suggestions on the matter.</p>
3
2009-08-24T14:37:40Z
1,323,280
<p>This is probably not a possible solution for you, but there is the <a href="http://www.resolversystems.com/products/resolver-one/" rel="nofollow">Resolver One</a> spreadsheet application (which is like Excel combined with Python). It is not connected with Excel in any way, but claims to be compatible to some extent.</p>
4
2009-08-24T16:07:51Z
[ "python", "excel" ]
What would be the best way to use python's functions from excel?
1,322,787
<p><em>Somebody really needs to fix this "subjective questions evaluator"</em></p> <p>I usually compile my functions in a DLL and call them from excel. That works fine (well, let's just say it works)</p> <p>Unfortunatelly, python cannot be compiled. I know of py2exe but I don't know that it can make a DLL.</p> <p>So, ..., is there any other way ? I appreciate all ideas and suggestions on the matter.</p>
3
2009-08-24T14:37:40Z
2,066,291
<p>I had to do this some years back. My solution was to run small Python server that exported the functions using SOAP, then call the functions using Visual Basic's SOAP library. The advantage is that you don't have to ship a Python environment with your spreadsheets. The disadvantage is that the clients will need a network connection.</p>
0
2010-01-14T17:56:03Z
[ "python", "excel" ]
What would be the best way to use python's functions from excel?
1,322,787
<p><em>Somebody really needs to fix this "subjective questions evaluator"</em></p> <p>I usually compile my functions in a DLL and call them from excel. That works fine (well, let's just say it works)</p> <p>Unfortunatelly, python cannot be compiled. I know of py2exe but I don't know that it can make a DLL.</p> <p>So, ..., is there any other way ? I appreciate all ideas and suggestions on the matter.</p>
3
2009-08-24T14:37:40Z
2,066,349
<p>There is an Excel Addin that allows you to do this called <a href="http://www.xefion.com/getting_started_diss.html" rel="nofollow">Discovery Script</a> at xefion.com.</p> <p>It's free but not open source. It's also based on the IronPython implementation.</p>
0
2010-01-14T18:06:26Z
[ "python", "excel" ]
What would be the best way to use python's functions from excel?
1,322,787
<p><em>Somebody really needs to fix this "subjective questions evaluator"</em></p> <p>I usually compile my functions in a DLL and call them from excel. That works fine (well, let's just say it works)</p> <p>Unfortunatelly, python cannot be compiled. I know of py2exe but I don't know that it can make a DLL.</p> <p>So, ..., is there any other way ? I appreciate all ideas and suggestions on the matter.</p>
3
2009-08-24T14:37:40Z
7,824,872
<p>Im surprised nobody mentioned <a href="http://www.pyxll.com/" rel="nofollow">pyxll</a>. From the website:</p> <blockquote> <p>PyXLL is an Excel addin that enables functions written in Python to be called in Excel. Python functions can either be exposed as Excel user defined functions that can be called from worksheets, as custom menu items, or as macros.</p> </blockquote>
4
2011-10-19T16:42:51Z
[ "python", "excel" ]
Finding "closest" strings in a Python list (alphabetically)
1,322,934
<p>I have a Python list of strings, e.g. initialized as follows:</p> <pre><code>l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra'] </code></pre> <p>I would like to test an input string against this list, and find the "closest string below it" and the "closest string above it", alphabetically and case-insensitively (i.e. no phonetics, just <code>a&lt;b</code> etc). If the input exists in the list, both the "below" and "above" should return the input.</p> <p>Several examples:</p> <pre><code>Input | Below | Above ------------------------------- bat | aardvark | cat aaa | None | aardvark ferret | dog | fish dog | dog | dog </code></pre> <p>What's the neatest way to achieve this in Python? (currently I'm iterating over a sorted list using a for loop)</p> <p>To further clarify: I'm interested in simple dictionary alphabetical comparison, not anything fancy like Levenshtein or phonetics.</p> <p>Thanks</p>
2
2009-08-24T15:04:06Z
1,323,000
<p>You can rephrase the problem to this:</p> <p>Given a sorted list of strings <code>l</code> and an input string <code>s</code>, find the index in <code>l</code> where <code>s</code> should be inserted so that <code>l</code> remains sorted after insertion.</p> <p>The elements of <code>l</code> at <code>index-1</code> and <code>index+1</code> (if they exist) are the ones you are looking for. In order to find the index, you can use <a href="http://en.wikipedia.org/wiki/Binary%5Fsearch%5Falgorithm" rel="nofollow">binary search</a>.</p>
2
2009-08-24T15:15:49Z
[ "python", "string" ]
Finding "closest" strings in a Python list (alphabetically)
1,322,934
<p>I have a Python list of strings, e.g. initialized as follows:</p> <pre><code>l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra'] </code></pre> <p>I would like to test an input string against this list, and find the "closest string below it" and the "closest string above it", alphabetically and case-insensitively (i.e. no phonetics, just <code>a&lt;b</code> etc). If the input exists in the list, both the "below" and "above" should return the input.</p> <p>Several examples:</p> <pre><code>Input | Below | Above ------------------------------- bat | aardvark | cat aaa | None | aardvark ferret | dog | fish dog | dog | dog </code></pre> <p>What's the neatest way to achieve this in Python? (currently I'm iterating over a sorted list using a for loop)</p> <p>To further clarify: I'm interested in simple dictionary alphabetical comparison, not anything fancy like Levenshtein or phonetics.</p> <p>Thanks</p>
2
2009-08-24T15:04:06Z
1,323,010
<p>A very naive implementation, good only for short lists: you can pretty easily iterate through the list and compare your choice against each one, then break the first time your choice is 'greater' than the item being compared.</p> <pre><code>for i, item in enumerate(l): if lower(item) &gt; lower(input): break print 'below: %s, above, %s' % (l[i-1], item) </code></pre>
1
2009-08-24T15:17:18Z
[ "python", "string" ]
Finding "closest" strings in a Python list (alphabetically)
1,322,934
<p>I have a Python list of strings, e.g. initialized as follows:</p> <pre><code>l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra'] </code></pre> <p>I would like to test an input string against this list, and find the "closest string below it" and the "closest string above it", alphabetically and case-insensitively (i.e. no phonetics, just <code>a&lt;b</code> etc). If the input exists in the list, both the "below" and "above" should return the input.</p> <p>Several examples:</p> <pre><code>Input | Below | Above ------------------------------- bat | aardvark | cat aaa | None | aardvark ferret | dog | fish dog | dog | dog </code></pre> <p>What's the neatest way to achieve this in Python? (currently I'm iterating over a sorted list using a for loop)</p> <p>To further clarify: I'm interested in simple dictionary alphabetical comparison, not anything fancy like Levenshtein or phonetics.</p> <p>Thanks</p>
2
2009-08-24T15:04:06Z
1,323,025
<p>This is exactly what the bisect module is for. It will be much faster than just iterating through large lists. </p> <pre><code>import bisect def closest(haystack, needle): if len(haystack) == 0: return None, None index = bisect.bisect_left(haystack, needle) if index == 0: return None, haystack[0] if index == len(haystack): return haystack[index], None if haystack[index] == needle: return haystack[index], haystack[index] return haystack[index-1], haystack[index] </code></pre> <p>The above code assumes you've sanitized the input and list to be all upper or lower case. Also, I wrote this on my iPhone, so please do check for typos. </p>
15
2009-08-24T15:21:21Z
[ "python", "string" ]
Finding "closest" strings in a Python list (alphabetically)
1,322,934
<p>I have a Python list of strings, e.g. initialized as follows:</p> <pre><code>l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra'] </code></pre> <p>I would like to test an input string against this list, and find the "closest string below it" and the "closest string above it", alphabetically and case-insensitively (i.e. no phonetics, just <code>a&lt;b</code> etc). If the input exists in the list, both the "below" and "above" should return the input.</p> <p>Several examples:</p> <pre><code>Input | Below | Above ------------------------------- bat | aardvark | cat aaa | None | aardvark ferret | dog | fish dog | dog | dog </code></pre> <p>What's the neatest way to achieve this in Python? (currently I'm iterating over a sorted list using a for loop)</p> <p>To further clarify: I'm interested in simple dictionary alphabetical comparison, not anything fancy like Levenshtein or phonetics.</p> <p>Thanks</p>
2
2009-08-24T15:04:06Z
1,323,368
<p>Are these relatively short lists, and do the contents change or are they fairly static? </p> <p>If you've got a large number of strings, and they're relatively fixed, you might want to look into storing your data in a Trie structure. Once you build it, then it's quick &amp; easy to search through and find your nearest neighbors the way you'd like.</p>
0
2009-08-24T16:23:07Z
[ "python", "string" ]
Multiprocessing with renewable queue
1,323,086
<p>I'm trying to figure out how to write a program in python that uses the multiprocessing queue.</p> <p>I have multiple servers and one of them will provide the queue remotely with this:</p> <pre><code>from multiprocessing.managers import BaseManager import Queue import daemonme queue = Queue.Queue() class QueueManager(BaseManager): pass daemonme.createDaemon() QueueManager.register('get_job', callable=lambda:queue) m = QueueManager(address=('', 50000), authkey='') s = m.get_server() s.serve_forever() </code></pre> <p>Now I want to use my dual Xeon, quad core server to process jobs off of this remote queue. The jobs are totally independent of one another. So if I have 8 cores, I'd like to start 7 processes that pick a job off the queue, process it, then go back for the next one. Each of the 7 processes will do this, but I can't quite get my head wrapped around the structure of this program.</p> <p>Can anyone provide me some educated ideas about the basic structure of this? </p> <p>Thank you in advance.</p>
2
2009-08-24T15:34:12Z
1,323,195
<p>You should use the master-slave (aka. farmer-worker) pattern. The initial process would be the master and creates the jobs. It </p> <ol> <li>creates a Queue</li> <li>creates 7 slave processes, passing the queue as a parameter</li> <li>starts writing jobs into the queue</li> </ol> <p>The slave processes continuously read from the queue, and perform the jobs (perhaps until they receive a stop message from the queue). There is no need to use Manager objects in this scenario, AFAICT.</p>
0
2009-08-24T15:53:11Z
[ "python", "queue", "multiprocessing" ]
Multiprocessing with renewable queue
1,323,086
<p>I'm trying to figure out how to write a program in python that uses the multiprocessing queue.</p> <p>I have multiple servers and one of them will provide the queue remotely with this:</p> <pre><code>from multiprocessing.managers import BaseManager import Queue import daemonme queue = Queue.Queue() class QueueManager(BaseManager): pass daemonme.createDaemon() QueueManager.register('get_job', callable=lambda:queue) m = QueueManager(address=('', 50000), authkey='') s = m.get_server() s.serve_forever() </code></pre> <p>Now I want to use my dual Xeon, quad core server to process jobs off of this remote queue. The jobs are totally independent of one another. So if I have 8 cores, I'd like to start 7 processes that pick a job off the queue, process it, then go back for the next one. Each of the 7 processes will do this, but I can't quite get my head wrapped around the structure of this program.</p> <p>Can anyone provide me some educated ideas about the basic structure of this? </p> <p>Thank you in advance.</p>
2
2009-08-24T15:34:12Z
1,323,211
<p>Look to the doc how to retreive a queue from the <a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing.managers" rel="nofollow">manager</a> (paragraph 17.6.2.7) than with a <a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing.managers" rel="nofollow">pool</a> (paragraph 17.6.2.9) of workers launch 7 jobs passing the queue to each one.</p> <p>in alternative you can think something like a producer/consumer problem:</p> <pre><code>from multiprocessing.managers import BaseManager import random class Producer(): def __init__(self): BaseManager.register('queue') self.m = BaseManager(address=('hostname', 50000), authkey='jgsjgfdjs') self.m.connect() self.cm_queue = self.m.queue() while 1: time.sleep(random.randint(1,3)) self.cm_queue.put(&lt;PUT-HERE-JOBS&gt;) from multiprocessing.managers import BaseManager import time import random class Consumer(): def __init__(self): BaseManager.register('queue') self.m = BaseManager(address=('host', 50000), authkey='jgsjgfdjs') self.m.connect() self.queue = self.m.queue() while 1: &lt;EXECUTE(job = self.queue.get())&gt; from multiprocessing.managers import BaseManager, Queue class Manager(): def __init__(self): self.queue = QueueQueu() BaseManager.register('st_queue', callable=lambda:self.queue) self.m = BaseManager(address=('host', 50000), authkey='jgsjgfdjs') self.s = self.m.get_server() self.s.serve_forever() </code></pre>
2
2009-08-24T15:55:54Z
[ "python", "queue", "multiprocessing" ]
How to extend and modify PyUnit
1,323,188
<p>I'm about to embark upon extending and modifying PyUnit. For instance, I will add warnings to it, in addition to failures.</p> <p>I'm interested in hearing words of advice on how to start, for instance, subclass every PyUnit class? What to avoid and misc caveats.</p> <p>Looking for input from those that have extended PyUnit already.</p>
1
2009-08-24T15:50:14Z
1,323,966
<p>I recommend studying the <a href="http://code.google.com/p/python-nose/" rel="nofollow">nose</a> project, a popular and well designed extension of PyUnit. You can browse its sources online <a href="http://code.google.com/p/python-nose/source/browse/" rel="nofollow">here</a> or get a copy on your machine via <a href="http://mercurial.selenic.com/wiki/" rel="nofollow">Mercurial</a>, aka <code>hg</code>, a nice distributed version control system in which <code>nose</code> keeps its sources on Google Code Hosting.</p> <p>You may well disagree with some of <code>nose</code>'s design decisions, but in general they have executed very well on those decisions, so the sources are worth studying anyway even if you decide that your extension will go in completely different directions.</p>
3
2009-08-24T18:28:47Z
[ "python", "pyunit" ]
Getting Wing IDE to stop catching the exceptions that wxPython catches
1,323,361
<p>I started using Wing IDE and it's great. I'm building a wxPython app, and I noticed that Wing IDE catches exceptions that are usually caught by wxPython and not really raised. This is usually useful, but I would like to disable this behavior occasionally. How do I do that?</p>
0
2009-08-24T16:21:53Z
1,323,458
<p>There is a <code>Ignore this exception location</code> check box in the window where the exception is reported in wing, or you could explicitly silence that specific exception in you code with a <code>try except</code> block.</p>
0
2009-08-24T16:40:33Z
[ "python", "wxpython", "wing-ide" ]
In Python, how to check if a string only contains certain characters?
1,323,364
<p>In Python, how to check if a string only contains certain characters?</p> <p>I need to check a string containing only a..z, 0..9, and . (period) and no other character.</p> <p>I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.</p> <p>I am not clear now how to do it with a regular expression.</p> <p>Is this correct? Can you suggest a simpler regular expression or a more efficient approach.</p> <pre><code>#Valid chars . a-z 0-9 def check(test_str): import re #http://docs.python.org/library/re.html #re.search returns None if no position in the string matches the pattern #pattern to search for any character other then . a-z 0-9 pattern = r'[^\.a-z0-9]' if re.search(pattern, test_str): #Character other then . a-z 0-9 was found print 'Invalid : %r' % (test_str,) else: #No character other then . a-z 0-9 was found print 'Valid : %r' % (test_str,) check(test_str='abcde.1') check(test_str='abcde.1#') check(test_str='ABCDE.12') check(test_str='_-/&gt;"!@#12345abcde&lt;') ''' Output: &gt;&gt;&gt; Valid : "abcde.1" Invalid : "abcde.1#" Invalid : "ABCDE.12" Invalid : "_-/&gt;"!@#12345abcde&lt;" ''' </code></pre>
26
2009-08-24T16:22:05Z
1,323,374
<p>Here's a simple, pure-Python implementation. It should be used when performance is not critical (included for future Googlers).</p> <pre><code>import string allowed = set(string.ascii_lowercase + string.digits + '.') def check(test_str): set(test_str) &lt;= allowed </code></pre> <p><hr /></p> <p>Regarding performance, iteration will probably be the fastest method. Regexes have to iterate through a state machine, and the set equality solution has to build a temporary set. However, the difference is unlikely to matter much. If performance of this function is very important, write it as a C extension module with a switch statement (which will be compiled to a jump table).</p> <p>Here's a C implementation, which uses if statements due to space constraints. If you absolutely need the tiny bit of extra speed, write out the switch-case. In my tests, it performs very well (2 seconds vs 9 seconds in benchmarks against the regex).</p> <pre><code>#define PY_SSIZE_T_CLEAN #include &lt;Python.h&gt; static PyObject *check(PyObject *self, PyObject *args) { const char *s; Py_ssize_t count, ii; char c; if (0 == PyArg_ParseTuple (args, "s#", &amp;s, &amp;count)) { return NULL; } for (ii = 0; ii &lt; count; ii++) { c = s[ii]; if ((c &lt; '0' &amp;&amp; c != '.') || c &gt; 'z') { Py_RETURN_FALSE; } if (c &gt; '9' &amp;&amp; c &lt; 'a') { Py_RETURN_FALSE; } } Py_RETURN_TRUE; } PyDoc_STRVAR (DOC, "Fast stringcheck"); static PyMethodDef PROCEDURES[] = { {"check", (PyCFunction) (check), METH_VARARGS, NULL}, {NULL, NULL} }; PyMODINIT_FUNC initstringcheck (void) { Py_InitModule3 ("stringcheck", PROCEDURES, DOC); } </code></pre> <p>Include it in your setup.py:</p> <pre><code>from distutils.core import setup, Extension ext_modules = [ Extension ('stringcheck', ['stringcheck.c']), ], </code></pre> <p>Use as:</p> <pre><code>&gt;&gt;&gt; from stringcheck import check &gt;&gt;&gt; check("abc") True &gt;&gt;&gt; check("ABC") False </code></pre>
37
2009-08-24T16:24:38Z
[ "python", "regex", "search", "character" ]
In Python, how to check if a string only contains certain characters?
1,323,364
<p>In Python, how to check if a string only contains certain characters?</p> <p>I need to check a string containing only a..z, 0..9, and . (period) and no other character.</p> <p>I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.</p> <p>I am not clear now how to do it with a regular expression.</p> <p>Is this correct? Can you suggest a simpler regular expression or a more efficient approach.</p> <pre><code>#Valid chars . a-z 0-9 def check(test_str): import re #http://docs.python.org/library/re.html #re.search returns None if no position in the string matches the pattern #pattern to search for any character other then . a-z 0-9 pattern = r'[^\.a-z0-9]' if re.search(pattern, test_str): #Character other then . a-z 0-9 was found print 'Invalid : %r' % (test_str,) else: #No character other then . a-z 0-9 was found print 'Valid : %r' % (test_str,) check(test_str='abcde.1') check(test_str='abcde.1#') check(test_str='ABCDE.12') check(test_str='_-/&gt;"!@#12345abcde&lt;') ''' Output: &gt;&gt;&gt; Valid : "abcde.1" Invalid : "abcde.1#" Invalid : "ABCDE.12" Invalid : "_-/&gt;"!@#12345abcde&lt;" ''' </code></pre>
26
2009-08-24T16:22:05Z
1,323,385
<p>Simpler approach? A little more Pythonic?</p> <pre><code>&gt;&gt;&gt; ok = "0123456789abcdef" &gt;&gt;&gt; all(c in ok for c in "123456abc") True &gt;&gt;&gt; all(c in ok for c in "hello world") False </code></pre> <p>It certainly isn't the most efficient, but it's sure readable.</p>
14
2009-08-24T16:26:21Z
[ "python", "regex", "search", "character" ]
In Python, how to check if a string only contains certain characters?
1,323,364
<p>In Python, how to check if a string only contains certain characters?</p> <p>I need to check a string containing only a..z, 0..9, and . (period) and no other character.</p> <p>I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.</p> <p>I am not clear now how to do it with a regular expression.</p> <p>Is this correct? Can you suggest a simpler regular expression or a more efficient approach.</p> <pre><code>#Valid chars . a-z 0-9 def check(test_str): import re #http://docs.python.org/library/re.html #re.search returns None if no position in the string matches the pattern #pattern to search for any character other then . a-z 0-9 pattern = r'[^\.a-z0-9]' if re.search(pattern, test_str): #Character other then . a-z 0-9 was found print 'Invalid : %r' % (test_str,) else: #No character other then . a-z 0-9 was found print 'Valid : %r' % (test_str,) check(test_str='abcde.1') check(test_str='abcde.1#') check(test_str='ABCDE.12') check(test_str='_-/&gt;"!@#12345abcde&lt;') ''' Output: &gt;&gt;&gt; Valid : "abcde.1" Invalid : "abcde.1#" Invalid : "ABCDE.12" Invalid : "_-/&gt;"!@#12345abcde&lt;" ''' </code></pre>
26
2009-08-24T16:22:05Z
1,323,402
<p><strong>EDIT: Changed the regular expression to exclude A-Z</strong></p> <p>Regular expression solution is the fastest pure python solution so far</p> <pre><code>reg=re.compile('^[a-z0-9\.]+$') &gt;&gt;&gt;reg.match('jsdlfjdsf12324..3432jsdflsdf') True &gt;&gt;&gt; timeit.Timer("reg.match('jsdlfjdsf12324..3432jsdflsdf')", "import re; reg=re.compile('^[a-z0-9\.]+$')").timeit() 0.70509696006774902 </code></pre> <p>Compared to other solutions:</p> <pre><code>&gt;&gt;&gt; timeit.Timer("set('jsdlfjdsf12324..3432jsdflsdf') &lt;= allowed", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit() 3.2119350433349609 &gt;&gt;&gt; timeit.Timer("all(c in allowed for c in 'jsdlfjdsf12324..3432jsdflsdf')", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit() 6.7066690921783447 </code></pre> <p>If you want to allow empty strings then change it to:</p> <pre><code>reg=re.compile('^[a-z0-9\.]*$') &gt;&gt;&gt;reg.match('') False </code></pre> <p><hr /></p> <p>Under request I'm going to return the other part of the answer. But please note that the following accept A-Z range.</p> <p>You can use <a href="http://docs.python.org/library/stdtypes.html#str.isalnum">isalnum</a></p> <pre><code>test_str.replace('.', '').isalnum() &gt;&gt;&gt; 'test123.3'.replace('.', '').isalnum() True &gt;&gt;&gt; 'test123-3'.replace('.', '').isalnum() False </code></pre> <p><strong>EDIT</strong> Using isalnum is much more efficient than the set solution</p> <pre><code>&gt;&gt;&gt; timeit.Timer("'jsdlfjdsf12324..3432jsdflsdf'.replace('.', '').isalnum()").timeit() 0.63245487213134766 </code></pre> <p><strong>EDIT2</strong> John gave an example where the above doesn't work. I changed the solution to overcome this special case by using encode</p> <pre><code>test_str.replace('.', '').encode('ascii', 'replace').isalnum() </code></pre> <p>And it is still almost 3 times faster than the set solution</p> <pre><code>timeit.Timer("u'ABC\u0131\u0661'.encode('ascii', 'replace').replace('.','').isalnum()", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit() 1.5719811916351318 </code></pre> <p>In my opinion using regular expressions is the best to solve this problem</p>
11
2009-08-24T16:28:56Z
[ "python", "regex", "search", "character" ]
In Python, how to check if a string only contains certain characters?
1,323,364
<p>In Python, how to check if a string only contains certain characters?</p> <p>I need to check a string containing only a..z, 0..9, and . (period) and no other character.</p> <p>I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.</p> <p>I am not clear now how to do it with a regular expression.</p> <p>Is this correct? Can you suggest a simpler regular expression or a more efficient approach.</p> <pre><code>#Valid chars . a-z 0-9 def check(test_str): import re #http://docs.python.org/library/re.html #re.search returns None if no position in the string matches the pattern #pattern to search for any character other then . a-z 0-9 pattern = r'[^\.a-z0-9]' if re.search(pattern, test_str): #Character other then . a-z 0-9 was found print 'Invalid : %r' % (test_str,) else: #No character other then . a-z 0-9 was found print 'Valid : %r' % (test_str,) check(test_str='abcde.1') check(test_str='abcde.1#') check(test_str='ABCDE.12') check(test_str='_-/&gt;"!@#12345abcde&lt;') ''' Output: &gt;&gt;&gt; Valid : "abcde.1" Invalid : "abcde.1#" Invalid : "ABCDE.12" Invalid : "_-/&gt;"!@#12345abcde&lt;" ''' </code></pre>
26
2009-08-24T16:22:05Z
1,325,265
<p><strong>Final(?) edit</strong></p> <p>Answer, wrapped up in a function, with annotated interactive session:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; def special_match(strg, search=re.compile(r'[^a-z0-9.]').search): ... return not bool(search(strg)) ... &gt;&gt;&gt; special_match("") True &gt;&gt;&gt; special_match("az09.") True &gt;&gt;&gt; special_match("az09.\n") False # The above test case is to catch out any attempt to use re.match() # with a `$` instead of `\Z` -- see point (6) below. &gt;&gt;&gt; special_match("az09.#") False &gt;&gt;&gt; special_match("az09.X") False &gt;&gt;&gt; </code></pre> <p>Note: There is a comparison with using re.match() further down in this answer. Further timings show that match() would win with much longer strings; match() seems to have a much larger overhead than search() when the final answer is True; this is puzzling (perhaps it's the cost of returning a MatchObject instead of None) and may warrant further rummaging.</p> <pre><code>==== Earlier text ==== </code></pre> <p>The [previously] accepted answer could use a few improvements:</p> <p>(1) Presentation gives the appearance of being the result of an interactive Python session:</p> <pre><code>reg=re.compile('^[a-z0-9\.]+$') &gt;&gt;&gt;reg.match('jsdlfjdsf12324..3432jsdflsdf') True </code></pre> <p>but match() doesn't return <code>True</code></p> <p>(2) For use with match(), the <code>^</code> at the start of the pattern is redundant, and appears to be slightly slower than the same pattern without the <code>^</code></p> <p>(3) Should foster the use of raw string automatically unthinkingly for any re pattern</p> <p>(4) The backslash in front of the dot/period is redundant</p> <p>(5) <strong>Slower than the OP's code!</strong> </p> <pre><code>prompt&gt;rem OP's version -- NOTE: OP used raw string! prompt&gt;\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import re;reg=re.compile(r'[^a-z0-9\.]')" "not bool(reg.search(t))" 1000000 loops, best of 3: 1.43 usec per loop prompt&gt;rem OP's version w/o backslash prompt&gt;\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import re;reg=re.compile(r'[^a-z0-9.]')" "not bool(reg.search(t))" 1000000 loops, best of 3: 1.44 usec per loop prompt&gt;rem cleaned-up version of accepted answer prompt&gt;\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import re;reg=re.compile(r'[a-z0-9.]+\Z')" "bool(reg.match(t))" 100000 loops, best of 3: 2.07 usec per loop prompt&gt;rem accepted answer prompt&gt;\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import re;reg=re.compile('^[a-z0-9\.]+$')" "bool(reg.match(t))" 100000 loops, best of 3: 2.08 usec per loop </code></pre> <p>(6) <strong>Can produce the wrong answer!!</strong></p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; bool(re.compile('^[a-z0-9\.]+$').match('1234\n')) True # uh-oh &gt;&gt;&gt; bool(re.compile('^[a-z0-9\.]+\Z').match('1234\n')) False </code></pre>
17
2009-08-24T23:12:00Z
[ "python", "regex", "search", "character" ]
In Python, how to check if a string only contains certain characters?
1,323,364
<p>In Python, how to check if a string only contains certain characters?</p> <p>I need to check a string containing only a..z, 0..9, and . (period) and no other character.</p> <p>I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.</p> <p>I am not clear now how to do it with a regular expression.</p> <p>Is this correct? Can you suggest a simpler regular expression or a more efficient approach.</p> <pre><code>#Valid chars . a-z 0-9 def check(test_str): import re #http://docs.python.org/library/re.html #re.search returns None if no position in the string matches the pattern #pattern to search for any character other then . a-z 0-9 pattern = r'[^\.a-z0-9]' if re.search(pattern, test_str): #Character other then . a-z 0-9 was found print 'Invalid : %r' % (test_str,) else: #No character other then . a-z 0-9 was found print 'Valid : %r' % (test_str,) check(test_str='abcde.1') check(test_str='abcde.1#') check(test_str='ABCDE.12') check(test_str='_-/&gt;"!@#12345abcde&lt;') ''' Output: &gt;&gt;&gt; Valid : "abcde.1" Invalid : "abcde.1#" Invalid : "ABCDE.12" Invalid : "_-/&gt;"!@#12345abcde&lt;" ''' </code></pre>
26
2009-08-24T16:22:05Z
24,769,085
<p>This has already been answered satisfactorily, but for people coming across this after the fact, I have done some profiling of several different methods of accomplishing this. In my case I wanted uppercase hex digits, so modify as necessary to suit your needs.</p> <p>Here are my test implementations:</p> <pre><code>import re hex_digits = set("ABCDEF1234567890") hex_match = re.compile(r'^[A-F0-9]+$') hex_search = re.compile(r'[^A-F0-9]') def test_set(input): return set(input) &lt;= hex_digits def test_not_any(input): return not any(c not in hex_digits for c in input) def test_re_match1(input): return bool(re.compile(r'^[A-F0-9]+$').match(input)) def test_re_match2(input): return bool(hex_match.match(input)) def test_re_match3(input): return bool(re.match(r'^[A-F0-9]+$', input)) def test_re_search1(input): return not bool(re.compile(r'[^A-F0-9]').search(input)) def test_re_search2(input): return not bool(hex_search.search(input)) def test_re_search3(input): return not bool(re.match(r'[^A-F0-9]', input)) </code></pre> <p>And the tests, in Python 3.4.0 on Mac OS X:</p> <pre><code>import cProfile import pstats import random # generate a list of 10000 random hex strings between 10 and 10009 characters long # this takes a little time; be patient tests = [ ''.join(random.choice("ABCDEF1234567890") for _ in range(l)) for l in range(10, 10010) ] # set up profiling, then start collecting stats test_pr = cProfile.Profile(timeunit=0.000001) test_pr.enable() # run the test functions against each item in tests. # this takes a little time; be patient for t in tests: for tf in [test_set, test_not_any, test_re_match1, test_re_match2, test_re_match3, test_re_search1, test_re_search2, test_re_search3]: _ = tf(t) # stop collecting stats test_pr.disable() # we create our own pstats.Stats object to filter # out some stuff we don't care about seeing test_stats = pstats.Stats(test_pr) # normally, stats are printed with the format %8.3f, # but I want more significant digits # so this monkey patch handles that def _f8(x): return "%11.6f" % x def _print_title(self): print(' ncalls tottime percall cumtime percall', end=' ', file=self.stream) print('filename:lineno(function)', file=self.stream) pstats.f8 = _f8 pstats.Stats.print_title = _print_title # sort by cumulative time (then secondary sort by name), ascending # then print only our test implementation function calls: test_stats.sort_stats('cumtime', 'name').reverse_order().print_stats("test_*") </code></pre> <p>which gave the following results:</p> <pre> 50335004 function calls in 13.428 seconds Ordered by: cumulative time, function name List reduced from 20 to 8 due to restriction ncalls tottime percall cumtime percall filename:lineno(function) 10000 0.005233 0.000001 0.367360 0.000037 :1(test_re_match2) 10000 0.006248 0.000001 0.378853 0.000038 :1(test_re_match3) 10000 0.010710 0.000001 0.395770 0.000040 :1(test_re_match1) 10000 0.004578 0.000000 0.467386 0.000047 :1(test_re_search2) 10000 0.005994 0.000001 0.475329 0.000048 :1(test_re_search3) 10000 0.008100 0.000001 0.482209 0.000048 :1(test_re_search1) 10000 0.863139 0.000086 0.863139 0.000086 :1(test_set) 10000 0.007414 0.000001 9.962580 0.000996 :1(test_not_any) </pre> <p>where:</p> <dl> <dt><b>ncalls</b></dt><dd>The number of times that function was called</dd> <dt><b>tottime</b></dt><dd>the total time spent in the given function, excluding time made to sub-functions</dd> <dt><b>percall</b></dt><dd>the quotient of tottime divided by ncalls</dd> <dt><b>cumtime</b></dt><dd>the cumulative time spent in this and all subfunctions</dd> <dt><b>percall</b></dt><dd>the quotient of cumtime divided by primitive calls</dd> </dl> <p>The columns we actually care about are cumtime and percall, as that shows us the actual time taken from function entry to exit. As we can see, regex match and search are not massively different. </p> <p>It is faster not to bother compiling the regex if you would have compiled it every time. It is about 7.5% faster to compile once than every time, but only 2.5% faster to compile than to not compile.</p> <p>test_set was twice as slow as re_search and thrice as slow as re_match</p> <p>test_not_any was a full order of magnitude slower than test_set</p> <p><b>TL;DR</b>: Use re.match or re.search</p>
0
2014-07-15T22:15:35Z
[ "python", "regex", "search", "character" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
1,323,426
<p><code>in</code> is definitely more pythonic.</p> <p>In fact <a href="http://docs.python.org/3.1/whatsnew/3.0.html#builtins"><code>has_key()</code> was removed in Python 3.x</a>.</p>
651
2009-08-24T16:33:18Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
1,323,429
<p>According to python <a href="http://docs.python.org/library/stdtypes.html#dict.has_key">docs</a>:</p> <blockquote> <p><code>has_key()</code> is deprecated in favor of <code>key in d</code>.</p> </blockquote>
48
2009-08-24T16:33:51Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
1,323,880
<p><code>in</code> wins hands-down, not just in elegance (and not being deprecated;-) but also in performance, e.g.:</p> <pre><code>$ python -mtimeit -s'd=dict.fromkeys(range(99))' '12 in d' 10000000 loops, best of 3: 0.0983 usec per loop $ python -mtimeit -s'd=dict.fromkeys(range(99))' 'd.has_key(12)' 1000000 loops, best of 3: 0.21 usec per loop </code></pre> <p>While the following observation is not <em>always</em> true, you'll notice that <em>usually</em>, in Python, the faster solution is more elegant and Pythonic; that's why <code>-mtimeit</code> is SO helpful -- it's not <em>just</em> about saving a hundred nanoseconds here and there!-)</p>
189
2009-08-24T18:12:28Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
1,323,998
<p><code>has_key</code> is a dictionary method, but <code>in</code> will work on any collection, and even when <code>__contains__</code> is missing, <code>in</code> will use any other method to iterate the collection to find out.</p>
11
2009-08-24T18:35:22Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
1,325,066
<p>Use <code>dict.has_key()</code> if (and only if) your code is required to be runnable by Python versions earlier than 2.3 (when <code>key in dict</code> was introduced). </p>
30
2009-08-24T22:11:34Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
8,913,940
<p>There is one example where <code>in</code> actually kills your performance.</p> <p>If you use <code>in</code> on a O(1) container that only implements <code>__getitem__</code> and <code>has_key()</code> but not <code>__contains__</code> you will turn an O(1) search into an O(N) search (as <code>in</code> falls back to a linear search via <code>__getitem__</code>).</p> <p>Fix is obviously trivial:</p> <pre><code>def __contains__(self, x): return self.has_key(x) </code></pre>
16
2012-01-18T16:45:39Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
10,512,159
<p>Python 2.x supports <code>has_key()</code>.</p> <p>Python 2.3+ and Python 3.x support <code>in</code>.</p>
9
2012-05-09T08:06:54Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
31,766,439
<p>If your intention is to use a default value in case a key is not in the dictionary then</p> <pre><code>my_dict.get('key') or default_value </code></pre> <p>is a way of skipping the <code>in</code> check. <code>get</code> returns <code>None</code> if the key is not in the dictionary. The speed is also O(1) as with using <code>in</code>. </p> <p>You can also use</p> <pre><code>my_dict.get('key', default_value) </code></pre> <p>but I find that less readable.</p>
3
2015-08-01T21:32:13Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
33,964,603
<p>The API looks the way it does for a reason... Using the builtin type APIs as documented is Pythonic...</p> <p>You should typically do <code>my_dict.get('key', default_value)</code> rather than <code>my_dict.get('key') or default_value</code>.</p> <p>The exception would be the odd case want to replace all false-equivalent values (<code>0</code>, <code>''</code>, <code>[]</code> etc) returned from <code>my_dict</code> with <code>default_value</code>.</p> <p>Actually, if the intention is to get a default value from a dict, why not use <code>collections.defaultdict</code> instead of the builtin <code>dict</code>?</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; d42 = defaultdict(lambda: 42) &gt;&gt;&gt; d42['x'] = 18 &gt;&gt;&gt; d42['x'] 18 &gt;&gt;&gt; d42['y'] 42 </code></pre> <p>The most common usecase for defaultdicts is probably with the list type, e.g:</p> <pre><code>&gt;&gt;&gt; dl = defaultdict(list) &gt;&gt;&gt; for x, y in some_list_of_tuples: ... dl[x].append(y) &gt;&gt;&gt; </code></pre>
0
2015-11-27T20:46:23Z
[ "python" ]
'has_key()' or 'in'?
1,323,410
<p>I wonder what is better to do:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d True </code></pre> <p>or:</p> <pre><code>d = {'a': 1, 'b': 2} d.has_key('a') True </code></pre>
474
2009-08-24T16:30:15Z
35,574,940
<p>Solution to dict.has_key() is deprecated, use 'in' -- sublime text editor 3</p> <p>Here I have taken an example of dictionary named 'ages' -</p> <pre><code>ages = {} # Add a couple of names to the dictionary ages['Sue'] = 23 ages['Peter'] = 19 ages['Andrew'] = 78 ages['Karren'] = 45 # use of 'in' in if condition instead of function_name.has_key(key-name). if 'Sue' in ages: print "Sue is in the dictionary. She is", ages['Sue'], "years old" else: print "Sue is not in the dictionary" </code></pre>
1
2016-02-23T10:29:07Z
[ "python" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre> <p>The output of the above is:</p> <pre><code>Calling BaseTest:testCommon .Calling BaseTest:testCommon .Calling SubTest1:testSub1 .Calling BaseTest:testCommon .Calling SubTest2:testSub2 . ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK </code></pre> <p>Is there a way to rewrite the above so that the very first <code>testCommon</code> is not called?</p> <p><strong>EDIT:</strong> Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.</p>
65
2009-08-24T16:39:41Z
1,323,503
<p>Change the BaseTest method name to setUp:</p> <pre><code>class BaseTest(unittest.TestCase): def setUp(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) </code></pre> <p>Output: </p> <blockquote> <p>Ran 2 tests in 0.000s</p> <p>Calling BaseTest:testCommon Calling<br /> SubTest1:testSub1 Calling<br /> BaseTest:testCommon Calling<br /> SubTest2:testSub2 </p> </blockquote> <p>From the <a href="http://docs.python.org/library/unittest.html#testcase-objects" rel="nofollow">documentation</a>:</p> <blockquote> <p>TestCase.setUp()<br /> Method called to prepare the test fixture. This is called immediately before calling the test method; any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.</p> </blockquote>
-2
2009-08-24T16:48:27Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre> <p>The output of the above is:</p> <pre><code>Calling BaseTest:testCommon .Calling BaseTest:testCommon .Calling SubTest1:testSub1 .Calling BaseTest:testCommon .Calling SubTest2:testSub2 . ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK </code></pre> <p>Is there a way to rewrite the above so that the very first <code>testCommon</code> is not called?</p> <p><strong>EDIT:</strong> Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.</p>
65
2009-08-24T16:39:41Z
1,323,519
<p>What are you trying to achieve? If you have common test code (assertions, template tests, etc), then place them in methods which aren't prefixed with <code>test</code> so <code>unittest</code> won't load them.</p> <pre><code>import unittest class CommonTests(unittest.TestCase): def common_assertion(self, foo, bar, baz): # whatever common code self.assertEqual(foo(bar), baz) class BaseTest(CommonTests): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(CommonTests): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(CommonTests): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre>
7
2009-08-24T16:52:44Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre> <p>The output of the above is:</p> <pre><code>Calling BaseTest:testCommon .Calling BaseTest:testCommon .Calling SubTest1:testSub1 .Calling BaseTest:testCommon .Calling SubTest2:testSub2 . ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK </code></pre> <p>Is there a way to rewrite the above so that the very first <code>testCommon</code> is not called?</p> <p><strong>EDIT:</strong> Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.</p>
65
2009-08-24T16:39:41Z
1,323,554
<p>Use multiple inheritance, so your class with common tests doesn't itself inherit from TestCase.</p> <pre><code>import unittest class CommonTests(object): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(unittest.TestCase, CommonTests): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(unittest.TestCase, CommonTests): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre>
99
2009-08-24T17:00:01Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre> <p>The output of the above is:</p> <pre><code>Calling BaseTest:testCommon .Calling BaseTest:testCommon .Calling SubTest1:testSub1 .Calling BaseTest:testCommon .Calling SubTest2:testSub2 . ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK </code></pre> <p>Is there a way to rewrite the above so that the very first <code>testCommon</code> is not called?</p> <p><strong>EDIT:</strong> Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.</p>
65
2009-08-24T16:39:41Z
6,459,279
<p>Matthew's answer is the one I needed to use since I'm on 2.5 still. But as of 2.7 you can use the @unittest.skip() decorator on any test methods you want to skip.</p> <p><a href="http://docs.python.org/library/unittest.html#skipping-tests-and-expected-failures" rel="nofollow">http://docs.python.org/library/unittest.html#skipping-tests-and-expected-failures</a></p> <p>You'll need to implement your own skipping decorator to check for the base type. Haven't used this feature before, but off the top of my head you could use BaseTest as a <strong>marker</strong> type to condition the skip:</p> <pre><code>def skipBaseTest(obj): if type(obj) is BaseTest: return unittest.skip("BaseTest tests skipped") return lambda func: func </code></pre>
4
2011-06-23T19:01:10Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre> <p>The output of the above is:</p> <pre><code>Calling BaseTest:testCommon .Calling BaseTest:testCommon .Calling SubTest1:testSub1 .Calling BaseTest:testCommon .Calling SubTest2:testSub2 . ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK </code></pre> <p>Is there a way to rewrite the above so that the very first <code>testCommon</code> is not called?</p> <p><strong>EDIT:</strong> Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.</p>
65
2009-08-24T16:39:41Z
17,696,807
<p>Matthew Marshall's answer is great, but it requires that you inherit from two classes in each of your test cases, which is error-prone. Instead, I use this (python>=2.7):</p> <pre><code>class BaseTest(unittest.TestCase): @classmethod def setUpClass(cls): if cls is BaseTest: raise unittest.SkipTest("Skip BaseTest tests, it's a base class") super(BaseTest, cls).setUpClass() </code></pre>
16
2013-07-17T10:01:59Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre> <p>The output of the above is:</p> <pre><code>Calling BaseTest:testCommon .Calling BaseTest:testCommon .Calling SubTest1:testSub1 .Calling BaseTest:testCommon .Calling SubTest2:testSub2 . ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK </code></pre> <p>Is there a way to rewrite the above so that the very first <code>testCommon</code> is not called?</p> <p><strong>EDIT:</strong> Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.</p>
65
2009-08-24T16:39:41Z
22,836,015
<p>You can solve this problem with a single command:</p> <pre><code>del(BaseTest) </code></pre> <p>So the code would look like this:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) del(BaseTest) if __name__ == '__main__': unittest.main() </code></pre>
17
2014-04-03T11:20:31Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre> <p>The output of the above is:</p> <pre><code>Calling BaseTest:testCommon .Calling BaseTest:testCommon .Calling SubTest1:testSub1 .Calling BaseTest:testCommon .Calling SubTest2:testSub2 . ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK </code></pre> <p>Is there a way to rewrite the above so that the very first <code>testCommon</code> is not called?</p> <p><strong>EDIT:</strong> Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.</p>
65
2009-08-24T16:39:41Z
24,924,066
<p>A way I've thought of solving this is by hiding the test methods if the base class is used. This way the tests aren't skipped, so the test results can be green instead of yellow in many test reporting tools.</p> <p>Compared to the mixin method, ide's like PyCharm won't complain that unit test methods are missing from the base class.</p> <p>If a base class inherits from this class, it will need to override the <code>setUpClass</code> and <code>tearDownClass</code> methods.</p> <pre><code>class BaseTest(unittest.TestCase): @classmethod def setUpClass(cls): cls._test_methods = [] if cls is BaseTest: for name in dir(cls): if name.startswith('test') and callable(getattr(cls, name)): cls._test_methods.append((name, getattr(cls, name))) setattr(cls, name, lambda self: None) @classmethod def tearDownClass(cls): if cls is BaseTest: for name, method in cls._test_methods: setattr(cls, name, method) cls._test_methods = [] </code></pre>
2
2014-07-24T02:15:58Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre> <p>The output of the above is:</p> <pre><code>Calling BaseTest:testCommon .Calling BaseTest:testCommon .Calling SubTest1:testSub1 .Calling BaseTest:testCommon .Calling SubTest2:testSub2 . ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK </code></pre> <p>Is there a way to rewrite the above so that the very first <code>testCommon</code> is not called?</p> <p><strong>EDIT:</strong> Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.</p>
65
2009-08-24T16:39:41Z
25,695,512
<p>Do not use multiple inheritance, it will bite you <a href="http://nedbatchelder.com/blog/201210/multiple_inheritance_is_hard.html">later</a>.</p> <p>Instead you can just move your base class into the separate module or wrap it with the blank class:</p> <pre><code>import unittest class BaseTestCases: class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTestCases.BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTestCases.BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre> <p>The output:</p> <pre><code>Calling BaseTest:testCommon .Calling SubTest1:testSub1 .Calling BaseTest:testCommon .Calling SubTest2:testSub2 . ---------------------------------------------------------------------- Ran 4 tests in 0.001s OK </code></pre>
47
2014-09-05T23:58:24Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre> <p>The output of the above is:</p> <pre><code>Calling BaseTest:testCommon .Calling BaseTest:testCommon .Calling SubTest1:testSub1 .Calling BaseTest:testCommon .Calling SubTest2:testSub2 . ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK </code></pre> <p>Is there a way to rewrite the above so that the very first <code>testCommon</code> is not called?</p> <p><strong>EDIT:</strong> Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.</p>
65
2009-08-24T16:39:41Z
25,895,445
<p>Another option is not to execute</p> <pre><code>unittest.main() </code></pre> <p>Instead of that you can use</p> <pre><code>suite = unittest.TestLoader().loadTestsFromTestCase(TestClass) unittest.TextTestRunner(verbosity=2).run(suite) </code></pre> <p>So you only execute the tests in the class <code>TestClass</code></p>
1
2014-09-17T16:09:50Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre> <p>The output of the above is:</p> <pre><code>Calling BaseTest:testCommon .Calling BaseTest:testCommon .Calling SubTest1:testSub1 .Calling BaseTest:testCommon .Calling SubTest2:testSub2 . ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK </code></pre> <p>Is there a way to rewrite the above so that the very first <code>testCommon</code> is not called?</p> <p><strong>EDIT:</strong> Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.</p>
65
2009-08-24T16:39:41Z
32,642,151
<p>Just rename the testCommon method to something else. Unittest (usually) skips anything that doesn't have 'test' in it.</p> <p>Quick and simple </p> <pre><code> import unittest class BaseTest(unittest.TestCase): def methodCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main()` </code></pre>
-1
2015-09-18T00:45:16Z
[ "python", "unit-testing", "testing" ]
Python unit test with base and sub class
1,323,455
<p>I currently have a few unit tests which share a common set of tests. Here's an example:</p> <pre><code>import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): def testSub1(self): print 'Calling SubTest1:testSub1' sub = 3 self.assertEquals(sub, 3) class SubTest2(BaseTest): def testSub2(self): print 'Calling SubTest2:testSub2' sub = 4 self.assertEquals(sub, 4) if __name__ == '__main__': unittest.main() </code></pre> <p>The output of the above is:</p> <pre><code>Calling BaseTest:testCommon .Calling BaseTest:testCommon .Calling SubTest1:testSub1 .Calling BaseTest:testCommon .Calling SubTest2:testSub2 . ---------------------------------------------------------------------- Ran 5 tests in 0.000s OK </code></pre> <p>Is there a way to rewrite the above so that the very first <code>testCommon</code> is not called?</p> <p><strong>EDIT:</strong> Instead of running 5 tests above, I want it to run only 4 tests, 2 from the SubTest1 and another 2 from SubTest2. It seems that Python unittest is running the original BaseTest on its own and I need a mechanism to prevent that from happening.</p>
65
2009-08-24T16:39:41Z
37,285,261
<p>I made about the same than @Vladim P. (<a href="http://stackoverflow.com/a/25695512/2451329">http://stackoverflow.com/a/25695512/2451329</a>) but slightly modified:</p> <pre><code>import unittest2 from some_module import func1, func2 def make_base_class(func): class Base(unittest2.TestCase): def test_common1(self): print("in test_common1") self.assertTrue(func()) def test_common2(self): print("in test_common1") self.assertFalse(func(42)) return Base class A(make_base_class(func1)): pass class B(make_base_class(func2)): def test_func2_with_no_arg_return_bar(self): self.assertEqual("bar", func2()) </code></pre> <p>and there we go.</p>
0
2016-05-17T20:02:34Z
[ "python", "unit-testing", "testing" ]
Why do I get 'service unavailable' with multiple chat sends when using XMPP?
1,323,693
<p>I have made a simple IM client in both Python and C#, using a few different XMPP libraries for each.</p> <p>They work very well as simple autoresponders, or trivial bots, but when I turn them into chat rooms (ie, a message gets reflected to many other JIDs), I suddenly start getting 503 service-unavailable responses from the Google talk server.</p> <p>Where should I start looking to resolve this issue? Given that I have used several languages and libraries, I don't think this is a problem with my particular setup. I am using the various examples provided with the libraries.</p>
1
2009-08-24T17:29:05Z
1,337,596
<p>Do you have all people you try to send messages to in your rooster? Otherwise GTalk won't allow the message to be sent and instead return Error 503.</p> <p>There was a pidgin bug tracker describing a similar problem: <a href="http://pidgin.im/pipermail/tracker/2007-December/019925.html" rel="nofollow">Pidgin #4236</a> </p> <p>If you're sure you have all the JIDs in your rooster you should also check how manny messages are send in parallel. Google will limit the count of messages a single JID is allowed to send in a specified period of time.</p>
2
2009-08-26T21:27:55Z
[ "c#", "python", "xmpp" ]
Why do I get 'service unavailable' with multiple chat sends when using XMPP?
1,323,693
<p>I have made a simple IM client in both Python and C#, using a few different XMPP libraries for each.</p> <p>They work very well as simple autoresponders, or trivial bots, but when I turn them into chat rooms (ie, a message gets reflected to many other JIDs), I suddenly start getting 503 service-unavailable responses from the Google talk server.</p> <p>Where should I start looking to resolve this issue? Given that I have used several languages and libraries, I don't think this is a problem with my particular setup. I am using the various examples provided with the libraries.</p>
1
2009-08-24T17:29:05Z
1,339,931
<p>If you're looking to create actual chat rooms, why not rather get a jabber server to host those (following <a href="http://xmpp.org/extensions/xep-0045.html" rel="nofollow">http://xmpp.org/extensions/xep-0045.html</a> - ejabberd has these as default and there are plugins for most jabber servers to implement them), and then have your bot join that room (most clients support this - Google Talk doesn't unfortunately)?</p>
1
2009-08-27T09:28:51Z
[ "c#", "python", "xmpp" ]
Running Panda3D on Python 2.6
1,323,887
<p>I just got Panda3D for the first time. I deleted the included Python version. In my Python dir, I put a file <code>panda.pth</code> that looks like this:</p> <pre><code>C:\Panda3D-1.6.2 C:\Panda3D-1.6.2\bin </code></pre> <p>But when I run <code>import direct.directbase.DirectStart</code>, I get:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import direct.directbase.DirectStart File "C:\Panda3D-1.6.2\direct\directbase\DirectStart.py", line 3, in &lt;module&gt; from direct.showbase import ShowBase File "C:\Panda3D-1.6.2\direct\showbase\ShowBase.py", line 10, in &lt;module&gt; from pandac.PandaModules import * File "C:\Panda3D-1.6.2\pandac\PandaModules.py", line 1, in &lt;module&gt; from libpandaexpressModules import * File "C:\Panda3D-1.6.2\pandac\libpandaexpressModules.py", line 1, in &lt;module&gt; from extension_native_helpers import * File "C:\Panda3D-1.6.2\pandac\extension_native_helpers.py", line 75, in &lt;module&gt; Dtool_PreloadDLL("libpandaexpress") File "C:\Panda3D-1.6.2\pandac\extension_native_helpers.py", line 73, in Dtool_PreloadDLL imp.load_dynamic(module, pathname) ImportError: Module use of python25.dll conflicts with this version of Python. </code></pre> <p>I'm assuming this has something to do with me using Python 2.6. Any solutions?</p>
0
2009-08-24T18:13:17Z
1,323,989
<p>Python extensions aren't binary compatible across major releases. Your options are:</p> <p>A. Recompile panda3d for python 2.6.</p> <p>B. Use python 2.5.</p> <p>No way around it.</p>
2
2009-08-24T18:32:29Z
[ "python", "panda3d" ]
Running Panda3D on Python 2.6
1,323,887
<p>I just got Panda3D for the first time. I deleted the included Python version. In my Python dir, I put a file <code>panda.pth</code> that looks like this:</p> <pre><code>C:\Panda3D-1.6.2 C:\Panda3D-1.6.2\bin </code></pre> <p>But when I run <code>import direct.directbase.DirectStart</code>, I get:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import direct.directbase.DirectStart File "C:\Panda3D-1.6.2\direct\directbase\DirectStart.py", line 3, in &lt;module&gt; from direct.showbase import ShowBase File "C:\Panda3D-1.6.2\direct\showbase\ShowBase.py", line 10, in &lt;module&gt; from pandac.PandaModules import * File "C:\Panda3D-1.6.2\pandac\PandaModules.py", line 1, in &lt;module&gt; from libpandaexpressModules import * File "C:\Panda3D-1.6.2\pandac\libpandaexpressModules.py", line 1, in &lt;module&gt; from extension_native_helpers import * File "C:\Panda3D-1.6.2\pandac\extension_native_helpers.py", line 75, in &lt;module&gt; Dtool_PreloadDLL("libpandaexpress") File "C:\Panda3D-1.6.2\pandac\extension_native_helpers.py", line 73, in Dtool_PreloadDLL imp.load_dynamic(module, pathname) ImportError: Module use of python25.dll conflicts with this version of Python. </code></pre> <p>I'm assuming this has something to do with me using Python 2.6. Any solutions?</p>
0
2009-08-24T18:13:17Z
1,324,037
<p>If you can wait for the upcoming 1.7.0 release, it will be compiled against Python 2.6 - see <a href="http://www.panda3d.org/phpbb2/viewtopic.php?p=42778&amp;sid=d77e7708ac0d9d3f79c19c0fcd5c4621" rel="nofollow">this thread</a>.</p>
1
2009-08-24T18:44:32Z
[ "python", "panda3d" ]
How do I get str.translate to work with Unicode strings?
1,324,067
<p>I have the following code:</p> <pre><code>import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_table = string.maketrans(not_letters_or_digits, translate_to *len(not_letters_or_digits)) return to_translate.translate(translate_table) </code></pre> <p>Which works great for non-unicode strings:</p> <pre><code>&gt;&gt;&gt; translate_non_alphanumerics('&lt;foo&gt;!') '_foo__' </code></pre> <p>But fails for unicode strings:</p> <pre><code>&gt;&gt;&gt; translate_non_alphanumerics(u'&lt;foo&gt;!') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 5, in translate_non_alphanumerics TypeError: character mapping must return integer, None or unicode </code></pre> <p>I can't make any sense of the paragraph on "Unicode objects" in the <a href="http://docs.python.org/library/stdtypes.html#string-methods">Python 2.6.2 docs</a> for the str.translate() method.</p> <p>How do I make this work for Unicode strings?</p>
48
2009-08-24T18:52:52Z
1,324,114
<p>The Unicode version of translate requires a mapping from Unicode ordinals (which you can retrieve for a single character with <code>ord</code>) to Unicode ordinals. If you want to delete characters, you map to <code>None</code>.</p> <p>I changed your function to build a dict mapping the ordinal of every character to the ordinal of what you want to translate to:</p> <pre><code>def translate_non_alphanumerics(to_translate, translate_to=u'_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_table = dict((ord(char), translate_to) for char in not_letters_or_digits) return to_translate.translate(translate_table) &gt;&gt;&gt; translate_non_alphanumerics(u'&lt;foo&gt;!') u'_foo__' </code></pre> <p><em>edit:</em> It turns out that the translation mapping must map from the Unicode ordinal (via <code>ord</code>) to either another Unicode ordinal, a Unicode string, or None (to delete). I have thus changed the default value for <code>translate_to</code> to be a Unicode literal. For example:</p> <pre><code>&gt;&gt;&gt; translate_non_alphanumerics(u'&lt;foo&gt;!', u'bad') u'badfoobadbad' </code></pre>
44
2009-08-24T19:02:57Z
[ "python", "unicode", "string" ]
How do I get str.translate to work with Unicode strings?
1,324,067
<p>I have the following code:</p> <pre><code>import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_table = string.maketrans(not_letters_or_digits, translate_to *len(not_letters_or_digits)) return to_translate.translate(translate_table) </code></pre> <p>Which works great for non-unicode strings:</p> <pre><code>&gt;&gt;&gt; translate_non_alphanumerics('&lt;foo&gt;!') '_foo__' </code></pre> <p>But fails for unicode strings:</p> <pre><code>&gt;&gt;&gt; translate_non_alphanumerics(u'&lt;foo&gt;!') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 5, in translate_non_alphanumerics TypeError: character mapping must return integer, None or unicode </code></pre> <p>I can't make any sense of the paragraph on "Unicode objects" in the <a href="http://docs.python.org/library/stdtypes.html#string-methods">Python 2.6.2 docs</a> for the str.translate() method.</p> <p>How do I make this work for Unicode strings?</p>
48
2009-08-24T18:52:52Z
1,324,274
<p>I came up with the following combination of my original function and <a href="http://stackoverflow.com/users/66502/mike-boers">Mike</a>'s version that works with Unicode and ASCII strings:</p> <pre><code>def translate_non_alphanumerics(to_translate, translate_to=u'_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' if isinstance(to_translate, unicode): translate_table = dict((ord(char), unicode(translate_to)) for char in not_letters_or_digits) else: assert isinstance(to_translate, str) translate_table = string.maketrans(not_letters_or_digits, translate_to *len(not_letters_or_digits)) return to_translate.translate(translate_table) </code></pre> <p><strong>Update</strong>: "coerced" <code>translate_to</code> to unicode for the unicode <code>translate_table</code>. Thanks Mike.</p>
4
2009-08-24T19:33:25Z
[ "python", "unicode", "string" ]
How do I get str.translate to work with Unicode strings?
1,324,067
<p>I have the following code:</p> <pre><code>import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_table = string.maketrans(not_letters_or_digits, translate_to *len(not_letters_or_digits)) return to_translate.translate(translate_table) </code></pre> <p>Which works great for non-unicode strings:</p> <pre><code>&gt;&gt;&gt; translate_non_alphanumerics('&lt;foo&gt;!') '_foo__' </code></pre> <p>But fails for unicode strings:</p> <pre><code>&gt;&gt;&gt; translate_non_alphanumerics(u'&lt;foo&gt;!') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 5, in translate_non_alphanumerics TypeError: character mapping must return integer, None or unicode </code></pre> <p>I can't make any sense of the paragraph on "Unicode objects" in the <a href="http://docs.python.org/library/stdtypes.html#string-methods">Python 2.6.2 docs</a> for the str.translate() method.</p> <p>How do I make this work for Unicode strings?</p>
48
2009-08-24T18:52:52Z
1,324,461
<p>For a simple hack that will work on both str and unicode objects, convert the translation table to unicode before running translate():</p> <pre><code>import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_table = string.maketrans(not_letters_or_digits, translate_to *len(not_letters_or_digits)) translate_table = translate_table.decode("latin-1") return to_translate.translate(translate_table) </code></pre> <p>The catch here is that it will implicitly convert all str objects to unicode, throwing errors if to_translate contains non-ascii characters.</p>
3
2009-08-24T20:07:33Z
[ "python", "unicode", "string" ]
How do I get str.translate to work with Unicode strings?
1,324,067
<p>I have the following code:</p> <pre><code>import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_table = string.maketrans(not_letters_or_digits, translate_to *len(not_letters_or_digits)) return to_translate.translate(translate_table) </code></pre> <p>Which works great for non-unicode strings:</p> <pre><code>&gt;&gt;&gt; translate_non_alphanumerics('&lt;foo&gt;!') '_foo__' </code></pre> <p>But fails for unicode strings:</p> <pre><code>&gt;&gt;&gt; translate_non_alphanumerics(u'&lt;foo&gt;!') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 5, in translate_non_alphanumerics TypeError: character mapping must return integer, None or unicode </code></pre> <p>I can't make any sense of the paragraph on "Unicode objects" in the <a href="http://docs.python.org/library/stdtypes.html#string-methods">Python 2.6.2 docs</a> for the str.translate() method.</p> <p>How do I make this work for Unicode strings?</p>
48
2009-08-24T18:52:52Z
13,179,797
<p>Instead of having to specify all the characters that need to be replaced, you could also view it the other way around and, instead, specify only the valid characters, like so:</p> <pre><code>import re def replace_non_alphanumerics(source, replacement_character='_'): result = re.sub("[^_a-zA-Z0-9]", replacement_character, source) return result </code></pre> <p>This works with unicode as well as regular strings, and preserves the type (if both the <code>replacement_character</code> and the <code>source</code> are of the same type, obviously).</p>
0
2012-11-01T15:00:31Z
[ "python", "unicode", "string" ]
How do I get str.translate to work with Unicode strings?
1,324,067
<p>I have the following code:</p> <pre><code>import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~' translate_table = string.maketrans(not_letters_or_digits, translate_to *len(not_letters_or_digits)) return to_translate.translate(translate_table) </code></pre> <p>Which works great for non-unicode strings:</p> <pre><code>&gt;&gt;&gt; translate_non_alphanumerics('&lt;foo&gt;!') '_foo__' </code></pre> <p>But fails for unicode strings:</p> <pre><code>&gt;&gt;&gt; translate_non_alphanumerics(u'&lt;foo&gt;!') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 5, in translate_non_alphanumerics TypeError: character mapping must return integer, None or unicode </code></pre> <p>I can't make any sense of the paragraph on "Unicode objects" in the <a href="http://docs.python.org/library/stdtypes.html#string-methods">Python 2.6.2 docs</a> for the str.translate() method.</p> <p>How do I make this work for Unicode strings?</p>
48
2009-08-24T18:52:52Z
19,113,364
<p>In this version you can relatively make one's letters to other </p> <pre><code>def trans(to_translate): tabin = u'привет' tabout = u'тевирп' tabin = [ord(char) for char in tabin] translate_table = dict(zip(tabin, tabout)) return to_translate.translate(translate_table) </code></pre>
6
2013-10-01T10:04:15Z
[ "python", "unicode", "string" ]
What is the fastest template system for Python?
1,324,238
<p>Jinja2 and Mako are both apparently pretty fast.</p> <p>How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?</p>
44
2009-08-24T19:28:00Z
1,324,258
<p>From the <a href="http://jinja.pocoo.org/2/documentation/faq">jinja2 docs</a>, it seems that string.Template is the fastest if that's all you need.</p> <blockquote> <p>Without a doubt you should try to remove as much logic from templates as possible. But templates without any logic mean that you have to do all the processing in the code which is boring and stupid. A template engine that does that is shipped with Python and called string.Template. Comes without loops and if conditions and is by far the fastest template engine you can get for Python.</p> </blockquote>
7
2009-08-24T19:30:46Z
[ "python", "django-templates", "template-engine", "mako", "jinja2" ]
What is the fastest template system for Python?
1,324,238
<p>Jinja2 and Mako are both apparently pretty fast.</p> <p>How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?</p>
44
2009-08-24T19:28:00Z
1,324,515
<p>In general you will have to do profiling to answer that question, as it depends on how you use the templates and what for.</p> <p>string.Template is the fastest, but so primitive it can hardly be called a template in the same breath as the other templating systems, as it only does string replacements, and has no conditions or loops, making it pretty useless in practice.</p>
1
2009-08-24T20:19:22Z
[ "python", "django-templates", "template-engine", "mako", "jinja2" ]
What is the fastest template system for Python?
1,324,238
<p>Jinja2 and Mako are both apparently pretty fast.</p> <p>How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?</p>
44
2009-08-24T19:28:00Z
1,325,478
<p>I think Cheetah might be the fastest, as it's implemented in C.</p>
-1
2009-08-25T00:29:17Z
[ "python", "django-templates", "template-engine", "mako", "jinja2" ]
What is the fastest template system for Python?
1,324,238
<p>Jinja2 and Mako are both apparently pretty fast.</p> <p>How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?</p>
44
2009-08-24T19:28:00Z
1,326,219
<p>Here are the results of the popular template engines for rendering a 10x1000 HTML table.</p> <pre><code>Python 2.6.2 on a 3GHz Intel Core 2 Kid template 696.89 ms Kid template + cElementTree 649.88 ms Genshi template + tag builder 431.01 ms Genshi tag builder 389.39 ms Django template 352.68 ms Genshi template 266.35 ms ElementTree 180.06 ms cElementTree 107.85 ms StringIO 41.48 ms Jinja 2 36.38 ms Cheetah template 34.66 ms Mako Template 29.06 ms Spitfire template 21.80 ms Tenjin 18.39 ms Spitfire template -O1 11.86 ms cStringIO 5.80 ms Spitfire template -O3 4.91 ms Spitfire template -O2 4.82 ms generator concat 4.06 ms list concat 3.99 ms generator concat optimized 2.84 ms list concat optimized 2.62 ms </code></pre> <p>The benchmark is based on <a href="http://code.google.com/p/spitfire/source/browse/trunk/tests/perf/bigtable.py">code from Spitfire performance tests</a> with some added template engines and added iterations to increase accuracy. The list and generator concat at the end are hand coded Python to get a feel for the upper limit of performance achievable by compiling to Python bytecode. The optimized versions use string interpolation in the inner loop.</p> <p>But before you run out to switch your template engine, make sure it matters. You'll need to be doing some pretty heavy caching and really optimized code before the differences between the compiling template engines starts to matter. For most applications good abstraction facilities, compatibility with design tools, familiarity and other things matter much much more.</p>
87
2009-08-25T05:28:48Z
[ "python", "django-templates", "template-engine", "mako", "jinja2" ]
What is the fastest template system for Python?
1,324,238
<p>Jinja2 and Mako are both apparently pretty fast.</p> <p>How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?</p>
44
2009-08-24T19:28:00Z
1,698,458
<p>If you can throw caching in the mix (like memcached) then choose based on features and ease of use rather than optimization.</p> <p>I use Mako because I like the syntax and features. Fortunately it is one of the fastest as well.</p>
3
2009-11-09T00:16:00Z
[ "python", "django-templates", "template-engine", "mako", "jinja2" ]
How to alphabetically sort the values in a many-to-many django-admin box?
1,324,602
<p>I have a simple model like this one:</p> <pre><code>class Artist(models.Model): surname = models.CharField(max_length=200) name = models.CharField(max_length=200, blank=True) slug = models.SlugField(unique=True) photo = models.ImageField(upload_to='artists', blank=True) bio = models.TextField(blank=True) class Images(models.Model): title = models.CharField(max_length=200) artist = models.ManyToManyField(Artist) img = models.ImageField(upload_to='images') </code></pre> <p>Well, I started to insert some Artists and then I went to the Images insert form. I found that the many-to-many artist box is unsorted:</p> <ul> <li>Mondino Aldo</li> <li>Aliprandi Bernardo</li> <li>Rotella Mimmo</li> <li>Corpora Antonio</li> </ul> <p>Instead of:</p> <ul> <li>Aliprandi Bernardo</li> <li>Corpora Antonio</li> <li>Mondino Aldo</li> <li>Rotella Mimmo</li> </ul> <p>How can I solve this issue? Any suggestion? Thank you in advance.</p> <p>Matteo</p>
7
2009-08-24T20:35:58Z
1,324,649
<p>Set <a href="http://docs.djangoproject.com/en/dev/ref/models/options/#ordering"><code>ordering</code></a> on the Article's inner <code>Meta</code> class.</p> <pre><code>class Article(models.Model): .... class Meta: ordering = ['surname', 'name'] </code></pre>
7
2009-08-24T20:43:49Z
[ "python", "django", "sorting", "django-admin", "many-to-many" ]
What python modules are available to assist in daemonization in the standard library?
1,324,651
<p>I have a simple python program that I'd like to daemonize. </p> <p>Since the point of my doing this is not to demonstrate mastery over the spawn, fork, disconnect , etc, I'd like to find a module that would make it quick and simple for me. I've been looking in the std lib, but can not seem to find anything. </p> <p>Is there?</p>
3
2009-08-24T20:43:59Z
1,324,692
<p>Here's a library for making well behaved unix daemons: <a href="http://pypi.python.org/pypi/python-daemon/" rel="nofollow">http://pypi.python.org/pypi/python-daemon/</a></p> <p>And another one that appears more lightweight: <a href="http://code.activestate.com/recipes/278731/" rel="nofollow">http://code.activestate.com/recipes/278731/</a></p>
4
2009-08-24T20:49:20Z
[ "python", "daemon" ]
What python modules are available to assist in daemonization in the standard library?
1,324,651
<p>I have a simple python program that I'd like to daemonize. </p> <p>Since the point of my doing this is not to demonstrate mastery over the spawn, fork, disconnect , etc, I'd like to find a module that would make it quick and simple for me. I've been looking in the std lib, but can not seem to find anything. </p> <p>Is there?</p>
3
2009-08-24T20:43:59Z
1,324,709
<pre><code>subprocess </code></pre> <p>is an (almost) platform-independent module to work with processes.</p>
-1
2009-08-24T20:53:01Z
[ "python", "daemon" ]
python time interval algorithm sum
1,324,748
<p>Hello Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all cases such as one interval inside other(so the result is the interval of the bigger one), no intersection (so the result is the sum of both intervals).</p> <p>My incoming data structure is primitive, simply string like "15:30" so a conversion may be needed.</p> <p>Thanks</p>
2
2009-08-24T20:59:25Z
1,324,813
<p>I'll assume you can do the conversion to something like <a href="http://docs.python.org/library/datetime.html" rel="nofollow">datetime</a> on your own.</p> <p>Sum the two intervals, then subtract any overlap. You can get the overlap by comparing the min and max of each of the two ranges.</p>
0
2009-08-24T21:12:39Z
[ "python", "time", "intervals" ]
python time interval algorithm sum
1,324,748
<p>Hello Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all cases such as one interval inside other(so the result is the interval of the bigger one), no intersection (so the result is the sum of both intervals).</p> <p>My incoming data structure is primitive, simply string like "15:30" so a conversion may be needed.</p> <p>Thanks</p>
2
2009-08-24T20:59:25Z
1,324,848
<pre><code>from datetime import datetime, timedelta START, END = xrange(2) def tparse(timestring): return datetime.strptime(timestring, '%H:%M') def sum_intervals(intervals): times = [] for interval in intervals: times.append((tparse(interval[START]), START)) times.append((tparse(interval[END]), END)) times.sort() started = 0 result = timedelta() for t, type in times: if type == START: if not started: start_time = t started += 1 elif type == END: started -= 1 if not started: result += (t - start_time) return result </code></pre> <p>Testing with your times from the question:</p> <pre><code>intervals = [ ('16:30', '20:00'), ('15:00', '19:00'), ] print sum_intervals(intervals) </code></pre> <p>That prints:</p> <pre><code>5:00:00 </code></pre> <p>Testing it together with data that doesn't overlap</p> <pre><code>intervals = [ ('16:30', '20:00'), ('15:00', '19:00'), ('03:00', '04:00'), ('06:00', '08:00'), ('07:30', '11:00'), ] print sum_intervals(intervals) </code></pre> <p>result:</p> <pre><code>11:00:00 </code></pre>
3
2009-08-24T21:20:39Z
[ "python", "time", "intervals" ]
python time interval algorithm sum
1,324,748
<p>Hello Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all cases such as one interval inside other(so the result is the interval of the bigger one), no intersection (so the result is the sum of both intervals).</p> <p>My incoming data structure is primitive, simply string like "15:30" so a conversion may be needed.</p> <p>Thanks</p>
2
2009-08-24T20:59:25Z
1,324,880
<p>Code for when there is an overlap, please add it to one of your solutions:</p> <pre><code>def interval(i1, i2): minstart, minend = [min(*e) for e in zip(i1, i2)] maxstart, maxend = [max(*e) for e in zip(i1, i2)] if minend &lt; maxstart: # no overlap return minend-minstart + maxend-maxstart else: # overlap return maxend-minstart </code></pre>
0
2009-08-24T21:30:44Z
[ "python", "time", "intervals" ]
python time interval algorithm sum
1,324,748
<p>Hello Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all cases such as one interval inside other(so the result is the interval of the bigger one), no intersection (so the result is the sum of both intervals).</p> <p>My incoming data structure is primitive, simply string like "15:30" so a conversion may be needed.</p> <p>Thanks</p>
2
2009-08-24T20:59:25Z
1,325,221
<p>You'll want to convert your strings into datetimes. You can do this with <code>datetime.datetime.strptime</code>.</p> <p>Given intervals of <code>datetime.datetime</code> objects, if the intervals are:</p> <pre><code>int1 = (start1, end1) int2 = (start2, end2) </code></pre> <p>Then isn't it just:</p> <pre><code>if end1 &lt; start2 or end2 &lt; start1: # The intervals are disjoint. return (end1-start1) + (end2-start2) else: return max(end1, end2) - min(start1, start2) </code></pre>
0
2009-08-24T22:55:39Z
[ "python", "time", "intervals" ]
Match database output (balanced parentheses, table & rows structure) and output as a list?
1,324,949
<p>How would I parse the following input (either going line by line or via regex... or combination of both):</p> <pre><code>Table[ Row[ C_ID[Data:12345.0][Sec:12345.0][Type:Double] F_ID[Data:17660][Sec:17660][Type:Long] NAME[Data:Mike Jones][Sec:Mike Jones][Type:String] ] Row[ C_ID[Data:2560.0][Sec:2560.0][Type:Double] ... ] ] </code></pre> <p>there is indentation in there, of course, so it can be split by \n\t (and then cleaned up for the extra tabs \t in C_ID, F_ID lines and such...</p> <p>The desired output is something more usable in python:</p> <pre><code>{'C_ID': 12345, 'F_ID': 17660, 'NAME': 'Mike Jones',....} {'C_ID': 2560, ....} </code></pre> <p>I've tried going line by line, and then using multiple splits() to throw away what I don't need and keep what I do need, but I'm sure there is a much more elegant and faster way of doing it...</p>
0
2009-08-24T21:45:27Z
1,324,992
<p>Parsing recursive structures with regex is a pain because you have to keep state.</p> <p>Instead, use <a href="http://pyparsing.wikispaces.com" rel="nofollow">pyparsing</a> or some other real parser.</p> <p>Some folks like <a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a> because it follows the traditional Lex/Yacc architecture.</p>
3
2009-08-24T21:56:58Z
[ "python", "regex", "parsing" ]
Match database output (balanced parentheses, table & rows structure) and output as a list?
1,324,949
<p>How would I parse the following input (either going line by line or via regex... or combination of both):</p> <pre><code>Table[ Row[ C_ID[Data:12345.0][Sec:12345.0][Type:Double] F_ID[Data:17660][Sec:17660][Type:Long] NAME[Data:Mike Jones][Sec:Mike Jones][Type:String] ] Row[ C_ID[Data:2560.0][Sec:2560.0][Type:Double] ... ] ] </code></pre> <p>there is indentation in there, of course, so it can be split by \n\t (and then cleaned up for the extra tabs \t in C_ID, F_ID lines and such...</p> <p>The desired output is something more usable in python:</p> <pre><code>{'C_ID': 12345, 'F_ID': 17660, 'NAME': 'Mike Jones',....} {'C_ID': 2560, ....} </code></pre> <p>I've tried going line by line, and then using multiple splits() to throw away what I don't need and keep what I do need, but I'm sure there is a much more elegant and faster way of doing it...</p>
0
2009-08-24T21:45:27Z
1,325,165
<p>This excellent <a href="http://nedbatchelder.com/text/python-parsers.html" rel="nofollow">page</a> lists many parsers available to Python programmers. Regexes are unsuitable for "balanced parentheses" matching, but any of the third party packages reviewed on that page will serve you well.</p>
0
2009-08-24T22:40:29Z
[ "python", "regex", "parsing" ]
Match database output (balanced parentheses, table & rows structure) and output as a list?
1,324,949
<p>How would I parse the following input (either going line by line or via regex... or combination of both):</p> <pre><code>Table[ Row[ C_ID[Data:12345.0][Sec:12345.0][Type:Double] F_ID[Data:17660][Sec:17660][Type:Long] NAME[Data:Mike Jones][Sec:Mike Jones][Type:String] ] Row[ C_ID[Data:2560.0][Sec:2560.0][Type:Double] ... ] ] </code></pre> <p>there is indentation in there, of course, so it can be split by \n\t (and then cleaned up for the extra tabs \t in C_ID, F_ID lines and such...</p> <p>The desired output is something more usable in python:</p> <pre><code>{'C_ID': 12345, 'F_ID': 17660, 'NAME': 'Mike Jones',....} {'C_ID': 2560, ....} </code></pre> <p>I've tried going line by line, and then using multiple splits() to throw away what I don't need and keep what I do need, but I'm sure there is a much more elegant and faster way of doing it...</p>
0
2009-08-24T21:45:27Z
1,325,382
<p>This regex:</p> <pre><code>Row\[[\s]*C_ID\[[\W]*Data:([0-9.]*)[\S\W]*F_ID\[[\S\W]*Data:([0-9.]*)[\S\W]*NAME\[[\S\W]*Data:([\w ]*)[\S ]* </code></pre> <p>for the first row will match:</p> <p>$1=12345.0 $2=17660 $3=Mike Jones</p> <p>Then you can use something like this:</p> <pre><code>{'C_ID': $1, 'F_ID': $2, 'NAME': '$3'} </code></pre> <p>to produce:</p> <pre><code>{'C_ID': 12345.0, 'F_ID': 17660, 'NAME': 'Mike Jones'} </code></pre> <p>So you need to iterate through your input until it stops matching your rows... Does it make sense?</p>
-1
2009-08-24T23:57:05Z
[ "python", "regex", "parsing" ]
Match database output (balanced parentheses, table & rows structure) and output as a list?
1,324,949
<p>How would I parse the following input (either going line by line or via regex... or combination of both):</p> <pre><code>Table[ Row[ C_ID[Data:12345.0][Sec:12345.0][Type:Double] F_ID[Data:17660][Sec:17660][Type:Long] NAME[Data:Mike Jones][Sec:Mike Jones][Type:String] ] Row[ C_ID[Data:2560.0][Sec:2560.0][Type:Double] ... ] ] </code></pre> <p>there is indentation in there, of course, so it can be split by \n\t (and then cleaned up for the extra tabs \t in C_ID, F_ID lines and such...</p> <p>The desired output is something more usable in python:</p> <pre><code>{'C_ID': 12345, 'F_ID': 17660, 'NAME': 'Mike Jones',....} {'C_ID': 2560, ....} </code></pre> <p>I've tried going line by line, and then using multiple splits() to throw away what I don't need and keep what I do need, but I'm sure there is a much more elegant and faster way of doing it...</p>
0
2009-08-24T21:45:27Z
1,390,191
<p>There really isn't a lot of unpredictable nesting going on here, so you could do this with regex's. But pyparsing is my tool of choice, so here is my solution:</p> <pre><code>from pyparsing import * LBRACK,RBRACK,COLON = map(Suppress,"[]:") ident = Word(alphas, alphanums+"_") datatype = oneOf("Double Long String Boolean") # define expressions for pieces of attribute definitions data = LBRACK + "Data" + COLON + SkipTo(RBRACK)("contents") + RBRACK sec = LBRACK + "Sec" + COLON + SkipTo(RBRACK)("contents") + RBRACK type = LBRACK + "Type" + COLON + datatype("datatype") + RBRACK # define entire attribute definition, giving each piece its own results name attrDef = Group(ident("key") + data("data") + sec("sec") + type("type")) # now a row is just a "Row[" and one or more attrDef's and "]" rowDef = Group("Row" + LBRACK + Group(OneOrMore(attrDef))("attrs") + RBRACK) # this method will process each row, and convert the key and data fields # to addressable results names def assignAttrs(tokens): ret = ParseResults(tokens.asList()) for attr in tokens[0].attrs: # use datatype mapped to function to convert data at parse time value = { 'Double' : float, 'Long' : int, 'String' : str, 'Boolean' : bool, }[attr.type.datatype](attr.data.contents) ret[attr.key] = value # replace parse results created by pyparsing with our own named results tokens[0] = ret rowDef.setParseAction(assignAttrs) # a TABLE is just "Table[", one or more rows and "]" tableDef = "Table" + LBRACK + OneOrMore(rowDef)("rows") + RBRACK test = """ Table[ Row[ C_ID[Data:12345.0][Sec:12345.0][Type:Double] F_ID[Data:17660][Sec:17660][Type:Long] NAME[Data:Mike Jones][Sec:Mike Jones][Type:String] ] Row[ C_ID[Data:2560.0][Sec:2560.0][Type:Double] NAME[Data:Casey Jones][Sec:Mike Jones][Type:String] ] ]""" # now parse table, and access each row and its defined attributes results = tableDef.parseString(test) for row in results.rows: print row.dump() print row.NAME, row.C_ID print </code></pre> <p>prints:</p> <pre><code>[[[['C_ID', 'Data', '12345.0', 'Sec', '12345.0', 'Type', 'Double'],... - C_ID: 12345.0 - F_ID: 17660 - NAME: Mike Jones Mike Jones 12345.0 [[[['C_ID', 'Data', '2560.0', 'Sec', '2560.0', 'Type', 'Double'], ... - C_ID: 2560.0 - NAME: Casey Jones Casey Jones 2560.0 </code></pre> <p>The results names assigned in assignAttrs give you access to each of your attributes by name. To see if a name has been omitted, just test "if not row.F_ID:".</p>
1
2009-09-07T16:57:32Z
[ "python", "regex", "parsing" ]
What order does SQLAlchemy use for primary key columns?
1,325,018
<p>Let's say I create a table like this:</p> <pre><code>table = Table('mytable', metadata, Column('a', Integer, primary_key=True), Column('b', Integer, primary_key=True), ) table.create() </code></pre> <p>Is it guaranteed that the primary key will be (a,b) and not (b,a)?</p>
0
2009-08-24T22:01:47Z
1,325,106
<p>Yes. It will be a really bad thing if resulting DDL wasn't giving consistent results.</p>
0
2009-08-24T22:24:18Z
[ "python", "sqlalchemy" ]
What order does SQLAlchemy use for primary key columns?
1,325,018
<p>Let's say I create a table like this:</p> <pre><code>table = Table('mytable', metadata, Column('a', Integer, primary_key=True), Column('b', Integer, primary_key=True), ) table.create() </code></pre> <p>Is it guaranteed that the primary key will be (a,b) and not (b,a)?</p>
0
2009-08-24T22:01:47Z
1,325,318
<p>USe echo=True and compare yours with a swapped version? That should give the answer.</p>
1
2009-08-24T23:29:28Z
[ "python", "sqlalchemy" ]
What order does SQLAlchemy use for primary key columns?
1,325,018
<p>Let's say I create a table like this:</p> <pre><code>table = Table('mytable', metadata, Column('a', Integer, primary_key=True), Column('b', Integer, primary_key=True), ) table.create() </code></pre> <p>Is it guaranteed that the primary key will be (a,b) and not (b,a)?</p>
0
2009-08-24T22:01:47Z
1,325,548
<p>its guaranteed, yes, since <code>Column</code> objects in <code>Table</code> are ordered. or if you really want to be explicit, use <code>PrimaryKeyContraint()</code>.</p>
3
2009-08-25T01:00:34Z
[ "python", "sqlalchemy" ]
Generate unique ID for python object based on its attributes
1,325,195
<p>Is there a way to generate a hash-like ID in for objects in python that is solely based on the objects' attribute values? For example, </p> <pre><code>class test: def __init__(self, name): self.name = name obj1 = test('a') obj2 = test('a') hash1 = magicHash(obj1) hash2 = magicHash(obj2) </code></pre> <p>What I'm looking for is something where hash1 == hash2. Does something like this exist in python? I know I can test if obj1.name == obj2.name, but I'm looking for something general I can use on any object.</p>
9
2009-08-24T22:47:22Z
1,325,216
<p>You mean something like this? Using the special method <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fhash%5F%5F" rel="nofollow"><code>__hash__</code></a></p> <pre><code>class test: def __init__(self, name): self.name = name def __hash__(self): return hash(self.name) &gt;&gt;&gt; hash(test(10)) == hash(test(20)) False &gt;&gt;&gt; hash(test(10)) == hash(test(10)) True </code></pre>
6
2009-08-24T22:54:21Z
[ "python", "object", "attributes" ]
Generate unique ID for python object based on its attributes
1,325,195
<p>Is there a way to generate a hash-like ID in for objects in python that is solely based on the objects' attribute values? For example, </p> <pre><code>class test: def __init__(self, name): self.name = name obj1 = test('a') obj2 = test('a') hash1 = magicHash(obj1) hash2 = magicHash(obj2) </code></pre> <p>What I'm looking for is something where hash1 == hash2. Does something like this exist in python? I know I can test if obj1.name == obj2.name, but I'm looking for something general I can use on any object.</p>
9
2009-08-24T22:47:22Z
1,325,231
<p>Have a lool at the <a href="http://docs.python.org/library/functions.html#hash" rel="nofollow">hash() build in function</a> and the <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fhash%5F%5F" rel="nofollow"><code>__hash__()</code> object method</a>. These may be just what you are looking for. You will have to implement <code>__hash__()</code> for you own classes.</p>
2
2009-08-24T22:56:48Z
[ "python", "object", "attributes" ]
Generate unique ID for python object based on its attributes
1,325,195
<p>Is there a way to generate a hash-like ID in for objects in python that is solely based on the objects' attribute values? For example, </p> <pre><code>class test: def __init__(self, name): self.name = name obj1 = test('a') obj2 = test('a') hash1 = magicHash(obj1) hash2 = magicHash(obj2) </code></pre> <p>What I'm looking for is something where hash1 == hash2. Does something like this exist in python? I know I can test if obj1.name == obj2.name, but I'm looking for something general I can use on any object.</p>
9
2009-08-24T22:47:22Z
1,325,234
<p><strong>To get a unique comparison:</strong></p> <p>To be unique you could serialize the data and then compare the serialized value to ensure it matches exactly.</p> <p>Example:</p> <pre><code>import pickle class C: i = 1 j = 2 c1 = C() c2 = C() c3 = C() c1.i = 99 unique_hash1 = pickle.dumps(c1) unique_hash2 = pickle.dumps(c2) unique_hash3 = pickle.dumps(c3) unique_hash1 == unique_hash2 #False unique_hash2 == unique_hash3 #True </code></pre> <p><strong>If you don't need unique values for each object, but mostly unique:</strong></p> <p>Note the same value will always reduce to the same hash, but 2 different values could reduce to the same hash. </p> <p>You cannot use something like the built-in hash() function (unless you override <code>__hash__</code>)</p> <pre><code>hash(c1) == hash(c2) #False hash(c2) == hash(c3) #False &lt;--- Wrong </code></pre> <p>or something like serialize the data using pickle and then use zlib.crc32.</p> <pre><code>import zlib crc1 = zlib.crc32(pickle.dumps(c1)) crc2 = zlib.crc32(pickle.dumps(c2)) crc3 = zlib.crc32(pickle.dumps(c3)) crc1 == crc2 #False crc2 == crc3 #True </code></pre>
3
2009-08-24T22:57:31Z
[ "python", "object", "attributes" ]
Generate unique ID for python object based on its attributes
1,325,195
<p>Is there a way to generate a hash-like ID in for objects in python that is solely based on the objects' attribute values? For example, </p> <pre><code>class test: def __init__(self, name): self.name = name obj1 = test('a') obj2 = test('a') hash1 = magicHash(obj1) hash2 = magicHash(obj2) </code></pre> <p>What I'm looking for is something where hash1 == hash2. Does something like this exist in python? I know I can test if obj1.name == obj2.name, but I'm looking for something general I can use on any object.</p>
9
2009-08-24T22:47:22Z
1,325,275
<p>I guess</p> <pre><code>def hash_attr(ins): return hash(tuple(ins.__dict__.items())) </code></pre> <p>hashes anything instance based on its attributes.</p>
2
2009-08-24T23:16:18Z
[ "python", "object", "attributes" ]
Importing a text file into SQL Server in Python
1,325,481
<p>I am writing a python script that will be doing some processing on text files. As part of that process, i need to import each line of the tab-separated file into a local MS SQL Server (2008) table. I am using pyodbc and I know how to do this. However, I have a question about the best way to execute it.</p> <p>I will be looping through the file, creating a cursor.execute(myInsertSQL) for each line of the file. Does anyone see any problems waiting to commit the statements until all records have been looped (i.e. doing the commit() after the loop and not inside the loop after each individual execute)? The reason I ask is that some files will have upwards of 5000 lines. I didn't know if trying to "save them up" and committing all 5000 at once would cause problems.</p> <p>I am fairly new to python, so I don't know all of these issues yet. </p> <p>Thanks.</p>
1
2009-08-25T00:30:51Z
1,325,524
<p>If I understand what you are doing, Python is not going to be a problem. Executing a statement inside a transaction does not create cumulative state in Python. It will do so only at the database server itself.</p> <p>When you commit you will need to make sure the commit occurred, since having a large batch commit may conflict with intervening changes in the database. If the commit fails, you will have to re-run the batch again.</p> <p>That's the only problem that I am aware of with large batches and Python/ODBC (and it's not even really a Python problem, since you would have that problem regardless.)</p> <p>Now, if you were creating all the SQL in memory, and then looping through the memory-representation, that might make more sense. Still, 5000 lines of text on a modern machine is really not that big of a deal. If you start needing to process two orders of magnitude more, you might need to rethink your process.</p>
0
2009-08-25T00:47:19Z
[ "python", "database", "odbc", "commit", "bulkinsert" ]
Importing a text file into SQL Server in Python
1,325,481
<p>I am writing a python script that will be doing some processing on text files. As part of that process, i need to import each line of the tab-separated file into a local MS SQL Server (2008) table. I am using pyodbc and I know how to do this. However, I have a question about the best way to execute it.</p> <p>I will be looping through the file, creating a cursor.execute(myInsertSQL) for each line of the file. Does anyone see any problems waiting to commit the statements until all records have been looped (i.e. doing the commit() after the loop and not inside the loop after each individual execute)? The reason I ask is that some files will have upwards of 5000 lines. I didn't know if trying to "save them up" and committing all 5000 at once would cause problems.</p> <p>I am fairly new to python, so I don't know all of these issues yet. </p> <p>Thanks.</p>
1
2009-08-25T00:30:51Z
1,325,882
<p>Create a file and use <a href="http://msdn.microsoft.com/en-us/library/ms188365.aspx" rel="nofollow">BULK INSER</a>T. It will be faster.</p>
0
2009-08-25T03:16:43Z
[ "python", "database", "odbc", "commit", "bulkinsert" ]
Mutate an integer array using ctypes
1,325,518
<p>Currently I'm in the process of moving a performance bottleneck in my python code to c, to investigate peformance effects. This code will run a simulation, and report back the results to python via ctypes. However, I'm having problems getting my types to match up correctly.</p> <p>Although I'm looking to solve this particular problem, I'm also on the lookout for more general advice on working with ctypes, as the documentation and procedure seems a bit thin. </p> <p>I have the following c function:</p> <pre><code>extern "C" { void f( int* array, int arraylen ) { for(int i = 0; i &lt; arraylen; i++) { array[i] = g() // mutate the value array[i]; } } } </code></pre> <p>And the following code in python:</p> <pre><code>import ctypes plib = ctypes.cdll.LoadLibrary('./mylib.so') _f = plib.f _f.restype = None _f.argtypes = [ ctypes.POINTER(ctypes.c_int), ctypes.c_int ] seqlen = 50 buffer = ctypes.c_int * seqlen _f( buffer, seqlen ) </code></pre> <p>However, this snippet dies with the following traceback:</p> <pre><code>Traceback (most recent call last): File "particle.py", line 9, in &lt;module&gt; _f( buffer, seqlen ) ctypes.ArgumentError: argument 1: &lt;type 'exceptions.TypeError'&gt;: expected LP_c_int instance instead of _ctypes.ArrayType </code></pre>
4
2009-08-25T00:44:01Z
1,325,533
<p>Looks like you want <a href="http://docs.python.org/library/ctypes.html#type-conversions" rel="nofollow">the cast function</a>:</p> <blockquote> <p>The cast function can be used to cast a ctypes instance into a pointer to a different ctypes data type. cast takes two parameters, a ctypes object that is or can be converted to a pointer of some kind, and a ctypes pointer type. It returns an instance of the second argument, which references the same memory block as the first argument:</p> </blockquote> <pre><code>&gt;&gt;&gt; a = (c_byte * 4)() &gt;&gt;&gt; a &lt;__main__.c_byte_Array_4 object at 0xb7da2df4&gt; &gt;&gt;&gt; cast(a, POINTER(c_int)) &lt;ctypes.LP_c_long object at ...&gt; &gt;&gt;&gt; </code></pre>
4
2009-08-25T00:53:16Z
[ "python", "ctypes" ]
easiest way to program a virtual file system in windows with Python
1,325,568
<p>I want to program a virtual file system in Windows with Python. </p> <p>That is, a program in Python whose interface is actually an "explorer windows". You can create &amp; manipulate file-like objects but instead of being created in the hard disk as regular files they are managed by my program and, say, stored remotely, or encrypted or compressed or versioned, or whatever I can do with Python.</p> <p>What is the easiest way to do that?</p>
9
2009-08-25T01:10:19Z
1,325,652
<p>If you are trying to write a virtual file system (I may misunderstand you) - I would look at a container file format. VHD is well documented along with HDI and (embedded) OSQ. There are basically two things you need to do. One is you need to decide on a file/container format. After that it is as simple as writing the API to manipulate that container. If you would like it to be manipulated over the internet, pick a transport protocol then just write a service (would would emulate a file system driver) that listens on a certain port and manipulates this container using your API</p>
1
2009-08-25T01:45:31Z
[ "python", "windows", "filesystems" ]
easiest way to program a virtual file system in windows with Python
1,325,568
<p>I want to program a virtual file system in Windows with Python. </p> <p>That is, a program in Python whose interface is actually an "explorer windows". You can create &amp; manipulate file-like objects but instead of being created in the hard disk as regular files they are managed by my program and, say, stored remotely, or encrypted or compressed or versioned, or whatever I can do with Python.</p> <p>What is the easiest way to do that?</p>
9
2009-08-25T01:10:19Z
1,325,685
<p>Does it need to be Windows-native? There is at least one protocol which can be both browsed by Windows Explorer, and served by free Python libraries: FTP. Stick your program behind pyftpdlib and you're done.</p>
2
2009-08-25T01:58:36Z
[ "python", "windows", "filesystems" ]
easiest way to program a virtual file system in windows with Python
1,325,568
<p>I want to program a virtual file system in Windows with Python. </p> <p>That is, a program in Python whose interface is actually an "explorer windows". You can create &amp; manipulate file-like objects but instead of being created in the hard disk as regular files they are managed by my program and, say, stored remotely, or encrypted or compressed or versioned, or whatever I can do with Python.</p> <p>What is the easiest way to do that?</p>
9
2009-08-25T01:10:19Z
1,325,941
<p>While perhaps not quite ripe yet (unfortunately I have no first-hand experience with it), <a href="http://code.google.com/p/pywinfuse/">pywinfuse</a> looks <em>exactly</em> like what you're looking for.</p>
8
2009-08-25T03:40:39Z
[ "python", "windows", "filesystems" ]
easiest way to program a virtual file system in windows with Python
1,325,568
<p>I want to program a virtual file system in Windows with Python. </p> <p>That is, a program in Python whose interface is actually an "explorer windows". You can create &amp; manipulate file-like objects but instead of being created in the hard disk as regular files they are managed by my program and, say, stored remotely, or encrypted or compressed or versioned, or whatever I can do with Python.</p> <p>What is the easiest way to do that?</p>
9
2009-08-25T01:10:19Z
5,072,466
<p>Have a look at <a href="https://dokan-dev.github.io/" rel="nofollow">Dokan</a> a User mode filesystem for Windows. There are Ruby, .NET (and Java by 3rd party) bindings available, and I don't think it'll be difficult to write python bindings either.</p>
3
2011-02-21T23:27:44Z
[ "python", "windows", "filesystems" ]
easiest way to program a virtual file system in windows with Python
1,325,568
<p>I want to program a virtual file system in Windows with Python. </p> <p>That is, a program in Python whose interface is actually an "explorer windows". You can create &amp; manipulate file-like objects but instead of being created in the hard disk as regular files they are managed by my program and, say, stored remotely, or encrypted or compressed or versioned, or whatever I can do with Python.</p> <p>What is the easiest way to do that?</p>
9
2009-08-25T01:10:19Z
34,673,049
<p>You might be interested in <a href="http://pyfilesystem.org" rel="nofollow">PyFilesystem</a>;</p> <blockquote> <p><em>A filesystem abstraction layer for Python</em></p> <p>PyFilesystem is an abstraction layer for filesystems. In the same way that Python's file-like objects provide a common way of accessing files, PyFilesystem provides a common way of accessing entire filesystems. You can write platform-independent code to work with local files, that also works with any of the supported filesystems (zip, ftp, S3 etc.).</p> </blockquote> <p>What the description on the homepage does not advertise is that you can then <a href="http://docs.pyfilesystem.org/en/latest/expose.html" rel="nofollow">expose</a> this abstraction again as a filesystem, among others SFTP, FTP (though <a href="https://github.com/PyFilesystem/pyfilesystem/issues/238" rel="nofollow">currently disfunct</a>, probably <a href="https://github.com/PyFilesystem/pyfilesystem/pull/239" rel="nofollow">fixable</a>) and <a href="http://docs.pyfilesystem.org/en/latest/expose/dokan.html" rel="nofollow">dokan</a> (<a href="https://github.com/PyFilesystem/pyfilesystem/issues/236" rel="nofollow">dito</a>) as well as <a href="http://docs.pyfilesystem.org/en/latest/expose/fuse.html" rel="nofollow">fuse</a>.</p>
1
2016-01-08T09:02:20Z
[ "python", "windows", "filesystems" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
1,325,736
<p>Not sure if I completely understand the question, but you can modify instance properties at runtime with the built-in <code>__dict__</code> of your class:</p> <pre><code>class C(object): def __init__(self, ks, vs): self.__dict__ = dict(zip(ks, vs)) if __name__ == "__main__": ks = ['ab', 'cd'] vs = [12, 34] c = C(ks, vs) print(c.ab) # 12 </code></pre>
2
2009-08-25T02:19:32Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
1,325,756
<p>You cannot add a new property() to an instance at runtime, because properties are data descriptors. Instead you must dynamically create a new class, or over <code>__getattribute__</code> in order to process data descriptors on instances.</p>
4
2009-08-25T02:23:36Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
1,325,768
<p>It seems you could solve this problem much more simply with a <a href="http://docs.python.org/library/collections.html#collections.namedtuple"><code>namedtuple</code></a>, since you know the entire list of fields ahead of time.</p> <pre><code>from collections import namedtuple Foo = namedtuple('Foo', ['bar', 'quux']) foo = Foo(bar=13, quux=74) print foo.bar, foo.quux foo2 = Foo() # error </code></pre> <p>If you absolutely need to write your own setter, you'll have to do the metaprogramming at the class level; <code>property()</code> doesn't work on instances.</p>
25
2009-08-25T02:28:05Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
1,325,772
<p>Only way to dynamically attach a property is to create a new class and its instance with your new property. </p> <pre><code>class Holder: p = property(lambda x: vs[i], self.fn_readonly) setattr(self, k, Holder().p) </code></pre>
0
2009-08-25T02:29:19Z
[ "python", "properties", "runtime", "monkeypatching" ]
How to add property to a python class dynamically?
1,325,673
<p>The goal is to create a mock class which behaves like a db resultset.</p> <p>So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see </p> <pre><code>&gt;&gt;&gt; dummy.ab 100 </code></pre> <p>So, at the beginning I thought I maybe able to do it this way</p> <pre><code>ks = ['ab', 'cd'] vs = [12, 34] class C(dict): def __init__(self, ks, vs): for i, k in enumerate(ks): self[k] = vs[i] setattr(self, k, property(lambda x: vs[i], self.fn_readyonly)) def fn_readonly(self, v) raise "It is ready only" if __name__ == "__main__": c = C(ks, vs) print c.ab </code></pre> <p>but "c.ab" returns a property object instead.</p> <p>Replace the setattr line with </p> <pre><code>k = property(lambda x: vs[i]) </code></pre> <p>It is of no use at all.</p> <p>So what is the right way to create an instance property in runtime?</p> <p>P.S. I am aware of an alternative <a href="http://stackoverflow.com/questions/371753/python-using-getattribute-method">here</a></p>
96
2009-08-25T01:53:33Z
1,325,798
<p>You don't need to use a property for that. Just override <code>__setattr__</code> to make them read only.</p> <pre><code>class C(object): def __init__(self, keys, values): for (key, value) in zip(keys, values): self.__dict__[key] = value def __setattr__(self, name, value): raise Exception("It is read only!") </code></pre> <p>Tada.</p> <pre><code>&gt;&gt;&gt; c = C('abc', [1,2,3]) &gt;&gt;&gt; c.a 1 &gt;&gt;&gt; c.b 2 &gt;&gt;&gt; c.c 3 &gt;&gt;&gt; c.d Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'C' object has no attribute 'd' &gt;&gt;&gt; c.d = 42 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 6, in __setattr__ Exception: It is read only! &gt;&gt;&gt; c.a = 'blah' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 6, in __setattr__ Exception: It is read only! </code></pre>
20
2009-08-25T02:41:46Z
[ "python", "properties", "runtime", "monkeypatching" ]