title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
In Python, how to check if a string only contains certain characters?
1,323,364
26
2009-08-24T16:22:05Z
1,323,402
11
2009-08-24T16:28:56Z
[ "python", "regex", "search", "character" ]
In Python, how to check if a string only contains certain characters? I need to check a string containing only a..z, 0..9, and . (period) and no other character. I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow. I am not clear now how to do it with a regular ex...
**EDIT: Changed the regular expression to exclude A-Z** Regular expression solution is the fastest pure python solution so far ``` reg=re.compile('^[a-z0-9\.]+$') >>>reg.match('jsdlfjdsf12324..3432jsdflsdf') True >>> timeit.Timer("reg.match('jsdlfjdsf12324..3432jsdflsdf')", "import re; reg=re.compile('^[a-z0-9\.]+$')...
In Python, how to check if a string only contains certain characters?
1,323,364
26
2009-08-24T16:22:05Z
1,325,265
17
2009-08-24T23:12:00Z
[ "python", "regex", "search", "character" ]
In Python, how to check if a string only contains certain characters? I need to check a string containing only a..z, 0..9, and . (period) and no other character. I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow. I am not clear now how to do it with a regular ex...
**Final(?) edit** Answer, wrapped up in a function, with annotated interactive session: ``` >>> import re >>> def special_match(strg, search=re.compile(r'[^a-z0-9.]').search): ... return not bool(search(strg)) ... >>> special_match("") True >>> special_match("az09.") True >>> special_match("az09.\n") False # The ...
'has_key()' or 'in'?
1,323,410
474
2009-08-24T16:30:15Z
1,323,426
651
2009-08-24T16:33:18Z
[ "python" ]
I wonder what is better to do: ``` d = {'a': 1, 'b': 2} 'a' in d True ``` or: ``` d = {'a': 1, 'b': 2} d.has_key('a') True ```
`in` is definitely more pythonic. In fact [`has_key()` was removed in Python 3.x](http://docs.python.org/3.1/whatsnew/3.0.html#builtins).
'has_key()' or 'in'?
1,323,410
474
2009-08-24T16:30:15Z
1,323,429
48
2009-08-24T16:33:51Z
[ "python" ]
I wonder what is better to do: ``` d = {'a': 1, 'b': 2} 'a' in d True ``` or: ``` d = {'a': 1, 'b': 2} d.has_key('a') True ```
According to python [docs](http://docs.python.org/library/stdtypes.html#dict.has_key): > `has_key()` is deprecated in favor of > `key in d`.
'has_key()' or 'in'?
1,323,410
474
2009-08-24T16:30:15Z
1,323,880
189
2009-08-24T18:12:28Z
[ "python" ]
I wonder what is better to do: ``` d = {'a': 1, 'b': 2} 'a' in d True ``` or: ``` d = {'a': 1, 'b': 2} d.has_key('a') True ```
`in` wins hands-down, not just in elegance (and not being deprecated;-) but also in performance, e.g.: ``` $ 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 ...
'has_key()' or 'in'?
1,323,410
474
2009-08-24T16:30:15Z
1,323,998
11
2009-08-24T18:35:22Z
[ "python" ]
I wonder what is better to do: ``` d = {'a': 1, 'b': 2} 'a' in d True ``` or: ``` d = {'a': 1, 'b': 2} d.has_key('a') True ```
`has_key` is a dictionary method, but `in` will work on any collection, and even when `__contains__` is missing, `in` will use any other method to iterate the collection to find out.
'has_key()' or 'in'?
1,323,410
474
2009-08-24T16:30:15Z
1,325,066
30
2009-08-24T22:11:34Z
[ "python" ]
I wonder what is better to do: ``` d = {'a': 1, 'b': 2} 'a' in d True ``` or: ``` d = {'a': 1, 'b': 2} d.has_key('a') True ```
Use `dict.has_key()` if (and only if) your code is required to be runnable by Python versions earlier than 2.3 (when `key in dict` was introduced).
'has_key()' or 'in'?
1,323,410
474
2009-08-24T16:30:15Z
8,913,940
16
2012-01-18T16:45:39Z
[ "python" ]
I wonder what is better to do: ``` d = {'a': 1, 'b': 2} 'a' in d True ``` or: ``` d = {'a': 1, 'b': 2} d.has_key('a') True ```
There is one example where `in` actually kills your performance. If you use `in` on a O(1) container that only implements `__getitem__` and `has_key()` but not `__contains__` you will turn an O(1) search into an O(N) search (as `in` falls back to a linear search via `__getitem__`). Fix is obviously trivial: ``` def ...
'has_key()' or 'in'?
1,323,410
474
2009-08-24T16:30:15Z
10,512,159
9
2012-05-09T08:06:54Z
[ "python" ]
I wonder what is better to do: ``` d = {'a': 1, 'b': 2} 'a' in d True ``` or: ``` d = {'a': 1, 'b': 2} d.has_key('a') True ```
Python 2.x supports `has_key()`. Python 2.3+ and Python 3.x support `in`.
Python unit test with base and sub class
1,323,455
65
2009-08-24T16:39:41Z
1,323,519
7
2009-08-24T16:52:44Z
[ "python", "unit-testing", "testing" ]
I currently have a few unit tests which share a common set of tests. Here's an example: ``` 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)...
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 `test` so `unittest` won't load them. ``` import unittest class CommonTests(unittest.TestCase): def common_assertion(self, foo, bar, baz): # whatever co...
Python unit test with base and sub class
1,323,455
65
2009-08-24T16:39:41Z
1,323,554
99
2009-08-24T17:00:01Z
[ "python", "unit-testing", "testing" ]
I currently have a few unit tests which share a common set of tests. Here's an example: ``` 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)...
Use multiple inheritance, so your class with common tests doesn't itself inherit from TestCase. ``` import unittest class CommonTests(object): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(unittest.TestCase, CommonTests): ...
Python unit test with base and sub class
1,323,455
65
2009-08-24T16:39:41Z
17,696,807
16
2013-07-17T10:01:59Z
[ "python", "unit-testing", "testing" ]
I currently have a few unit tests which share a common set of tests. Here's an example: ``` 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)...
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): ``` class BaseTest(unittest.TestCase): @classmethod def setUpClass(cls): if cls is BaseTest: raise unittest.SkipTest("S...
Python unit test with base and sub class
1,323,455
65
2009-08-24T16:39:41Z
22,836,015
17
2014-04-03T11:20:31Z
[ "python", "unit-testing", "testing" ]
I currently have a few unit tests which share a common set of tests. Here's an example: ``` 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)...
You can solve this problem with a single command: ``` del(BaseTest) ``` So the code would look like this: ``` import unittest class BaseTest(unittest.TestCase): def testCommon(self): print 'Calling BaseTest:testCommon' value = 5 self.assertEquals(value, 5) class SubTest1(BaseTest): ...
Python unit test with base and sub class
1,323,455
65
2009-08-24T16:39:41Z
25,695,512
47
2014-09-05T23:58:24Z
[ "python", "unit-testing", "testing" ]
I currently have a few unit tests which share a common set of tests. Here's an example: ``` 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)...
Do not use multiple inheritance, it will bite you [later](http://nedbatchelder.com/blog/201210/multiple_inheritance_is_hard.html). Instead you can just move your base class into the separate module or wrap it with the blank class: ``` import unittest class BaseTestCases: class BaseTest(unittest.TestCase): ...
How do I get str.translate to work with Unicode strings?
1,324,067
48
2009-08-24T18:52:52Z
1,324,114
44
2009-08-24T19:02:57Z
[ "python", "unicode", "string" ]
I have the following code: ``` import string def translate_non_alphanumerics(to_translate, translate_to='_'): not_letters_or_digits = u'!"#%\'()*+,-./:;<=>?@[\]^_`{|}~' translate_table = string.maketrans(not_letters_or_digits, translate_to ...
The Unicode version of translate requires a mapping from Unicode ordinals (which you can retrieve for a single character with `ord`) to Unicode ordinals. If you want to delete characters, you map to `None`. I changed your function to build a dict mapping the ordinal of every character to the ordinal of what you want t...
What is the fastest template system for Python?
1,324,238
44
2009-08-24T19:28:00Z
1,324,258
7
2009-08-24T19:30:46Z
[ "python", "django-templates", "template-engine", "mako", "jinja2" ]
Jinja2 and Mako are both apparently pretty fast. How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?
From the [jinja2 docs](http://jinja.pocoo.org/2/documentation/faq), it seems that string.Template is the fastest if that's all you need. > 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 w...
What is the fastest template system for Python?
1,324,238
44
2009-08-24T19:28:00Z
1,326,219
87
2009-08-25T05:28:48Z
[ "python", "django-templates", "template-engine", "mako", "jinja2" ]
Jinja2 and Mako are both apparently pretty fast. How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?
Here are the results of the popular template engines for rendering a 10x1000 HTML table. ``` 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 D...
How to alphabetically sort the values in a many-to-many django-admin box?
1,324,602
7
2009-08-24T20:35:58Z
1,324,649
7
2009-08-24T20:43:49Z
[ "python", "django", "sorting", "django-admin", "many-to-many" ]
I have a simple model like this one: ``` 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 ...
Set [`ordering`](http://docs.djangoproject.com/en/dev/ref/models/options/#ordering) on the Article's inner `Meta` class. ``` class Article(models.Model): .... class Meta: ordering = ['surname', 'name'] ```
easiest way to program a virtual file system in windows with Python
1,325,568
9
2009-08-25T01:10:19Z
1,325,941
8
2009-08-25T03:40:39Z
[ "python", "windows", "filesystems" ]
I want to program a virtual file system in Windows with Python. That is, a program in Python whose interface is actually an "explorer windows". You can create & 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 encry...
While perhaps not quite ripe yet (unfortunately I have no first-hand experience with it), [pywinfuse](http://code.google.com/p/pywinfuse/) looks *exactly* like what you're looking for.
How to add property to a python class dynamically?
1,325,673
96
2009-08-25T01:53:33Z
1,325,768
25
2009-08-25T02:28:05Z
[ "python", "properties", "runtime", "monkeypatching" ]
The goal is to create a mock class which behaves like a db resultset. So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see ``` >>> dummy.ab 100 ``` So, at the beginning I thought I maybe able to do it this way ``` ks = ['ab', 'cd'] vs = [12, 34] class C(dic...
It seems you could solve this problem much more simply with a [`namedtuple`](http://docs.python.org/library/collections.html#collections.namedtuple), since you know the entire list of fields ahead of time. ``` from collections import namedtuple Foo = namedtuple('Foo', ['bar', 'quux']) foo = Foo(bar=13, quux=74) prin...
How to add property to a python class dynamically?
1,325,673
96
2009-08-25T01:53:33Z
1,325,798
20
2009-08-25T02:41:46Z
[ "python", "properties", "runtime", "monkeypatching" ]
The goal is to create a mock class which behaves like a db resultset. So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see ``` >>> dummy.ab 100 ``` So, at the beginning I thought I maybe able to do it this way ``` ks = ['ab', 'cd'] vs = [12, 34] class C(dic...
You don't need to use a property for that. Just override `__setattr__` to make them read only. ``` 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 on...
How to add property to a python class dynamically?
1,325,673
96
2009-08-25T01:53:33Z
1,328,686
34
2009-08-25T14:33:07Z
[ "python", "properties", "runtime", "monkeypatching" ]
The goal is to create a mock class which behaves like a db resultset. So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see ``` >>> dummy.ab 100 ``` So, at the beginning I thought I maybe able to do it this way ``` ks = ['ab', 'cd'] vs = [12, 34] class C(dic...
> The goal is to create a mock class which behaves like a db resultset. So what you want is a dictionary where you can spell a['b'] as a.b? That's easy: ``` class atdict(dict): __getattr__= dict.__getitem__ __setattr__= dict.__setitem__ __delattr__= dict.__delitem__ ```
How to add property to a python class dynamically?
1,325,673
96
2009-08-25T01:53:33Z
1,355,444
170
2009-08-31T01:30:05Z
[ "python", "properties", "runtime", "monkeypatching" ]
The goal is to create a mock class which behaves like a db resultset. So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see ``` >>> dummy.ab 100 ``` So, at the beginning I thought I maybe able to do it this way ``` ks = ['ab', 'cd'] vs = [12, 34] class C(dic...
I suppose I should expand this answer, now that I'm older and wiser and know what's going on. Better late than never. You *can* add a property to a class dynamically. But that's the catch: you have to add it to the *class*. ``` >>> class Foo(object): ... pass ... >>> foo = Foo() >>> foo.a = 3 >>> Foo.b = propert...
Inserting Line at Specified Position of a Text File
1,325,905
26
2009-08-25T03:27:23Z
1,325,927
50
2009-08-25T03:34:13Z
[ "python", "text", "insert" ]
I have a text file which looks like this: ``` blah blah foo1 bar1 foo1 bar2 foo1 bar3 foo2 bar4 foo2 bar5 blah blah ``` Now I want to insert `'foo bar'` between `'foo1 bar3'` and `'foo2 bar4'`. This is how I did it: ``` import shutil txt = '1.txt' tmptxt = '1.txt.tmp' with open(tmptxt, 'w') as outfile: with o...
The best way to make "pseudo-inplace" changes to a file in Python is with the `fileinput` module from the standard library: ``` import fileinput processing_foo1s = False for line in fileinput.input('1.txt', inplace=1): if line.startswith('foo1'): processing_foo1s = True else: if processing_foo1s: p...
Inserting Line at Specified Position of a Text File
1,325,905
26
2009-08-25T03:27:23Z
1,327,523
8
2009-08-25T11:02:47Z
[ "python", "text", "insert" ]
I have a text file which looks like this: ``` blah blah foo1 bar1 foo1 bar2 foo1 bar3 foo2 bar4 foo2 bar5 blah blah ``` Now I want to insert `'foo bar'` between `'foo1 bar3'` and `'foo2 bar4'`. This is how I did it: ``` import shutil txt = '1.txt' tmptxt = '1.txt.tmp' with open(tmptxt, 'w') as outfile: with o...
Recall that an iterator is a first-class object. It can be used in multiple **for** statements. Here's a way to handle this without a lot of complex-looking if-statements and flags. ``` with open(tmptxt, 'w') as outfile: with open(txt, 'r') as infile: rowIter= iter(infile) for row in rowIter: ...
Inserting Line at Specified Position of a Text File
1,325,905
26
2009-08-25T03:27:23Z
6,281,147
11
2011-06-08T15:15:22Z
[ "python", "text", "insert" ]
I have a text file which looks like this: ``` blah blah foo1 bar1 foo1 bar2 foo1 bar3 foo2 bar4 foo2 bar5 blah blah ``` Now I want to insert `'foo bar'` between `'foo1 bar3'` and `'foo2 bar4'`. This is how I did it: ``` import shutil txt = '1.txt' tmptxt = '1.txt.tmp' with open(tmptxt, 'w') as outfile: with o...
Adapting Alex Martelli's example: ``` import fileinput for line in fileinput.input('1.txt', inplace=1): print line, if line.startswith('foo1 bar3'): print 'foo bar' ```
Using sphinx to auto-document a python class, module
1,326,796
20
2009-08-25T08:23:25Z
1,326,893
12
2009-08-25T08:41:23Z
[ "python", "documentation-generation", "python-sphinx" ]
I have installed [Sphinx](http://sphinx.pocoo.org/) in order to document some python modules and class I'm working on. While the markup language looks very nice, I haven't managed to auto-document a python code. Basically, I have the following python module: ``` SegLib.py ``` And A class called `Seg` in it. I would ...
Add to the begining of the file: ``` .. module:: SegLib ``` Try using **:autoclass:** directive for class doc. BTW: module names should be lower\_case. **EDIT:** [I learned a lot from reading other source files](http://almir.readthedocs.org/en/latest/_sources/api.txt).
Append a tuple to a list
1,327,204
2
2009-08-25T09:50:43Z
1,327,227
9
2009-08-25T09:55:59Z
[ "python" ]
Given a tuple (specifically, a functions varargs), I want to prepend a list containing one or more items, then call another function with the result as a list. So far, the best I've come up with is: ``` def fn(*args): l = ['foo', 'bar'] l.extend(args) fn2(l) ``` Which, given Pythons usual terseness when i...
You can convert the tuple to a list, which will allow you to concatenate it to the other list. ie: ``` def fn(*args): fn2(['foo', 'bar'] + list(args)) ```
extract contents of regex
1,327,369
29
2009-08-25T10:24:58Z
1,327,389
45
2009-08-25T10:29:31Z
[ "python", "html", "regex", "html-content-extraction" ]
I want a regular expression to extract the title from a HTML page. Currently I have this: ``` title = re.search('<title>.*</title>', html, re.IGNORECASE).group() if title: title = title.replace('<title>', '').replace('</title>', '') ``` Is there a regular expression to extract just the contents of so I don't have...
Use `(` `)` in regexp and `group(1)` in python to retrieve the captured string (`re.search` will return `None` if it doesn't find the result, so *don't use group() directly*): ``` title_search = re.search('<title>(.*)</title>', html, re.IGNORECASE) if title_search: title = title_search.group(1) ```
extract contents of regex
1,327,369
29
2009-08-25T10:24:58Z
1,327,398
18
2009-08-25T10:31:31Z
[ "python", "html", "regex", "html-content-extraction" ]
I want a regular expression to extract the title from a HTML page. Currently I have this: ``` title = re.search('<title>.*</title>', html, re.IGNORECASE).group() if title: title = title.replace('<title>', '').replace('</title>', '') ``` Is there a regular expression to extract just the contents of so I don't have...
**Please, do NOT use regex to parse markup languages. Use lxml or beautifulsoup.**
python - problems with regular expression and unicode
1,327,731
4
2009-08-25T11:40:25Z
1,327,764
14
2009-08-25T11:47:03Z
[ "python", "regex", "unicode" ]
Hi I have a problem in python. I try to explain my problem with an example. I have this string: ``` >>> string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ' >>> print string ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷Ã...
You need to make sure that your strings are unicode strings, not plain strings (plain strings are like byte arrays). Example: ``` >>> string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ' >>> type(string) <type 'str'> # do this instead: # (note the u in f...
Autodocumenting Python using Sphinx
1,328,041
15
2009-08-25T12:42:38Z
1,328,264
35
2009-08-25T13:26:39Z
[ "python", "documentation-generation", "python-sphinx" ]
This is a generalized version of a [previous question regarding Sphinx](http://stackoverflow.com/questions/1326796/using-sphinx-to-auto-document-a-python-class-module). Is there a way to recursively autodocument modules or packages which contain classes and functions within them? I think it is silly to add the `autof...
We use ``` .. automodule:: module :members: ```
Autodocumenting Python using Sphinx
1,328,041
15
2009-08-25T12:42:38Z
1,328,722
21
2009-08-25T14:37:36Z
[ "python", "documentation-generation", "python-sphinx" ]
This is a generalized version of a [previous question regarding Sphinx](http://stackoverflow.com/questions/1326796/using-sphinx-to-auto-document-a-python-class-module). Is there a way to recursively autodocument modules or packages which contain classes and functions within them? I think it is silly to add the `autof...
To make things easier you can use this script (look at the bottom of the page for the last version): <http://bitbucket.org/birkenfeld/sphinx/issue/98/add-the-autogenerate-script-to-sphinx> This script will parse your packages/modules and generate all the rest files necessary to build the doc from docstrings. I'm the ...
Autodocumenting Python using Sphinx
1,328,041
15
2009-08-25T12:42:38Z
5,141,321
15
2011-02-28T11:22:50Z
[ "python", "documentation-generation", "python-sphinx" ]
This is a generalized version of a [previous question regarding Sphinx](http://stackoverflow.com/questions/1326796/using-sphinx-to-auto-document-a-python-class-module). Is there a way to recursively autodocument modules or packages which contain classes and functions within them? I think it is silly to add the `autof...
Etienne's script, mentioned in his answer, has now been integrated into Sphinx as sphinx-apidoc. It does exactly what the OP wants. It is slated for release in Sphinx 1.1, or is available from the Hg repo: <https://bitbucket.org/birkenfeld/sphinx> It works beautifully for me. The docs read thus: ``` > sphinx-apidoc ...
SHA256 hash in Python 2.4
1,328,155
7
2009-08-25T13:04:25Z
1,328,162
10
2009-08-25T13:06:42Z
[ "python", "sha256", "python-2.4" ]
Is there a way I can calculate a SHA256 hash in Python 2.4 ? (I emphasize: Python 2.4) I know how to do it in Python 2.5 but unfortunately it's not available on my server and an upgrade will not be made. I have the same problem as the guy in [this](http://stackoverflow.com/questions/1306550/calculating-a-sha-hash-with-...
Yes you can. With Python 2.4, there was SHA-1 module which does exactly this. See [the documentation](http://www.python.org/doc/2.4/lib/module-sha.html). However, bear in mind that code importing from this module will cause DeprecationWarnings when run with newer Python. Ok, as the requirement was tightened to be SHA...
SHA256 hash in Python 2.4
1,328,155
7
2009-08-25T13:04:25Z
1,328,203
8
2009-08-25T13:13:16Z
[ "python", "sha256", "python-2.4" ]
Is there a way I can calculate a SHA256 hash in Python 2.4 ? (I emphasize: Python 2.4) I know how to do it in Python 2.5 but unfortunately it's not available on my server and an upgrade will not be made. I have the same problem as the guy in [this](http://stackoverflow.com/questions/1306550/calculating-a-sha-hash-with-...
You can use the `sha` module, if you want to stay compatible, you can import it like this: ``` try: from hashlib import sha1 except ImportError: from sha import sha as sha1 ```
Python/PySerial and CPU usage
1,328,606
9
2009-08-25T14:20:37Z
1,328,675
9
2009-08-25T14:31:57Z
[ "python", "cpu-usage", "pyserial" ]
I've created a script to monitor the output of a serial port that receives 3-4 lines of data every half hour - the script runs fine and grabs everything that comes off the port which at the end of the day is what matters... What bugs me, however, is that the cpu usage seems rather high for a program that's just monito...
Maybe you could issue a blocking `read(1)` call, and when it succeeds use `read(inWaiting())` to get the right number of remaining bytes.
How do I use colour with Windows command prompt using Python?
1,328,643
10
2009-08-25T14:26:47Z
1,328,961
21
2009-08-25T15:17:23Z
[ "python", "windows", "command-prompt", "waf" ]
I'm trying to patch a [waf issue](http://code.google.com/p/waf/issues/detail?id=243), where the Windows command prompt output isn't coloured when it's supposed to be. I'm trying to figure out how to actually implement this patch, but I'm having trouble finding sufficient resources - could someone point me in right dire...
It is possible thanks to ctypes and [SetConsoleTextAttribute](http://msdn.microsoft.com/en-us/library/ms686047%28VS.85%29.aspx) Here is an example ``` from ctypes import * STD_OUTPUT_HANDLE_ID = c_ulong(0xfffffff5) windll.Kernel32.GetStdHandle.restype = c_ulong std_output_hdl = windll.Kernel32.GetStdHandle(STD_OUTPUT...
Gender problem in a django i18n translation
1,329,115
10
2009-08-25T15:39:26Z
3,436,409
9
2010-08-08T22:57:34Z
[ "python", "django", "localization", "internationalization" ]
I need to solve a gender translation problem, and Django doesn't seem to have [gettext contexts](http://www.gnu.org/software/gettext/manual/gettext.html#Contexts) implemented yet... I need to translate from english: ``` <p>Welcome, {{ username }}</p> ``` In two forms of spanish, one for each gender. If user is a mal...
The way that I've solved this is: ``` {% if profile.male %} {% blocktrans with profile.name as male %}Welcome, {{ male }}{% endblocktrans %} {% else %} {% blocktrans with profile.name as female %}Welcome, {{ female }}{% endblocktrans %} {% endif %} ```
Python/Suds: Type not found: 'xs:complexType'
1,329,190
9
2009-08-25T15:53:16Z
1,360,535
14
2009-09-01T04:33:49Z
[ "python", "soap", "suds" ]
I have the following simple python test script that uses [Suds](https://fedorahosted.org/suds/) to call a SOAP web service (the service is written in ASP.net): ``` from suds.client import Client url = 'http://someURL.asmx?WSDL' client = Client( url ) result = client.service.GetPackageDetails( "MyPackage" ) print ...
**Ewall**'s resource is a good one. If you try to search in suds trac tickets, you could see that other people have problems [similar to yours](https://fedorahosted.org/suds/ticket/220), but with different object types. It can be a good way to learn from it's examples and how they import their namespaces. > The proble...
What is cross browser support for JavaScript 1.7's new features? Specifically array comprehensions and the "let" statement
1,330,498
16
2009-08-25T19:41:34Z
1,330,566
9
2009-08-25T19:54:28Z
[ "javascript", "python", "arrays", "internet-explorer", "cross-browser" ]
<https://developer.mozilla.org/en/New_in_JavaScript_1.7> A lot of these new features are borrowed from Python, and would allow the creation of less verbose apps, which is always a good thing. How many times have you typed ``` for (i = 0; i < arr.length; i++) { /* ... */ } ``` for really simple operations? Wouldn...
No, when they say "JavaScript", they mean it literally: the ECMAScript engine used by Gecko. JScript and other engines (AFAIK) don't support these features. EDIT: According to [wikipedia](http://en.wikipedia.org/wiki/ECMAScript#Version%5Fcorrespondence), JavaScript 1.7 implements ECMAScript "Edition 3 plus all JavaScr...
What is cross browser support for JavaScript 1.7's new features? Specifically array comprehensions and the "let" statement
1,330,498
16
2009-08-25T19:41:34Z
2,209,743
33
2010-02-05T19:20:40Z
[ "javascript", "python", "arrays", "internet-explorer", "cross-browser" ]
<https://developer.mozilla.org/en/New_in_JavaScript_1.7> A lot of these new features are borrowed from Python, and would allow the creation of less verbose apps, which is always a good thing. How many times have you typed ``` for (i = 0; i < arr.length; i++) { /* ... */ } ``` for really simple operations? Wouldn...
While this question is a bit old, and is marked "answered" - I found it on Google and the answers given are possibly inaccurate, or if not, definitely incomplete. It's very important to note that Javascript is NOT A STANDARD. Ken correctly mentioned that ECMAScript is the cross-browser standard that all browsers aim t...
Converting list of integers into a binary "string" in python
1,331,187
3
2009-08-25T21:42:35Z
1,331,227
9
2009-08-25T21:50:56Z
[ "python", "string", "list", "binary" ]
I have a list of numbers that i would like to send out onto a socket connection as binary data. As an example, i start off with the following list: ``` data = [2,25,0,0,ALPHA,0,23,18,188] ``` In the above list, **ALPHA** can be any value between 1 and 999. Initially, I was converting this into a string using ``` h...
You want to send a single byte for ALPHA if it's < 256, but two bytes if >= 256? This seems weird -- how is the receiver going to know which is the case...??? But, if this IS what you want, then ``` x = struct.pack(4*'B' + 'HB'[ALPHA<256] + 4*'B', *data) ``` is one way to achieve this.
In-memory size of a Python structure
1,331,471
57
2009-08-25T22:56:35Z
1,331,541
82
2009-08-25T23:13:48Z
[ "python", "memory", "memory-footprint" ]
Is there a reference for the memory size of Python data stucture on 32- and 64-bit platforms? If not, this would be nice to have it on SO. The more exhaustive the better! So how many bytes are used by the following Python structures (depending on the `len` and the content type when relevant)? * `int` * `float` * refe...
The recommendation from [an earlier question](http://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python) on this was to use [sys.getsizeof()](http://docs.python.org/library/sys.html#sys.getsizeof), quoting: ``` >>> import sys >>> x = 2 >>> sys.getsizeof(x) 14 >>> sys.getsizeof(sys.ge...
In-memory size of a Python structure
1,331,471
57
2009-08-25T22:56:35Z
1,331,952
29
2009-08-26T01:45:10Z
[ "python", "memory", "memory-footprint" ]
Is there a reference for the memory size of Python data stucture on 32- and 64-bit platforms? If not, this would be nice to have it on SO. The more exhaustive the better! So how many bytes are used by the following Python structures (depending on the `len` and the content type when relevant)? * `int` * `float` * refe...
I've been happily using [pympler](http://code.google.com/p/pympler/) for such tasks. It's compatible with many versions of Python -- the `asizeof` module in particular goes back to 2.2! For example, using hughdbrown's example but with `from pympler import asizeof` at the start and `print asizeof.asizeof(v)` at the end...
Regular Expression to match cross platform newline characters
1,331,815
33
2009-08-26T00:54:20Z
1,331,840
64
2009-08-26T01:02:00Z
[ "python", "regex", "cross-platform", "eol" ]
My program can accept data that has newline characters of \n, \r\n or \r (eg Unix, PC or Mac styles) What is the best way to construct a regular expression that will match whatever the encoding is? Alternatively, I could use universal\_newline support on input, but now I'm interested to see what the regex would be.
The regex I use when I want to be precise is `"\r\n?|\n"`. When I'm not concerned about consistency or empty lines, I use `"[\r\n]+"`, I imagine it makes my programs somewhere in the order of 0.2% faster.
django template system, calling a function inside a model
1,333,189
46
2009-08-26T08:31:03Z
1,333,277
64
2009-08-26T08:51:17Z
[ "python", "django", "django-models", "django-templates" ]
I want to call a function from my model at a template such as: ``` class ChannelStatus(models.Model): .............................. .............................. def get_related_deltas(self,epk): mystring = "" if not self.get_error_code_delta(epk): return mystring else: for i in sel...
You can't call a function with parameters from the template. You can only do this in the view. Alternatively you could write a [custom template filter](https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#writing-custom-template-filters), which might look like this: ``` @register.filter def related_deltas...
django template system, calling a function inside a model
1,333,189
46
2009-08-26T08:31:03Z
13,367,016
20
2012-11-13T19:03:03Z
[ "python", "django", "django-models", "django-templates" ]
I want to call a function from my model at a template such as: ``` class ChannelStatus(models.Model): .............................. .............................. def get_related_deltas(self,epk): mystring = "" if not self.get_error_code_delta(epk): return mystring else: for i in sel...
If the method doesn't require any arguments, you can use the @property decorator and access it normally in the template. ``` class ChannelStatus(models.Model): ... @property def function_you_want_as_property(self): mystring = "" ... ```
Python: Set with only existence check?
1,333,381
8
2009-08-26T09:13:44Z
1,333,414
10
2009-08-26T09:18:59Z
[ "python", "data-structures", "hash", "set" ]
I have a set of lots of big long strings that I want to do existence lookups for. I don't need the whole string ever to be saved. As far as I can tell, the `set()` actually stored the string which is eating up a lot of my memory. Does such a data structure exist? ``` done = hash_only_set() while len(queue) > 0 : i...
It's certainly possible to keep a set of only hashes: ``` done = set() while len(queue) > 0 : item = queue.pop() h = hash(item) if h not in done : process(item) done.add(h) ``` Notice that because of hash collisions, there is a chance that you consider an item done even though it isn't. If you c...
Delete None values from Python dict
1,334,020
8
2009-08-26T11:21:15Z
1,334,038
18
2009-08-26T11:24:05Z
[ "python" ]
Newbie to Python, so this may seem silly. I have two dicts: ``` default = {'a': 'alpha', 'b': 'beta', 'g': 'Gamma'} user = {'a': 'NewAlpha', 'b': None} ``` I need to update my defaults with the values that exist in user. But only for those that have a value not equal to None. So I need to get back a new dict: ``` r...
``` result = default.copy() result.update((k, v) for k, v in user.iteritems() if v is not None) ```
Delete None values from Python dict
1,334,020
8
2009-08-26T11:21:15Z
1,334,040
7
2009-08-26T11:24:06Z
[ "python" ]
Newbie to Python, so this may seem silly. I have two dicts: ``` default = {'a': 'alpha', 'b': 'beta', 'g': 'Gamma'} user = {'a': 'NewAlpha', 'b': None} ``` I need to update my defaults with the values that exist in user. But only for those that have a value not equal to None. So I need to get back a new dict: ``` r...
With the `update()` method, and some generator expression: ``` D.update((k, v) for k, v in user.iteritems() if v is not None) ```
How to change baseclass
1,334,222
3
2009-08-26T12:02:05Z
1,334,242
7
2009-08-26T12:06:52Z
[ "python", "dynamic", "class" ]
I have a class which is derived from a base class, and have many many lines of code e.g. ``` class AutoComplete(TextCtrl): ..... ``` What I want to do is change the baseclass so that it works like ``` class AutoComplete(PriceCtrl): ..... ``` I have use for both type of AutoCompletes and may be would like t...
You could have a factory for your classes: ``` def completefactory(baseclass): class AutoComplete(baseclass): pass return AutoComplete ``` And then use: ``` TextAutoComplete = completefactory(TextCtrl) PriceAutoComplete = completefactory(PriceCtrl) ``` On the other hand depending on what you want to...
percentage difference between two text files
1,334,725
4
2009-08-26T13:34:15Z
1,334,758
19
2009-08-26T13:39:05Z
[ "python", "linux", "algorithm", "language-agnostic" ]
I know that I can use cmp, diff, etc to compare two files, but what I am looking for is a utility that gives me percentage difference between two files. if there is no such utility, any algorithm would do fine too. I have read about fuzzy programming, but I have not quite understand it.
You can use difflib.SequenceMatcher [ratio](http://docs.python.org/library/difflib.html#difflib.SequenceMatcher.ratio) method From the documentation: > Return a measure of the > sequences’ similarity as a float in > the range [0, 1]. For example: ``` from difflib import SequenceMatcher text1 = open(file1).read() ...
Iteration over list slices
1,335,392
19
2009-08-26T15:04:04Z
1,335,456
7
2009-08-26T15:12:18Z
[ "python", "loops", "iteration", "slice" ]
Good day function-wizards, I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ. In my mind it is something like: ``` for list_of_x_items in fatherList: foo(list_of_x_items) ``` Is there a way to properly define `list_of_x_items` or some other way of doing this...
Do you mean something like: ``` def callonslices(size, fatherList, foo): for i in xrange(0, len(fatherList), size): foo(fatherList[i:i+size]) ``` If this is roughly the functionality you want you might, if you desire, dress it up a bit in a generator: ``` def sliceup(size, fatherList): for i in xrange(0, len...
Iteration over list slices
1,335,392
19
2009-08-26T15:04:04Z
1,335,572
18
2009-08-26T15:28:54Z
[ "python", "loops", "iteration", "slice" ]
Good day function-wizards, I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ. In my mind it is something like: ``` for list_of_x_items in fatherList: foo(list_of_x_items) ``` Is there a way to properly define `list_of_x_items` or some other way of doing this...
If you want to be able to consume any iterable you can use these functions: ``` from itertools import chain, islice def ichunked(seq, chunksize): """Yields items from an iterator in iterable chunks.""" it = iter(seq) while True: yield chain([it.next()], islice(it, chunksize-1)) def chunked(seq, c...
Iteration over list slices
1,335,392
19
2009-08-26T15:04:04Z
1,335,618
48
2009-08-26T15:35:05Z
[ "python", "loops", "iteration", "slice" ]
Good day function-wizards, I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ. In my mind it is something like: ``` for list_of_x_items in fatherList: foo(list_of_x_items) ``` Is there a way to properly define `list_of_x_items` or some other way of doing this...
If you want to divide a list into slices you can use this trick: ``` list_of_slices = zip(*(iter(the_list),) * slice_size) ``` For example ``` >>> zip(*(iter(range(10)),) * 3) [(0, 1, 2), (3, 4, 5), (6, 7, 8)] ``` If the number of items is not dividable by the slice size and you want to pad the list with None you c...
Iteration over list slices
1,335,392
19
2009-08-26T15:04:04Z
1,336,821
7
2009-08-26T19:02:07Z
[ "python", "loops", "iteration", "slice" ]
Good day function-wizards, I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ. In my mind it is something like: ``` for list_of_x_items in fatherList: foo(list_of_x_items) ``` Is there a way to properly define `list_of_x_items` or some other way of doing this...
### Answer to the last part of the question: > question update: How to modify the > function you have provided to store > the extra items and use them when the > next fatherList is fed to the > function? If you need to store state then you can use an object for that. ``` class Chunker(object): """Split `iterable...
Keyboard input with timeout in Python
1,335,507
16
2009-08-26T15:19:05Z
1,336,751
10
2009-08-26T18:50:00Z
[ "python", "timeout", "keyboard-input" ]
How would you prompt the user for some input but timing out after N seconds? Google is pointing to a mail thread about it at <http://mail.python.org/pipermail/python-list/2006-January/533215.html> but it seems not to work. The statement in which the timeout happens, no matter whether it is a sys.input.readline or time...
The example you have linked to is wrong and the exception is actually occuring when calling alarm handler instead of when read blocks. Better try this: ``` import signal TIMEOUT = 5 # number of seconds your want for timeout def interrupted(signum, frame): "called when read times out" print 'interrupted!' sign...
Keyboard input with timeout in Python
1,335,507
16
2009-08-26T15:19:05Z
2,904,057
45
2010-05-25T11:18:11Z
[ "python", "timeout", "keyboard-input" ]
How would you prompt the user for some input but timing out after N seconds? Google is pointing to a mail thread about it at <http://mail.python.org/pipermail/python-list/2006-January/533215.html> but it seems not to work. The statement in which the timeout happens, no matter whether it is a sys.input.readline or time...
Using a select call is shorter, and should be much more portable ``` import sys, select print "You have ten seconds to answer!" i, o, e = select.select( [sys.stdin], [], [], 10 ) if (i): print "You said", sys.stdin.readline().strip() else: print "You said nothing!" ```
Is it a good idea to hash a Python class?
1,335,556
4
2009-08-26T15:27:15Z
1,335,582
7
2009-08-26T15:29:36Z
[ "python", "class", "inheritance", "hash", "dictionary" ]
For example, suppose I do this: ``` >>> class foo(object): ... pass ... >>> class bar(foo): ... pass ... >>> some_dict = { foo : 'foo', ... bar : 'bar'} >>> >>> some_dict[bar] 'bar' >>> some_dict[foo] 'foo' >>> hash(bar) 165007700 >>> id(bar) 165007700 ``` Based on that, it looks like the class is getting ...
Yes, any object that doesn't implement a `__hash__()` function will return its id when hashed. From [Python Language Reference: Data Model - Basic Customization](http://docs.python.org/reference/datamodel.html#object.%5F%5Fhash%5F%5F): > User-defined classes have `__cmp__()` and `__hash__()` methods by default; with t...
job queue implementation for python
1,336,489
13
2009-08-26T18:01:08Z
3,303,367
12
2010-07-21T20:08:00Z
[ "python", "job-queue" ]
Do you know/use any distributed job queue for python? Can you share links or tools
Pyres is a resque clone built in python. Resque is used by Github as their message queue. Both use Redis as the queue backend and provide a web-based monitoring application. <http://binarydud.github.com/pyres/intro.html>
Example of subclassing string.Template in Python?
1,336,786
13
2009-08-26T18:54:53Z
1,336,851
19
2009-08-26T19:07:40Z
[ "python", "stringtemplate" ]
I haven't been able to find a good example of subclassing string.Template in Python, even though I've seen multiple references to doing so in documentation. Are there any examples of this on the web? I want to change the $ to be a different character and maybe change the regex for identifiers.
From python [docs](http://docs.python.org/library/string.html): > Advanced usage: you can derive > subclasses of Template to customize > the placeholder syntax, delimiter > character, or the entire regular > expression used to parse template > strings. To do this, you can override > these class attributes: > > delimit...
Dictionary vs Object - which is more efficient and why?
1,336,791
76
2009-08-26T18:55:45Z
1,336,829
10
2009-08-26T19:03:57Z
[ "python", "performance", "dictionary", "object" ]
What is more efficient in Python in terms of memory usage and CPU consumption - Dictionary or Object? **Background:** I have to load huge amount of data into Python. I created an object that is just a field container. Creating 4M instances and putting them into a dictionary took about 10 minutes and ~6GB of memory. Af...
Attribute access in an object uses dictionary access behind the scenes - so by using attribute access you are adding extra overhead. Plus in the object case, you are incurring additional overhead because of e.g. additional memory allocations and code execution (e.g. of the `__init__` method). In your code, if `o` is a...
Dictionary vs Object - which is more efficient and why?
1,336,791
76
2009-08-26T18:55:45Z
1,336,890
107
2009-08-26T19:17:25Z
[ "python", "performance", "dictionary", "object" ]
What is more efficient in Python in terms of memory usage and CPU consumption - Dictionary or Object? **Background:** I have to load huge amount of data into Python. I created an object that is just a field container. Creating 4M instances and putting them into a dictionary took about 10 minutes and ~6GB of memory. Af...
Have you tried using `__slots__`? From the documentation <http://docs.python.org/reference/datamodel.html#slots>: "By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute w...
Dictionary vs Object - which is more efficient and why?
1,336,791
76
2009-08-26T18:55:45Z
1,338,150
7
2009-08-26T23:39:22Z
[ "python", "performance", "dictionary", "object" ]
What is more efficient in Python in terms of memory usage and CPU consumption - Dictionary or Object? **Background:** I have to load huge amount of data into Python. I created an object that is just a field container. Creating 4M instances and putting them into a dictionary took about 10 minutes and ~6GB of memory. Af...
Have you considered using a [namedtuple](http://docs.python.org/library/collections.html)? ([link for python 2.4/2.5](http://code.activestate.com/recipes/500261/)) It's the new standard way of representing structured data that gives you the performance of a tuple and the convenience of a class. It's only downside com...
SQLAlchemy Inheritance
1,337,095
38
2009-08-26T19:57:53Z
1,337,871
57
2009-08-26T22:25:10Z
[ "python", "inheritance", "sqlalchemy" ]
I'm a bit confused about inheritance under sqlalchemy, to the point where I'm not even sure what type of inheritance (single table, joined table, concrete) I should be using here. I've got a base class with some information that's shared amongst the subclasses, and some data that are completely separate. Sometimes, I'l...
Choosing how to represent the inheritance is mostly a database design issue. For performance single table inheritance is usually best. From a good database design point of view, joined table inheritance is better. Joined table inheritance enables you to have foreign keys to subclasses enforced by the database, it's a l...
SQLAlchemy Inheritance
1,337,095
38
2009-08-26T19:57:53Z
1,337,957
8
2009-08-26T22:42:50Z
[ "python", "inheritance", "sqlalchemy" ]
I'm a bit confused about inheritance under sqlalchemy, to the point where I'm not even sure what type of inheritance (single table, joined table, concrete) I should be using here. I've got a base class with some information that's shared amongst the subclasses, and some data that are completely separate. Sometimes, I'l...
Ants Aasma's solution is much more elegant, but if you are keeping your Class definitions separate from your table definitions intentionally, you need to map your classes to your tables with the mapper function. After you have defined your classes, you need to define your tables: ``` building = Table('building', metad...
Is there a Python module for converting RTF to plain text?
1,337,446
20
2009-08-26T20:56:59Z
1,337,815
7
2009-08-26T22:10:09Z
[ "python", "text", "rtf" ]
Ideally, I'd like a module or library that doesn't require superuser access to install; I have limited privileges in my working environment.
OpenOffice has a RTF reader. You can use python to script OpenOffice, [see here for more info](http://wiki.services.openoffice.org/wiki/Python). You could probably try using the magic com-object on Windows to read anything that smells ms-binary. I wouldn't recommend that though. Actually parsing the raw data probably...
Is there a Python module for converting RTF to plain text?
1,337,446
20
2009-08-26T20:56:59Z
1,821,405
36
2009-11-30T18:07:06Z
[ "python", "text", "rtf" ]
Ideally, I'd like a module or library that doesn't require superuser access to install; I have limited privileges in my working environment.
I've been working on a library called Pyth, which can do this: <http://pypi.python.org/pypi/pyth/> Converting an RTF file to plaintext looks something like this: ``` from pyth.plugins.rtf15.reader import Rtf15Reader from pyth.plugins.plaintext.writer import PlaintextWriter doc = Rtf15Reader.read(open('sample.rtf'))...
Python object @property
1,337,935
6
2009-08-26T22:39:35Z
1,337,976
9
2009-08-26T22:47:45Z
[ "python", "new-style-class" ]
I'm trying to create a point class which defines a property called "coordinate". However, it's not behaving like I'd expect and I can't figure out why. ``` class Point: def __init__(self, coord=None): self.x = coord[0] self.y = coord[1] @property def coordinate(self): return (self....
The `property` method (and by extension, the `@property` decorator) [requires a new-style class](http://docs.python.org/library/functions.html#property) i.e. a class that subclasses `object`. For instance, ``` class Point: ``` should be ``` class Point(object): ``` Also, the `setter` attribute (along with the othe...
One-liner Python code for setting string to 0 string if empty
1,338,518
10
2009-08-27T02:12:49Z
1,338,529
11
2009-08-27T02:15:50Z
[ "python", "string" ]
What is a one-liner code for setting a string in python to the string, 0 if the string is empty? ``` # line_parts[0] can be empty # if so, set a to the string, 0 # one-liner solution should be part of the following line of code if possible a = line_parts[0] ... ```
``` a = '0' if not line_parts[0] else line_parts[0] ```
One-liner Python code for setting string to 0 string if empty
1,338,518
10
2009-08-27T02:12:49Z
1,338,532
45
2009-08-27T02:16:41Z
[ "python", "string" ]
What is a one-liner code for setting a string in python to the string, 0 if the string is empty? ``` # line_parts[0] can be empty # if so, set a to the string, 0 # one-liner solution should be part of the following line of code if possible a = line_parts[0] ... ```
``` a = line_parts[0] or "0" ``` This is one of the nicest Python idioms, making it easy to provide default values. It's often used like this for default values of functions: ``` def fn(arg1, arg2=None): arg2 = arg2 or ["weird default value"] ```
Good way of handling NoneType objects when printing in Python
1,338,690
4
2009-08-27T03:22:55Z
1,338,726
8
2009-08-27T03:39:36Z
[ "python", "string" ]
How do I go about printin a NoneType object in Python? ``` # score can be a NonType object logging.info("NEW_SCORE : "+score) ``` Also why is that sometime I see a comma instead of the + above?
The best approach is: ``` logging.info("NEW_SCORE: %s", score) ``` In most contexts, you'd have to use a `%` operator between the format string on the left and the value(s) on the right (in a tuple, if more than one). But the `logging` functions are special: you pass the format string as the first argument, then, one...
Accesing dictionary with class attribute
1,338,714
4
2009-08-27T03:34:08Z
1,338,737
7
2009-08-27T03:42:05Z
[ "python", "dictionary" ]
now i am working with python. So one question about dict .... suppose i have a dict that ``` config = {'account_receivable': '4', 'account_payable': '5', 'account_cogs': '8', 'accoun t_retained_earning': '9', 'account_income': '6', 'account_expense': '31', 'durat ion': 2, 'financial_year_month': 9, 'financial_year_day...
You can do this with collections.namedtuple: ``` from collections import namedtuple config_object = namedtuple('ConfigClass', config.keys())(*config.values()) print config_object.account_receivable ``` You can learn more about namedtuple here: <http://docs.python.org/dev/library/collections.html>
Accesing dictionary with class attribute
1,338,714
4
2009-08-27T03:34:08Z
1,338,739
12
2009-08-27T03:42:59Z
[ "python", "dictionary" ]
now i am working with python. So one question about dict .... suppose i have a dict that ``` config = {'account_receivable': '4', 'account_payable': '5', 'account_cogs': '8', 'accoun t_retained_earning': '9', 'account_income': '6', 'account_expense': '31', 'durat ion': 2, 'financial_year_month': 9, 'financial_year_day...
For that purpose, lo that many years ago, I invented the simple `Bunch` idiom; one simple way to implement `Bunch` is: ``` class Bunch(object): def __init__(self, adict): self.__dict__.update(adict) ``` If `config` is a dict, you can't use `config.account_receivable` -- that's absolutely impossible, because a d...
Is it crazy to not rely on a caching system like memcached nowadays ( for dynamic sites )?
1,338,777
2
2009-08-27T03:57:36Z
1,338,828
9
2009-08-27T04:18:05Z
[ "php", "python", "memcached", "scalability" ]
I was just reviewing one of my client's applications which uses some old outdated php framework that doesn't rely on caching at all and is pretty much completely database dependent. I figure I'll just rewrite it from scratch because it's *really* outdated and in this rewrite I want to implement a caching system. It'd ...
Caching, when it works right (==high hit rate), is one of the few general-purpose techniques that can really help with *latency* -- the harder part of problems generically describes as "performance". You can enhance *QPS* (queries per second) measures of performance just by throwing more hardware at the problem -- but ...
Python: Memory leak debugging
1,339,293
24
2009-08-27T06:55:41Z
1,343,115
18
2009-08-27T18:52:29Z
[ "python", "django", "debugging", "memory-leaks" ]
I have a small multithreaded script running in django and over time its starts using more and more memory. Leaving it for a full day eats about 6GB of RAM and I start to swap. Following <http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks> I see this as the most common types (with only 800M of memory use...
Is DEBUG=False in settings.py? If not Django will happily store all the SQL queries you make which adds up.
Python: Memory leak debugging
1,339,293
24
2009-08-27T06:55:41Z
4,957,480
29
2011-02-10T13:10:05Z
[ "python", "django", "debugging", "memory-leaks" ]
I have a small multithreaded script running in django and over time its starts using more and more memory. Leaving it for a full day eats about 6GB of RAM and I start to swap. Following <http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks> I see this as the most common types (with only 800M of memory use...
See <http://opensourcehacker.com/2008/03/07/debugging-django-memory-leak-with-trackrefs-and-guppy/> . Short answer: if you're running django but not in a web-request-based format, you need to manually run `db.reset_queries()` (and of course have DEBUG=False, as others have mentioned). Django automatically does `reset_q...
How to add bi-directional manytomanyfields in django admin?
1,339,409
11
2009-08-27T07:31:08Z
1,452,189
8
2009-09-20T22:29:06Z
[ "python", "django", "django-models" ]
In my models.py i have something like: ``` class LocationGroup(models.Model): name = models.CharField(max_length=200) class Report(models.Model): name = models.CharField(max_length=200) locationgroups = models.ManyToManyField(LocationGroup) ``` admin.py (standard): ``` admin.site.register(LocationGroup)...
The workaround I found was to follow the instructions for [ManyToManyFields with intermediary models](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models). Even though you're not using the 'through' model feature, just pretend as if you were and create a stub model with...
Should Python unittests be in a separate module?
1,340,892
14
2009-08-27T12:52:34Z
1,340,934
9
2009-08-27T13:00:42Z
[ "python", "unit-testing", "testing" ]
Is there a consensus about the best place to put Python unittests? Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (`if __name__ == '__main__'`, etc.)), or is it better to include the unittests within different modules? Perhaps a co...
Personally, I create a tests/ folder in my source directory and try to, more or less, mirror my main source code hierarchy with unit test equivalents (having 1 module = 1 unit test module as a rule of thumb). Note that I'm using [nose](http://code.google.com/p/python-nose/) and its philosophy is a bit different than u...
Should Python unittests be in a separate module?
1,340,892
14
2009-08-27T12:52:34Z
1,341,053
8
2009-08-27T13:18:00Z
[ "python", "unit-testing", "testing" ]
Is there a consensus about the best place to put Python unittests? Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (`if __name__ == '__main__'`, etc.)), or is it better to include the unittests within different modules? Perhaps a co...
1. Where you have to if using a library specifying where unittests should live, 2. in the modules themselves for small projects, or 3. in a `tests/` subdirectory in your package for larger projects. It's a matter of what works best for the project you're creating. Sometimes the libraries you're using determine where ...
Should Python unittests be in a separate module?
1,340,892
14
2009-08-27T12:52:34Z
1,341,119
9
2009-08-27T13:31:11Z
[ "python", "unit-testing", "testing" ]
Is there a consensus about the best place to put Python unittests? Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (`if __name__ == '__main__'`, etc.)), or is it better to include the unittests within different modules? Perhaps a co...
# YES, do use a separate module. It does not really make sense to use the `__main__` trick. Just assume that you have **several files** in your module, and it does not work anymore, because **you don't want to run each source file** separately when testing your module. Also, when installing a module, most of the time...
How to make the python interpreter correctly handle non-ASCII characters in string operations?
1,342,000
74
2009-08-27T15:53:31Z
1,342,042
24
2009-08-27T15:59:53Z
[ "python", "unicode" ]
I have a string that looks like so: ``` 6 918 417 712 ``` The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called `s`, we get: ``` s.replace(' ', '') ``` That should do the trick. But of course it complains that the non-ASCII character `'\xc2'` i...
``` >>> unicode_string = u"hello aåbäcö" >>> unicode_string.encode("ascii", "ignore") 'hello abc' ```
How to make the python interpreter correctly handle non-ASCII characters in string operations?
1,342,000
74
2009-08-27T15:53:31Z
1,342,079
46
2009-08-27T16:04:51Z
[ "python", "unicode" ]
I have a string that looks like so: ``` 6 918 417 712 ``` The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called `s`, we get: ``` s.replace(' ', '') ``` That should do the trick. But of course it complains that the non-ASCII character `'\xc2'` i...
Python 2 uses `ascii` as the default encoding for source files, which means you must specify another encoding at the top of the file to use non-ascii unicode characters in literals. Python 3 uses `utf-8` as the default encoding for source files, so this is less of an issue. See: <http://docs.python.org/tutorial/interp...
How to make the python interpreter correctly handle non-ASCII characters in string operations?
1,342,000
74
2009-08-27T15:53:31Z
1,342,373
148
2009-08-27T16:57:23Z
[ "python", "unicode" ]
I have a string that looks like so: ``` 6 918 417 712 ``` The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called `s`, we get: ``` s.replace(' ', '') ``` That should do the trick. But of course it complains that the non-ASCII character `'\xc2'` i...
``` def removeNonAscii(s): return "".join(filter(lambda x: ord(x)<128, s)) ``` edit: my first impulse is always to use a filter, but the generator expression is more memory efficient (and shorter)... ``` def removeNonAscii(s): return "".join(i for i in s if ord(i)<128) ``` Keep in mind that this is guaranteed to wor...
How to make the python interpreter correctly handle non-ASCII characters in string operations?
1,342,000
74
2009-08-27T15:53:31Z
1,343,125
7
2009-08-27T18:54:33Z
[ "python", "unicode" ]
I have a string that looks like so: ``` 6 918 417 712 ``` The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called `s`, we get: ``` s.replace(' ', '') ``` That should do the trick. But of course it complains that the non-ASCII character `'\xc2'` i...
Using Regex: ``` import re strip_unicode = re.compile("([^-_a-zA-Z0-9!@#%&=,/'\";:~`\$\^\*\(\)\+\[\]\.\{\}\|\?\<\>\\]+|[^\s]+)") print strip_unicode.sub('', u'6Â 918Â 417Â 712') ```
How to make the python interpreter correctly handle non-ASCII characters in string operations?
1,342,000
74
2009-08-27T15:53:31Z
10,268,212
14
2012-04-22T13:12:10Z
[ "python", "unicode" ]
I have a string that looks like so: ``` 6 918 417 712 ``` The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called `s`, we get: ``` s.replace(' ', '') ``` That should do the trick. But of course it complains that the non-ASCII character `'\xc2'` i...
The following code will replace all non ASCII characters with question marks. ``` "".join([x if ord(x) < 128 else '?' for x in s]) ```
Can you really use the Visual Studio 2008 IDE to code in Python?
1,342,377
2
2009-08-27T16:57:39Z
1,342,421
8
2009-08-27T17:03:58Z
[ "python", "visual-studio", "ironpython" ]
I have a friend who I am trying to teach how to program. He comes from a very basic PHP background, and for some reason is ANTI C#, I guess because some of his PHP circles condemn anything that comes from Microsoft. Anyways - I've told him its possible to use either Ruby or Python with the VS2008 IDE, because I've rea...
If you want to use Python together with the .NET Common Language Runtime, then you want one of: * [Python.NET](http://pythonnet.sourceforge.net/) (extension to vanilla Python that adds .NET support) * [IronPython](http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython) (re-implementation of Python as a .NET lan...
Pythonic way of checking if a condition holds for any element of a list
1,342,601
29
2009-08-27T17:36:55Z
1,342,617
65
2009-08-27T17:38:53Z
[ "python", "list" ]
I have a list in Python, and I want to check if any elements are negative. Specman has the `has()` method for lists which does: ``` x: list of uint; if (x.has(it < 0)) { // do something }; ``` Where `it` is a Specman keyword mapped to each element of the list in turn. I find this rather elegant. I looked through...
[any()](http://docs.python.org/library/functions.html#any): ``` if any(t < 0 for t in x): # do something ``` Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory: ``` if True in (t < 0 for t in x): ```
Pythonic way of checking if a condition holds for any element of a list
1,342,601
29
2009-08-27T17:36:55Z
1,342,622
18
2009-08-27T17:39:10Z
[ "python", "list" ]
I have a list in Python, and I want to check if any elements are negative. Specman has the `has()` method for lists which does: ``` x: list of uint; if (x.has(it < 0)) { // do something }; ``` Where `it` is a Specman keyword mapped to each element of the list in turn. I find this rather elegant. I looked through...
Use `any()`. ``` if any(t < 0 for t in x): # do something ```
Pythonic way of checking if a condition holds for any element of a list
1,342,601
29
2009-08-27T17:36:55Z
1,342,629
8
2009-08-27T17:40:26Z
[ "python", "list" ]
I have a list in Python, and I want to check if any elements are negative. Specman has the `has()` method for lists which does: ``` x: list of uint; if (x.has(it < 0)) { // do something }; ``` Where `it` is a Specman keyword mapped to each element of the list in turn. I find this rather elegant. I looked through...
Python has a built in [any()](http://docs.python.org/library/functions.html#any) function for exactly this purpose.
How does python decide whether a parameter is a reference or a value?
1,342,953
4
2009-08-27T18:31:35Z
1,342,976
11
2009-08-27T18:33:36Z
[ "python", "pointers", "reference" ]
In C++, `void somefunction(int)` passes a value, while `void somefunction(int&)` passes a reference. In Java, primitives are passed by value, while objects are passed by reference. How does python make this decision? Edit: Since everything is passed by reference, why does this: ``` def foo(num): num *= 2 a = 4 f...
It passes everything by reference. Even when you specify a numeric value, it is a reference against a table containing that value. This is the difference between static and dynamic languages. The type stays with the value, not with the container, and variables are just references towards a "value space" where all value...
How does python decide whether a parameter is a reference or a value?
1,342,953
4
2009-08-27T18:31:35Z
1,343,188
9
2009-08-27T19:07:23Z
[ "python", "pointers", "reference" ]
In C++, `void somefunction(int)` passes a value, while `void somefunction(int&)` passes a reference. In Java, primitives are passed by value, while objects are passed by reference. How does python make this decision? Edit: Since everything is passed by reference, why does this: ``` def foo(num): num *= 2 a = 4 f...
There is disagreement on terminology here. In the Java community, they say that everything is passed by value: primitives are passed by value; references are passed by value. (Just search this site for Java and pass by reference if you don't believe this.) Note that "objects" are not values in the language; only refere...
Python Packages?
1,342,975
9
2009-08-27T18:33:28Z
1,343,149
8
2009-08-27T18:58:48Z
[ "python", "unit-testing", "packages" ]
Ok, I think whatever I'm doing wrong, it's probably blindingly obvious, but I can't figure it out. I've read and re-read the tutorial section on packages and the only thing I can figure is that this won't work because I'm executing it directly. Here's the directory setup: ``` eulerproject/ __init__.py euler1.py ...
I had the same problem. I now use [nose](http://nose.readthedocs.org/en/latest/) to run my tests, and relative imports are correctly handled. Yeah, this whole relative import thing is confusing.
Python Packages?
1,342,975
9
2009-08-27T18:33:28Z
1,343,173
8
2009-08-27T19:03:55Z
[ "python", "unit-testing", "packages" ]
Ok, I think whatever I'm doing wrong, it's probably blindingly obvious, but I can't figure it out. I've read and re-read the tutorial section on packages and the only thing I can figure is that this won't work because I'm executing it directly. Here's the directory setup: ``` eulerproject/ __init__.py euler1.py ...
Generally you would have a directory, the name of which is your package name, somewhere on your PYTHONPATH. For example: ``` eulerproject/ euler/ __init__.py euler1.py ... tests/ ... setup.py ``` Then, you can either install this systemwide, or make sure to set `PYT...
Can Python's logging format be modified depending on the message log level?
1,343,227
38
2009-08-27T19:13:52Z
1,343,273
25
2009-08-27T19:20:42Z
[ "python", "logging" ]
I'm using Python's `logging` mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info." For exampl...
Yes, you can do this by having a custom `Formatter` class: ``` class MyFormatter(logging.Formatter): def format(self, record): #compute s according to record.levelno #for example, by setting self._fmt #according to the levelno, then calling #the superclass to do the actual formattin...
Can Python's logging format be modified depending on the message log level?
1,343,227
38
2009-08-27T19:13:52Z
8,349,076
30
2011-12-01T22:15:30Z
[ "python", "logging" ]
I'm using Python's `logging` mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info." For exampl...
I just ran into this issue and had trouble filling in the "holes" left in the above example. Here's a more complete, working version that I used. Hopefully this helps someone: ``` # Custom formatter class MyFormatter(logging.Formatter): err_fmt = "ERROR: %(msg)s" dbg_fmt = "DBG: %(module)s: %(lineno)d: %(ms...
Can Python's logging format be modified depending on the message log level?
1,343,227
38
2009-08-27T19:13:52Z
14,520,171
9
2013-01-25T10:44:12Z
[ "python", "logging" ]
I'm using Python's `logging` mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info." For exampl...
And again like JS answer but more compact. ``` class SpecialFormatter(logging.Formatter): FORMATS = {logging.DEBUG :"DBG: %(module)s: %(lineno)d: %(message)s", logging.ERROR : "ERROR: %(message)s", logging.INFO : "%(message)s", 'DEFAULT' : "%(levelname)s: %(message)s"} ...
How to explicitly specify a path to Firefox for Selenium?
1,344,026
8
2009-08-27T22:12:11Z
1,345,097
14
2009-08-28T05:00:00Z
[ "python", "windows", "firefox", "testing", "selenium" ]
I got Selenium IDE, followed [this post](http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html), got to ``` python test_default_server.py ``` and it complains Firefox is not in my path: ``` Please add the directory containing ''firefox.exe'' to your PATH environment variable, or explicitly specif...
You have to use the following string when you instantiate selenium instead of just "\*firefox": ``` "*firefox C:\\Program Files\\Mozilla Firefox\\firefox.exe" ``` Notice: I'm not sure that path is correct, but it should be a similar one. Update: Where do you instantiate your browser? By the tags in the question I su...
Django vs. Pylons
1,344,824
16
2009-08-28T03:03:37Z
1,344,842
19
2009-08-28T03:11:29Z
[ "python", "django", "grails", "pylons" ]
I've recently become a little frustrated with Django as a whole. It seems like I can't get full control over anything. I love Python to death, but I want to be able (and free) to do something as simple as adding a css class to an auto-generated form. One MVC framework that I have really been enjoying working with is G...
I'm using Pylons right now. The flexibility is great. It's all about best-of-breed rather than The Django Way. It's more oriented toward custom application development, as opposed to content-based web sites. You can certainly do content sites in it; it's just not specifically designed for them. On the other hand, you ...