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 Django - Model Inheritance - Does it allow you to override a parent model's attribute?
2,344,751
45
2010-02-26T20:50:54Z
2,345,037
9
2010-02-26T21:43:43Z
[ "python", "django", "django-inheritance" ]
I'm looking to do this: ``` class Place(models.Model): name = models.CharField(max_length=20) rating = models.DecimalField() class LongNamedRestaurant(Place): # Subclassing `Place`. name = models.CharField(max_length=255) # Notice, I'm overriding `Place.name` to give it a longer length. food_type = models.CharF...
Pasted your code into a fresh app, added app to INSTALLED\_APPS and ran syncdb: ``` django.core.exceptions.FieldError: Local field 'name' in class 'LongNamedRestaurant' clashes with field of similar name from base class 'Place' ``` Looks like Django does not support that.
In Django - Model Inheritance - Does it allow you to override a parent model's attribute?
2,344,751
45
2010-02-26T20:50:54Z
2,357,942
39
2010-03-01T18:08:20Z
[ "python", "django", "django-inheritance" ]
I'm looking to do this: ``` class Place(models.Model): name = models.CharField(max_length=20) rating = models.DecimalField() class LongNamedRestaurant(Place): # Subclassing `Place`. name = models.CharField(max_length=255) # Notice, I'm overriding `Place.name` to give it a longer length. food_type = models.CharF...
No, [it is not](https://docs.djangoproject.com/en/dev/topics/db/models/#field-name-hiding-is-not-permitted): > ### Field name “hiding” is not permitted > > In normal Python class inheritance, it is permissible for a child > class to override any attribute from the parent class. In Django, this > is not permitted f...
In Django - Model Inheritance - Does it allow you to override a parent model's attribute?
2,344,751
45
2010-02-26T20:50:54Z
18,159,571
12
2013-08-10T07:13:11Z
[ "python", "django", "django-inheritance" ]
I'm looking to do this: ``` class Place(models.Model): name = models.CharField(max_length=20) rating = models.DecimalField() class LongNamedRestaurant(Place): # Subclassing `Place`. name = models.CharField(max_length=255) # Notice, I'm overriding `Place.name` to give it a longer length. food_type = models.CharF...
That is not possible, and here is why: `LongNamedRestaurant` is also a `Place`, not only as a class but also in the database. The place-table contains an entry for every pure `Place` and for every `LongNamedRestaurant`. `LongNamedRestaurant` just creates an extra table with the `food_type` and a reference to the place ...
In Django - Model Inheritance - Does it allow you to override a parent model's attribute?
2,344,751
45
2010-02-26T20:50:54Z
24,581,514
13
2014-07-04T23:04:06Z
[ "python", "django", "django-inheritance" ]
I'm looking to do this: ``` class Place(models.Model): name = models.CharField(max_length=20) rating = models.DecimalField() class LongNamedRestaurant(Place): # Subclassing `Place`. name = models.CharField(max_length=255) # Notice, I'm overriding `Place.name` to give it a longer length. food_type = models.CharF...
See <http://stackoverflow.com/a/6379556/15690>: ``` class BaseMessage(models.Model): is_public = models.BooleanField(default=False) # some more fields... class Meta: abstract = True class Message(BaseMessage): # some fields... Message._meta.get_field('is_public').default = True ```
PyUnit tearDown and setUp vs __init__ and __del__
2,344,772
8
2010-02-26T20:53:52Z
2,344,828
13
2010-02-26T21:03:43Z
[ "python", "unit-testing" ]
Is there a difference between using tearDown and setUp versus `__init__` and `__del__` when using the pyUnit testing framework? If so, what is it exactly and what is the preferred method of use?
`setUp` is called before every test, and `tearDown` is called after every test. `__init__` is called only once when the class is instantiated. You generally do not need to define `__init__` or `__del__` when writing unit tests, though you could use `__init__` to define a constant used by many tests.
Python: Why is comparison between lists and tuples not supported?
2,345,092
12
2010-02-26T21:53:52Z
2,345,112
16
2010-02-26T21:56:49Z
[ "python", "list", "comparison", "tuples" ]
When comparing a tuple with a list like ... ``` >>> [1,2,3] == (1,2,3) False >>> [1,2,3].__eq__((1,2,3)) NotImplemented >>> (1,2,3).__eq__([1,2,3]) NotImplemented ``` ... Python does not deep-compare them as done with `(1,2,3) == (1,2,3)`. So what is the reason for this? Is it because the mutable list can be changed...
You can always "cast" it ``` >>> tuple([1, 2]) == (1, 2) True ``` Keep in mind that Python, unlike for example Javascript, [is strongly](http://en.wikipedia.org/wiki/Strongly_typed_programming_language) [typed](http://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic%20language%20and%20also%20a%20strongly%20typed%...
Why is post_save being raised twice during the save of a Django model?
2,345,400
15
2010-02-26T22:55:25Z
2,345,948
7
2010-02-27T01:57:51Z
[ "python", "django", "django-models", "signals" ]
I am attaching a method to the post\_save signal of my Django model. This way I can clear some cached items whenever the model is modified. The problem I am having is that the signal is being triggered twice when the model is saved. It doesn't necessarily hurt anything (the code will just gracefully error out) but it ...
While looking for the root of this problem, you can use quick workaround to prevent registering signal twice: ``` signals.post_save.connect(my_handler, MyModel, dispatch_uid="path.to.this.module") ``` [Source](http://code.djangoproject.com/wiki/Signals#Helppost_saveseemstobeemittedtwiceforeachsave).
Why is post_save being raised twice during the save of a Django model?
2,345,400
15
2010-02-26T22:55:25Z
2,345,967
12
2010-02-27T02:06:07Z
[ "python", "django", "django-models", "signals" ]
I am attaching a method to the post\_save signal of my Django model. This way I can clear some cached items whenever the model is modified. The problem I am having is that the signal is being triggered twice when the model is saved. It doesn't necessarily hurt anything (the code will just gracefully error out) but it ...
Apparently, [Python is sensitive to the way you import modules](http://stackoverflow.com/questions/1801249/import-twice-when-run-test). In my case, it wasn't an issue with any of import code inside my blog application but an issue with the INSTALLED\_APPS configuration, which I assume is used by Django to do an initial...
Exclude object's field from pickling in python
2,345,944
5
2010-02-27T01:56:55Z
2,345,985
14
2010-02-27T02:14:46Z
[ "python", "pickle" ]
I would like to avoid pickling of certain fields in an instance of a class. Currently, before pickling I just set those fields to None, but I wonder whether there's more elegant solution?
One way to handle instance attributes that are not picklable objects is to use the special methods available for modifying a class instance's state: *getstate*() and *setstate*(). Here is an example ``` class Foo(object): def __init__(self, value, filename): self.value = value self.logfile = file(...
Execute sqlite3 "dot" commands from Python or register collation in command line utility
2,346,074
14
2010-02-27T03:05:15Z
2,346,075
7
2010-02-27T03:07:53Z
[ "python", "sqlite", "collation", "dot-command" ]
My sqlite3 database contains a "collate" column-constraint. I've placed it in the schema for the table, to prevent accidentally neglecting to use the necessary collation. However this means when running `sqlite3` from the command line, and not from my Python code, the collation referenced in the schema is not present, ...
The dot commands are only available to the `sqlite3` executable. You will have to replace them with the equivalent combination of Python code and DB-API calls in order to mimic their behavior.
PyGame Set Mouse Cursor from Bitmap
2,346,205
8
2010-02-27T04:11:53Z
2,354,944
11
2010-03-01T09:53:29Z
[ "python", "pygame", "mouse-cursor" ]
I'm making an image editor using pyGame and I was wondering if it was possible to change the mouse cursor to something more suitable (for instance a circle or rectangle) for brushes. PyGame has a really weird way of doing it that I'm not sure would work very well. Is there a way I can write to a bitmap and then use tha...
Another option is to simply [hide](http://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_visible) the cursor, [load](http://www.pygame.org/docs/ref/image.html#pygame.image.load) any arbitrary bitmap that you like and [draw](http://www.pygame.org/docs/ref/surface.html#Surface.blit) it every frame [where the cursor ...
Why does += behave unexpectedly on lists?
2,347,265
61
2010-02-27T12:15:59Z
2,347,272
75
2010-02-27T12:19:23Z
[ "python", "augmented-assignment" ]
The `+=` operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here? ``` class foo: bar = [] def __init__(self,x): self.bar += [x] class foo2: bar = [] def __init__(self,x): self.bar = self.bar + [x] f = foo(1) g = foo(2) print f...
For the general case, see [Scott Griffith's answer](http://stackoverflow.com/a/2347423/1709587). When dealing with lists like you are, though, the `+=` operator is a shorthand for `someListObject.extend(iterableObject)`. See the [documentation of extend()](http://docs.python.org/tutorial/datastructures.html). The `ext...
Why does += behave unexpectedly on lists?
2,347,265
61
2010-02-27T12:15:59Z
2,347,278
17
2010-02-27T12:23:17Z
[ "python", "augmented-assignment" ]
The `+=` operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here? ``` class foo: bar = [] def __init__(self,x): self.bar += [x] class foo2: bar = [] def __init__(self,x): self.bar = self.bar + [x] f = foo(1) g = foo(2) print f...
The problem here is, `bar` is defined as a class attribute, not an instance variable. In `foo`, the class attribute is modified in the `init` method, that's why all instances are affected. In `foo2`, an instance variable is defined using the (empty) class attribute, and every instance gets its own `bar`. The "correc...
Why does += behave unexpectedly on lists?
2,347,265
61
2010-02-27T12:15:59Z
2,347,423
65
2010-02-27T13:14:11Z
[ "python", "augmented-assignment" ]
The `+=` operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here? ``` class foo: bar = [] def __init__(self,x): self.bar += [x] class foo2: bar = [] def __init__(self,x): self.bar = self.bar + [x] f = foo(1) g = foo(2) print f...
The general answer is that `+=` tries to call the `__iadd__` special method, and if that isn't available it tries to use `__add__` instead. So the issue is with the difference between these special methods. The `__iadd__` special method is for an in-place addition, that is it mutates the object that it acts on. The `_...
Python: passing a function with parameters as parameter
2,347,388
11
2010-02-27T13:04:31Z
2,347,401
20
2010-02-27T13:08:17Z
[ "python", "function" ]
``` def lite(a,b,c): #... def big(func): # func = callable() #... #main big(lite(1,2,3)) ``` how to do this? in what way to pass function with parameters to another function?
Why not do: ``` big(lite, (1, 2, 3)) ``` ? Then you can do: ``` def big(func, args): func(*args) ```
Coping dictionary within a dictionary(Nested dictionary)
2,347,854
3
2010-02-27T15:31:58Z
2,347,871
11
2010-02-27T15:35:05Z
[ "python", "dictionary" ]
I am having a dictionary like as `dict1 = { 0 : 0, 1 : 1, 2 : { 0: 0, 1 : 1}}` (which is also having a dictionary as value). I want to keep store these value same for some modification checking purpose. So now I am copy this dictionary content into another dictionary as `dict2 = dict1.copy()`. Now I am changing the val...
Use [`copy.deepcopy`](http://docs.python.org/library/copy.html) to perform a deep copy.
python single configuration file
2,348,927
20
2010-02-27T20:53:15Z
2,349,182
9
2010-02-27T22:30:47Z
[ "python", "configuration-files" ]
I am developing a project that requires a single configuration file whose data is used by multiple modules. My question is: what is the common approach to that? should i read the configuration file from each of my modules (files) or is there any other way to do it? I was thinking to have a module named config.py tha...
I like the approach of a single `config.py` module whose body (when first imported) parses one or more configuration-data files and sets its own "global variables" appropriately -- though I'd favor `config.teamdata` over the round-about `config.data['teamdata']` approach. This assumes configuration settings are read-o...
Accessing Lower Triangle of a Numpy Matrix?
2,349,260
4
2010-02-27T22:51:55Z
2,349,327
11
2010-02-27T23:09:08Z
[ "python", "numpy" ]
Okay, so basically lets say i have a matrix: ``` matrix([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]) ``` Is it possible to get the area below the diagonal easily when working with numpy matrixs? I looked around and could not find anything. I ca...
You could use `tril` and `triu`. See them here: <http://docs.scipy.org/doc/numpy/reference/routines.array-creation.html>
Python: How to import other Python files
2,349,991
218
2010-02-28T03:40:11Z
2,349,998
153
2010-02-28T03:42:33Z
[ "python", "python-import" ]
How do I import other files in Python? 1. How exactly can I import a specific python file like `import file.py`? 2. How to import a folder instead of a specific file? 3. I want to load a Python file dynamically in runtime, based on user input. 4. I want to know how to take from the file just one specific part. For...
1. Just `import file` without the '.py' extension 2. You can mark a folder as a package, by adding an empty file named `__init__.py`. 3. You can use `__import__` function, it takes the name as the module name as string. (again: module name without .py extension) ``` pmName = input('Enter module name:') pm = _...
Python: How to import other Python files
2,349,991
218
2010-02-28T03:40:11Z
14,503,276
14
2013-01-24T14:08:54Z
[ "python", "python-import" ]
How do I import other files in Python? 1. How exactly can I import a specific python file like `import file.py`? 2. How to import a folder instead of a specific file? 3. I want to load a Python file dynamically in runtime, based on user input. 4. I want to know how to take from the file just one specific part. For...
You do not have many complex methods to import a python file from one folder to another. Just create a **\_\_init\_\_.py** file to declare this folder is a python package and then go to your host file where you want to import just type `from root.parent.folder.file import variable, class, whatever`
Python: How to import other Python files
2,349,991
218
2010-02-28T03:40:11Z
16,299,963
18
2013-04-30T12:30:38Z
[ "python", "python-import" ]
How do I import other files in Python? 1. How exactly can I import a specific python file like `import file.py`? 2. How to import a folder instead of a specific file? 3. I want to load a Python file dynamically in runtime, based on user input. 4. I want to know how to take from the file just one specific part. For...
To import a specific Python file at 'runtime' with a known name: ``` import os import sys ``` ... ``` scriptpath = "../Test/MyModule.py" # Add the directory containing your module to the Python path (wants absolute paths) sys.path.append(os.path.abspath(scriptpath)) # Do the import import MyModule ```
Python: How to import other Python files
2,349,991
218
2010-02-28T03:40:11Z
20,749,411
353
2013-12-23T18:46:10Z
[ "python", "python-import" ]
How do I import other files in Python? 1. How exactly can I import a specific python file like `import file.py`? 2. How to import a folder instead of a specific file? 3. I want to load a Python file dynamically in runtime, based on user input. 4. I want to know how to take from the file just one specific part. For...
## There are many ways to import a python file, all with their pros and cons. Don't just hastily pick the first import strategy that works for you or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs. I'll start out explaining the easiest example #1, then I'll move toward the ...
How to build a web crawler based on Scrapy to run forever?
2,350,049
11
2010-02-28T04:07:13Z
2,350,109
12
2010-02-28T04:47:32Z
[ "python", "web-crawler", "scrapy" ]
I want to build a web crawler based on Scrapy to grab news pictures from several news portal website. I want to this crawler to be: 1. Run forever Means it will periodical re-visit some portal pages to get updates. 2. Schedule priorities. Give different priorities to different type of URLs. 3. Multi thread fet...
Scrapy is a framework for the spidering of websites, as such, it is intended to support your criteria but it isn't going to dance for you out of the box; you will probably have to get relatively familiar with the module for some tasks. 1. Running forever is up to your application that calls Scrapy. You tell [the spide...
Python: does the set class "leak" when items are removed, like a dict?
2,350,050
4
2010-02-28T04:08:43Z
2,350,061
7
2010-02-28T04:14:41Z
[ "python", "set", "dictionary" ]
I know that Python `dict`s will "leak" when items are removed (because the item's slot will be overwritten with the magic "removed" value)… But will the `set` class behave the same way? Is it safe to keep a `set` around, adding and removing stuff from it over time? **Edit**: Alright, I've tried it out, and here's wh...
Yes, `set` is basically a hash table just like `dict` -- the differences at the interface don't imply many differences "below" it. Once in a while, you should copy the set -- `myset = set(myset)` -- just like you should for a dict on which many additions and removals are regularly made over time.
Custom data types in numpy arrays
2,350,072
17
2010-02-28T04:21:15Z
2,352,846
15
2010-02-28T21:57:18Z
[ "python", "numpy" ]
I'm creating a numpy array which is to be filled with objects of a particular class I've made. I'd like to initialize the array such that it will only ever contain objects of that class. For example, here's what I'd like to do, and what happens if I do it. ``` class Kernel: pass >>> L = np.empty(4,dtype=Kernel) ...
If your Kernel class has a predictable amount of member data, then you could define a dtype for it instead of a class. e.g. if it's parameterized by 9 floats and an int, you could do ``` kerneldt = np.dtype([('myintname', np.int32), ('myfloats', np.float64, 9)]) arr = np.empty(dims, dtype=kerneldt) ``` You'll have to...
Django LowerCaseCharField
2,350,681
11
2010-02-28T09:52:35Z
2,350,728
16
2010-02-28T10:17:00Z
[ "python", "django", "lowercase" ]
We implemented a LowerCaseCharField. We would be happy to hear better implementation suggestions. ``` from django.db.models.fields import CharField class LowerCaseCharField(CharField): """ Defines a charfield which automatically converts all inputs to lowercase and saves. """ def pre_save(self, m...
You may wish to override `to_python`, which will allow you to compare non-lowercase strings when doing database lookups. The actual method is `get_prep_value`, but as that calls `to_python` for `CharField`, it's more convenient to override that: ``` def to_python(self, value): value = super(LowerCaseCharField, sel...
Dictionary-like object in Python that allows setting arbitrary attributes
2,350,817
3
2010-02-28T10:52:51Z
2,350,827
7
2010-02-28T10:58:31Z
[ "python", "dictionary", "attributes" ]
What I want to do in my code: ``` myobj = <SomeBuiltinClass>() myobj.randomattr = 1 print myobj.randomattr ... ``` I can implement a custom SomeClass that implements `__setattr__` `__getattr__`. But I wonder if there is already a built-in Python class or simple way to do this?
You can just use an empty class: ``` class A(object): pass a = A() a.randomattr = 1 ```
When will Jython support Python 3?
2,351,008
38
2010-02-28T12:21:52Z
2,351,358
25
2010-02-28T14:40:08Z
[ "python", "python-3.x", "jython" ]
According to [Jython's documentation](http://wiki.python.org/jython/JythonFaq/GeneralInfo#IsJythonthesamelanguageasPython.3F): > Jython is an implementation of the > Python language for the Java platform. > Jython 2.5 implements the same > language as CPython 2.5, and nearly > all of the Core Python standard > library...
Jython roadmap is definitely outdated. However, on Frank Wierzbicki's Weblog (one of Jython's main developers) you can get [an update](http://fwierzbicki.blogspot.com/2008/10/updated-jython-roadmap.html), telling that Python 3 is definitely on the radar. Unfortunately, it is not yet clear when, as it is stated in a ...
When will Jython support Python 3?
2,351,008
38
2010-02-28T12:21:52Z
33,433,803
14
2015-10-30T10:28:12Z
[ "python", "python-3.x", "jython" ]
According to [Jython's documentation](http://wiki.python.org/jython/JythonFaq/GeneralInfo#IsJythonthesamelanguageasPython.3F): > Jython is an implementation of the > Python language for the Java platform. > Jython 2.5 implements the same > language as CPython 2.5, and nearly > all of the Core Python standard > library...
5 years after the question has been asked, the answer is still "it will come, but the time frame for an initial release is not clear yet". What we can say is that now there is a [jython3 repository](https://github.com/jython/jython3) targetting Python 3.5. `README.md`, dated 28 May 2015, says: > This repo is in the v...
What are the Difference between cElementtree and ElementTree?
2,351,694
8
2010-02-28T16:32:11Z
2,351,707
16
2010-02-28T16:36:10Z
[ "python", "xml" ]
I know a little of dom, and would like to learn about ElementTree. Python 2.6 has a somewhat older implementation of ElementTree, but still usable. However, it looks like it comes with two different classes: xml.etree.ElementTree and xml.etree.cElementTree. Would someone please be so kind to enlighten me with their dif...
It is the same library (same API, same features) but ElementTree is implemented in Python and cElementTree is implemented in C. If you can, use the C implementation because it is optimized for fast parsing and low memory use, and is 15-20 times faster than the Python implementation. Use the Python version if you are ...
Python error: ImportError: cannot import name Akismet
2,351,919
11
2010-02-28T17:46:20Z
7,460,739
15
2011-09-18T09:56:30Z
[ "python", "environment-variables", "python-import" ]
I've seen many similar errors, but I can't see a solution that applies to my particular problem. I'm trying to use the [Akismet module](http://www.voidspace.org.uk/python/akismet_python.html#downloading) which is on my PYTHONPATH, then if I start up the interactive interpreter, when I run `from akismet import Akismet`...
I just want to draw more attention to Doppelganger's own answer to his question. I had this error, and the situation is this: You're trying to import function/class X from a module called say 'strategy.py'. Unfortunately you've also created a python package directory called strategy, in other words you've got a direc...
Can't use unichr in Python 3.1
2,352,018
11
2010-02-28T18:11:55Z
2,352,047
22
2010-02-28T18:19:08Z
[ "python", "unicode", "string" ]
new here! I'm a beginner in Python, and I've been looking through the **Python Cookbook (2nd Edition)** to learn how to process strings and characters. I wanted to try converting a number into its Unicode equivalent. So I tried using the [built-in function called '**unichr**'](http://docs.python.org/library/functions....
In Python 3, you just use chr: ``` >>> chr(10000) '✐' ```
Can't use unichr in Python 3.1
2,352,018
11
2010-02-28T18:11:55Z
2,352,059
7
2010-02-28T18:21:23Z
[ "python", "unicode", "string" ]
new here! I'm a beginner in Python, and I've been looking through the **Python Cookbook (2nd Edition)** to learn how to process strings and characters. I wanted to try converting a number into its Unicode equivalent. So I tried using the [built-in function called '**unichr**'](http://docs.python.org/library/functions....
In Python 3, there's no difference between unicode and normal strings anymore. Only between unicode strings and binary data. So the developers finally removed the `unichr` function in favor of a common `chr` which now does what the old `unichr` did. See the documentation [here](http://docs.python.org/3.1/library/functi...
How to use a dot "." to access members of dictionary?
2,352,181
82
2010-02-28T18:51:42Z
2,352,195
47
2010-02-28T18:55:03Z
[ "python", "dictionary" ]
How do I make Python dictionary members accessible via a dot "."? For example, instead of writing `mydict['val']`, I'd like to write `mydict.val`. Also I'd like to access nested dicts this way. For example, `mydict.mydict2.val` would refer to `mydict = { 'mydict2': { 'val': ... } }`. Thanks, Boda Cydo.
Derive from dict and and implement `__getattr__` and `__setattr__`. Or you can use [Bunch](http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/) which is very similar. I don't think it's possible to monkeypatch built-in dict class.
How to use a dot "." to access members of dictionary?
2,352,181
82
2010-02-28T18:51:42Z
9,205,155
7
2012-02-09T03:50:46Z
[ "python", "dictionary" ]
How do I make Python dictionary members accessible via a dot "."? For example, instead of writing `mydict['val']`, I'd like to write `mydict.val`. Also I'd like to access nested dicts this way. For example, `mydict.mydict2.val` would refer to `mydict = { 'mydict2': { 'val': ... } }`. Thanks, Boda Cydo.
I tried this: ``` class dotdict(dict): def __getattr__(self, name): return self[name] ``` you can try \_\_getattribute\_\_ too. make every dict a type of dotdict would be good enough, if you want to init this from a multi-layer dict, try implement **init** too.
How to use a dot "." to access members of dictionary?
2,352,181
82
2010-02-28T18:51:42Z
23,689,767
36
2014-05-15T22:29:39Z
[ "python", "dictionary" ]
How do I make Python dictionary members accessible via a dot "."? For example, instead of writing `mydict['val']`, I'd like to write `mydict.val`. Also I'd like to access nested dicts this way. For example, `mydict.mydict2.val` would refer to `mydict = { 'mydict2': { 'val': ... } }`. Thanks, Boda Cydo.
I've always kept this around in a util file. You can use it as a mixin on your own classes too. ``` >>> class dotdict(dict): ... """dot.notation access to dictionary attributes""" ... __getattr__ = dict.get ... __setattr__ = dict.__setitem__ ... __delattr__ = dict.__delitem__ ... >>> mydict = {'val':'...
How to use a dot "." to access members of dictionary?
2,352,181
82
2010-02-28T18:51:42Z
28,463,329
24
2015-02-11T19:57:52Z
[ "python", "dictionary" ]
How do I make Python dictionary members accessible via a dot "."? For example, instead of writing `mydict['val']`, I'd like to write `mydict.val`. Also I'd like to access nested dicts this way. For example, `mydict.mydict2.val` would refer to `mydict = { 'mydict2': { 'val': ... } }`. Thanks, Boda Cydo.
Install `dotmap` via `pip` ``` pip install dotmap ``` It does everything you want it to do and subclasses `dict`, so it operates like a normal dictionary: ``` from dotmap import DotMap m = DotMap() m.hello = 'world' m.hello m.hello += '!' # m.hello and m['hello'] now both return 'world!' m.val = 5 m.val2 = 'Sam' ``...
How to use a dot "." to access members of dictionary?
2,352,181
82
2010-02-28T18:51:42Z
32,107,024
44
2015-08-19T23:03:39Z
[ "python", "dictionary" ]
How do I make Python dictionary members accessible via a dot "."? For example, instead of writing `mydict['val']`, I'd like to write `mydict.val`. Also I'd like to access nested dicts this way. For example, `mydict.mydict2.val` would refer to `mydict = { 'mydict2': { 'val': ... } }`. Thanks, Boda Cydo.
You can do it using this class I just made. With this class you can use the `Map` object like another dictionary(including json serialization) or with the dot notation. I hope to help you: ``` class Map(dict): """ Example: m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer']) ...
How to use dicts in Mako templates?
2,352,252
2
2010-02-28T19:09:23Z
2,352,421
7
2010-02-28T19:56:20Z
[ "python", "templates", "mako" ]
Whenever I pass a complicated data structure to Mako, it's hard to iterate it. For example, I pass a dict of dict of list, and to access it in Mako, I have to do something like: `% for item in dict1['dict2']['list']: ... %endfor` I am wondering if Mako has some mechanism that could replace `[]` usage to access dictio...
Simplification of Łukasz' example: ``` class Bunch: def __init__(self, d): for k, v in d.items(): if isinstance(v, dict): v = Bunch(v) self.__dict__[k] = v print Bunch({'a':1, 'b':{'foo':2}}).b.foo ``` See also: <http://code.activestate.com/recipes/52308-the-simpl...
The difference between python dict and tr1::unordered_map in C++
2,352,342
9
2010-02-28T19:35:36Z
2,352,356
7
2010-02-28T19:38:57Z
[ "c++", "python", "dictionary", "hashmap", "tr1" ]
I have a question related to understanding of how python dictionaries work. I remember reading somewhere strings in python are immutable to allow hashing, and it is the same reason why one cannot directly use lists as keys, i.e. the lists are mutable (by supporting .append) and hence they cannot be used as dictionary ...
Keys in all C++ map/set containers are const and thus immutable (after added to the container). Notice that C++ containers are not specific to string keys, you can use any objects, but the constness will prevent modifications after the key is copied to the container.
Calculating the area underneath a mathematical function
2,352,499
4
2010-02-28T20:18:09Z
2,352,526
8
2010-02-28T20:25:47Z
[ "python", "polynomial-math", "numerical-integration" ]
I have a range of data that I have approximated using a polynomial of degree 2 in Python. I want to calculate the area underneath this polynomial between 0 and 1. Is there a calculus, or similar package from numpy that I can use, or should I just make a simple function to integrate these functions? I'm a little uncle...
If you're integrating only polynomials, you don't need to represent a general mathematical function, use `numpy.poly1d`, which has an `integ` method for integration. ``` >>> import numpy >>> p = numpy.poly1d([2, 4, 6]) >>> print p 2 2 x + 4 x + 6 >>> i = p.integ() >>> i poly1d([ 0.66666667, 2. , 6. ...
How to write modern Python tests?
2,352,516
11
2010-02-28T20:22:23Z
2,352,575
11
2010-02-28T20:37:38Z
[ "python", "testing" ]
What is the latest way to write Python tests? What modules/frameworks to use? And another question: are `doctest` tests still of any value? Or should all the tests be written in a more modern testing framework? Thanks, Boda Cydo.
The usual way is to use the builtin [unittest](http://docs.python.org/library/unittest.html) module for creating unit tests and bundling them together to test suites which can be run independently. `unittest` is very similar to (and inspired by) jUnit and thus very easy to use. If you're interested in the very latest ...
How to write modern Python tests?
2,352,516
11
2010-02-28T20:22:23Z
2,352,607
9
2010-02-28T20:48:03Z
[ "python", "testing" ]
What is the latest way to write Python tests? What modules/frameworks to use? And another question: are `doctest` tests still of any value? Or should all the tests be written in a more modern testing framework? Thanks, Boda Cydo.
Using the built-in `unittest` module is as relevant and easy as ever. The other unit testing options, `py.test`,`nose`, and `twisted.trial` are mostly compatible with `unittest`. Doctests are of the same value they always were—they are great for *testing your documentation*, not your code. If you are going to put co...
Parsing broken XML with lxml.etree.iterparse
2,352,840
10
2010-02-28T21:55:58Z
9,050,454
25
2012-01-29T02:36:19Z
[ "python", "xml", "sax", "lxml" ]
I'm trying to parse a huge xml file with lxml in a memory efficient manner (ie streaming lazily from disk instead of loading the whole file in memory). Unfortunately, the file contains some bad ascii characters that break the default parser. The parser works if I set recover=True, but the iterparse method doesn't take ...
The currently accepted answer is, well, not what one should do. The question itself also has a bad assumption: > parser = lxml.etree.XMLParser(recover=True) *#recovers from bad characters.* Actually `recover=True` is for recovering *from misformed XML*. There is however an ["encoding" option](http://lxml.de/parsing.h...
Are python functions threadsafe? (Particularly this one?)
2,352,934
2
2010-02-28T22:26:12Z
2,352,954
7
2010-02-28T22:31:17Z
[ "python", "multithreading", "scope" ]
Before answering, please understand I do NOT want you to do the work for me. I would rather appreciate a worded answer as to why my (possibly theoretical) problem exists, and an explanation of the process to go about fixing it. I find it harder to learn properly when someone just does the work for me. Thank you in adva...
> A more simple form of the question: If I call this function from a multi-threaded environment, will I have problems, Yes it is thread-safe from what I can tell > or do I need to move it into its own class? Thread safety has nothing to do with classes: it has to do with shared state. If threads share state, provisi...
Have to Restart Apache When Using Django On Apache with mod_wsgi
2,353,012
11
2010-02-28T22:48:18Z
2,353,038
15
2010-02-28T22:55:04Z
[ "python", "django", "apache", "mod-wsgi", "restart" ]
I'm creating a web app with Django. Since I'm very familiar with Apache I setup my development environment to have Django run through Apache using mod\_wsgi. The only annoyance I have with this is that I have to restart Apache everytime I change my code. Is there a way around this?
mod\_wsgi is great for production but I think the included server is better for development. Anyway you should read [this](http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode) about automatic reloading of source code.
Python 3 object construction: which is the most Pythonic / the accepted way?
2,353,140
8
2010-02-28T23:34:28Z
2,353,165
8
2010-02-28T23:43:18Z
[ "python-3.x", "python", "conventions" ]
Having a background in Java, which is very verbose and strict, I find the ability to mutate Python objects as to give them with fields other than those presented to the constructor really "ugly". Trying to accustom myself to a Pythonic way of thinking, **I'm wondering how I should allow my objects to be constructed**....
The first you describe is very common. Some use the shorter ``` class Foo: def __init__(self, foo, bar): self.foo, self.bar = foo, bar ``` Your second approach isn't common, but a similar version is this: ``` class Thing: def __init__(self, **kwargs): self.something = kwargs['something'] #...
No module named urls
2,353,416
16
2010-03-01T01:29:17Z
6,154,486
39
2011-05-27T15:32:00Z
[ "python", "django" ]
I'm following the Django Tutorials, I'm at the end of part 3, at Decoupling the URLconfs, at <http://docs.djangoproject.com/en/1.1/intro/tutorial03/#intro-tutorial03> and I'm getting a "No module named urls" error message. When I change: ``` from django.conf.urls.defaults import * from django.contrib import admin ad...
I had a similar problem in my project root ... django complained that it couldn't find the module mysite.urls. Turns out my ROOT\_URLCONF variable in settings.py, which was set up using the default values, was set incorrect. Instead of "mysite.urls", it should have been simply "urls" I changed it, and voila, it worke...
CPython - Internally, what is stored on the stack and heap?
2,353,552
14
2010-03-01T02:18:56Z
2,353,565
10
2010-03-01T02:22:37Z
[ "python", "memory-management" ]
In C#, Value Types (eg: int, float, etc) are stored on the stack. Method parameters may also be stored on the stack as well. Most everything else, however, is stored on the heap. This includes Lists, objects, etc. I was wondering, does CPython do the same thing internally? What does it store on the stack, and what doe...
Python's runtime only deals in references to objects (which all live in the heap): what goes on Python's stack (as operands and results of its bytecode operations) are always **references** (to values that live elsewhere).
CPython - Internally, what is stored on the stack and heap?
2,353,552
14
2010-03-01T02:18:56Z
2,353,568
19
2010-03-01T02:22:49Z
[ "python", "memory-management" ]
In C#, Value Types (eg: int, float, etc) are stored on the stack. Method parameters may also be stored on the stack as well. Most everything else, however, is stored on the heap. This includes Lists, objects, etc. I was wondering, does CPython do the same thing internally? What does it store on the stack, and what doe...
All Python objects in the CPython implementation go on the heap. You can read in detail how Python's memory management works **[here](http://docs.python.org/c-api/memory.html)** in the documentation: > Memory management in Python involves a private heap **containing all Python objects and data structures.** The manage...
Python: How to find if a path exists between 2 nodes in a graph?
2,353,768
13
2010-03-01T03:41:47Z
2,353,783
10
2010-03-01T03:51:53Z
[ "python", "networkx" ]
I am using networkx package of Python.
``` >>> import networkx as nx >>> G=nx.empty_graph() >>> G.add_edge(1,2) >>> G.add_edge(2,3) >>> G.add_edge(4,5) >>> nx.path.bidirectional_dijkstra(G,1,2) (1, [1, 2]) >>> nx.path.bidirectional_dijkstra(G,1,3) (2, [1, 2, 3]) >>> nx.path.bidirectional_dijkstra(G,1,4) False >>> nx.path.bidirectional_dijkstra(G,1,5) False ...
Python: How to find if a path exists between 2 nodes in a graph?
2,353,768
13
2010-03-01T03:41:47Z
5,665,794
8
2011-04-14T15:38:29Z
[ "python", "networkx" ]
I am using networkx package of Python.
Using a disjoint set data structure: Create a singleton set for every vertex in the graph, then union the sets containing each of the pair of vertices for every edge in the graph. Finally, you know a path exists between two vertices if they are in the same set. See the [wikipedia](http://en.wikipedia.org/wiki/Disjoi...
Python: How to find if a path exists between 2 nodes in a graph?
2,353,768
13
2010-03-01T03:41:47Z
19,620,496
12
2013-10-27T16:36:54Z
[ "python", "networkx" ]
I am using networkx package of Python.
To check whether there is a path between two nodes in a graph - ``` >>> import networkx as nx >>> G=nx.Graph() >>> G.add_edge(1,2) >>> G.add_edge(2,3) >>> nx.has_path(G,1,3) True >>> G.add_edge(4,5) >>> nx.has_path(G,1,5) False ``` For more information, please refer [has\_path — NetworkX 1.7 documentation](http://net...
Automate Windows GUI operations with Python
2,353,963
10
2010-03-01T05:02:35Z
8,731,567
13
2012-01-04T17:55:29Z
[ "python", "winapi" ]
I want to make a Python script that automates the process of setting up a VPN server in Windows XP, but the only way I know how to do it is using the Windows GUI dialogs. How would I go about figuring out what those dialogs are doing to the system and designing a Python script to automate it?
You can also use [pywinauto](http://pywinauto.github.io/) for GUI automation. **Edit:** There seems to be now GUI for creating the scripts, [swapy](http://code.google.com/p/swapy/).
How do you modify sys.path in Google App Engine (Python)?
2,354,166
8
2010-03-01T06:11:36Z
2,354,273
17
2010-03-01T06:48:29Z
[ "python", "google-app-engine", "sys.path" ]
I've tried adding the following line to my handler script (main.py), but it doesn't seem to work: > sys.path.append('subdir') `subdir` lives in the my root directory (i.e. the one containing `app.yaml`). This doesn't seem to work, because when I try to import modules that live in `subdir`, my app explodes.
1) Ensure you have a blank `__init__.py` file in `subdir`. 2) Use a full path; something like this: ``` import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), 'subdir')) ``` --- Edit: providing more info to answer questions asked in a comment. [As Nick Johnson demonstrates](http://code.googl...
what's the meaning of %r in python
2,354,329
34
2010-03-01T07:13:09Z
2,354,337
15
2010-03-01T07:15:08Z
[ "python", "sign" ]
what's the meaning of `%r` in the following statement? ``` print '%r' % (1) ``` I think I've heard of `%s`, `%d`, and `%f` but never heard of this.
It calls [`repr()`](http://docs.python.org/library/functions.html#repr) on the object and inserts the resulting string.
what's the meaning of %r in python
2,354,329
34
2010-03-01T07:13:09Z
2,354,652
48
2010-03-01T08:48:07Z
[ "python", "sign" ]
what's the meaning of `%r` in the following statement? ``` print '%r' % (1) ``` I think I've heard of `%s`, `%d`, and `%f` but never heard of this.
Background: In Python, there are two builtin functions for turning an object into a string: [`str`](https://docs.python.org/2/library/functions.html#str) vs. [`repr`](https://docs.python.org/2/library/functions.html#func-repr). `str` is supposed to be a friendly, human readable string. `repr` is supposed to include de...
ALTER TABLE Sqlite: how to check if a column exists before alter the table?
2,354,696
6
2010-03-01T08:59:29Z
2,354,763
11
2010-03-01T09:15:59Z
[ "python", "sqlite3", "exists", "alter" ]
I need to execute in python a SQL query that adds a new column, in sqlite3. The problem is that sometimes it already exists. So previous to executing the query I need to check if the column already exists. If it does, then I won't execute the query. **Is there a way in sqlite to do that? Or do I have to make it thro...
You can get a list of columns for a table via the following statement: ``` PRAGMA table_info('table_name'); ``` More details on the pragma commands are availabel at [the sqlite web site](http://www.sqlite.org/pragma.html)
ALTER TABLE Sqlite: how to check if a column exists before alter the table?
2,354,696
6
2010-03-01T08:59:29Z
2,354,829
10
2010-03-01T09:30:35Z
[ "python", "sqlite3", "exists", "alter" ]
I need to execute in python a SQL query that adds a new column, in sqlite3. The problem is that sometimes it already exists. So previous to executing the query I need to check if the column already exists. If it does, then I won't execute the query. **Is there a way in sqlite to do that? Or do I have to make it thro...
IMO this ``` conn = sqlite3.connect(':memory:') c = conn.cursor() try: c.execute('ALTER TABLE mytable ADD COLUMN newcolumn;') except: pass # handle the error c.close() ``` is a better choice than constructing *special case* queries. You can wrap the above code in a AddColumn(cursor, table, column) function s...
Problem running Virtualenv on Mac OS X
2,355,188
14
2010-03-01T10:42:56Z
4,239,066
12
2010-11-21T17:04:38Z
[ "python", "osx", "virtualenv" ]
I'm using virtualenv-1.4.5 on Mac OS X 10.6.2 (Xcode is installed) and Python 2.6. Here's what I get when I attempt to run a virtualenv... ``` Mac-Pro:pylonsdev paul$ virtualenv --no-site-packages -v trythis Creating trythis/lib/python2.6 Symlinking Python bootstrap modules Symlinking trythis/lib/python2.6/_abcoll....
Install XCode from the App Store to fix the problem. I had the same error, installed XCode, ran it after installing, and now virtualenv works.
Problem running Virtualenv on Mac OS X
2,355,188
14
2010-03-01T10:42:56Z
9,384,860
24
2012-02-21T20:44:01Z
[ "python", "osx", "virtualenv" ]
I'm using virtualenv-1.4.5 on Mac OS X 10.6.2 (Xcode is installed) and Python 2.6. Here's what I get when I attempt to run a virtualenv... ``` Mac-Pro:pylonsdev paul$ virtualenv --no-site-packages -v trythis Creating trythis/lib/python2.6 Symlinking Python bootstrap modules Symlinking trythis/lib/python2.6/_abcoll....
All you really need to do is install the Xcode "Command Line Tools", there is two ways to do it: 1.- If you already have Xcode installed, go to Preferences -> Downloads and select "Command Line Tools". 2.- Download the "Command Line Tools for Xcode" .dmg from: <https://developer.apple.com/downloads>. You can install...
Python: Control timeout length
2,355,743
4
2010-03-01T12:34:00Z
2,355,781
7
2010-03-01T12:39:27Z
[ "python" ]
I have code similar to the following running in a script: ``` try: s = ftplib.FTP('xxx.xxx.xxx.xxx','username','password') except: print ('Could not contact FTP serer') sys.exit() ``` IF the FTP site is inaccessible, the script almost seems to 'hang' ... It is taking about 75 seconds on average before s...
Starting with 2.6, the [`FTP constructor`](http://docs.python.org/library/ftplib.html#ftplib.FTP) has an optional `timeout` parameter: > `class ftplib.FTP([host[, user[, passwd[, acct[, timeout]]]]])` > > Return a new instance of the FTP class. When host is given, the method call connect(host) is made. When user is gi...
Tell if python is in interactive mode
2,356,399
28
2010-03-01T14:20:57Z
2,356,420
41
2010-03-01T14:25:26Z
[ "python", "interactive", "python-2.5", "python-2.x" ]
In a python script, is there any way to tell if the interpreter is in interactive mode? This would be useful, for instance, when you run an interactive python session and import a module, slightly different code is executed (for example, log file writing is turned off, or a figure won't be produced, so you can interact...
`__main__.__file__` doesn't exist in the interactive interpreter: ``` import __main__ as main print hasattr(main, '__file__') ``` This also goes for code run via `python -c`, but not `python -m`.
Tell if python is in interactive mode
2,356,399
28
2010-03-01T14:20:57Z
2,356,427
15
2010-03-01T14:27:50Z
[ "python", "interactive", "python-2.5", "python-2.x" ]
In a python script, is there any way to tell if the interpreter is in interactive mode? This would be useful, for instance, when you run an interactive python session and import a module, slightly different code is executed (for example, log file writing is turned off, or a figure won't be produced, so you can interact...
[`sys.ps1`](http://docs.python.org/library/sys.html#sys.ps1) and [`sys.ps2`](http://docs.python.org/library/sys.html#sys.ps2) are only defined in interactive mode.
How do you round UP a number in Python?
2,356,501
165
2010-03-01T14:40:04Z
2,356,510
341
2010-03-01T14:40:58Z
[ "python", "floating-point", "integer", "rounding" ]
This problem is killing me. How does one roundup a number UP in Python? I tried round(number) but it round the number down. Example: ``` round(2.3) = 2.0 and not 3, what I would like ``` The I tried int(number + .5) but it round the number down again! Example: ``` int(2.3 + .5) = 2 ``` Then I tried round(number + ...
The [ceil](https://docs.python.org/2/library/math.html#math.ceil) (ceiling) function: ``` import math print math.ceil(4.2) ```
How do you round UP a number in Python?
2,356,501
165
2010-03-01T14:40:04Z
2,356,515
11
2010-03-01T14:41:23Z
[ "python", "floating-point", "integer", "rounding" ]
This problem is killing me. How does one roundup a number UP in Python? I tried round(number) but it round the number down. Example: ``` round(2.3) = 2.0 and not 3, what I would like ``` The I tried int(number + .5) but it round the number down again! Example: ``` int(2.3 + .5) = 2 ``` Then I tried round(number + ...
[Use `math.ceil`](https://docs.python.org/2/library/math.html#math.ceil) to round up: ``` >>> import math >>> math.ceil(5.4) 6.0 ``` **NOTE**: The input should be float. If you need an integer, call `int` to convert it: ``` >>> int(math.ceil(5.4)) 6 ``` BTW, use `math.floor` to round *down* and `round` to round to...
How do you round UP a number in Python?
2,356,501
165
2010-03-01T14:40:04Z
7,950,627
90
2011-10-31T06:39:44Z
[ "python", "floating-point", "integer", "rounding" ]
This problem is killing me. How does one roundup a number UP in Python? I tried round(number) but it round the number down. Example: ``` round(2.3) = 2.0 and not 3, what I would like ``` The I tried int(number + .5) but it round the number down again! Example: ``` int(2.3 + .5) = 2 ``` Then I tried round(number + ...
Interesting Python 2.x issue to keep in mind: ``` >>> import math >>> math.ceil(4500/1000) 4.0 >>> math.ceil(4500/1000.0) 5.0 ``` The problem is that dividing two ints in python produces another int and that's rounded before the ceiling call. You have to make one value a float (or cast) to get a correct result. In j...
How do you round UP a number in Python?
2,356,501
165
2010-03-01T14:40:04Z
16,241,082
20
2013-04-26T16:27:43Z
[ "python", "floating-point", "integer", "rounding" ]
This problem is killing me. How does one roundup a number UP in Python? I tried round(number) but it round the number down. Example: ``` round(2.3) = 2.0 and not 3, what I would like ``` The I tried int(number + .5) but it round the number down again! Example: ``` int(2.3 + .5) = 2 ``` Then I tried round(number + ...
You might also like numpy: ``` >>> import numpy as np >>> np.ceil(2.3) 3.0 ``` I'm not saying it's better than math, but if you were already using numpy for other purposes, you can keep your code consistent. Anyway, just a detail I came across. I use numpy a lot and was surprised it didn't get mentioned, but of cour...
How do you round UP a number in Python?
2,356,501
165
2010-03-01T14:40:04Z
23,590,097
36
2014-05-11T07:28:39Z
[ "python", "floating-point", "integer", "rounding" ]
This problem is killing me. How does one roundup a number UP in Python? I tried round(number) but it round the number down. Example: ``` round(2.3) = 2.0 and not 3, what I would like ``` The I tried int(number + .5) but it round the number down again! Example: ``` int(2.3 + .5) = 2 ``` Then I tried round(number + ...
I know this answer is for a question from a while back, but if you don't want to import math and you just want to round up, this works for me. ``` >>> int(21 / 5) 4 >>> int(21 / 5) + (21 % 5 > 0) 5 ``` The first part becomes 4 and the second part evaluates to "True" if there is a remainder, which in addition True = 1...
How do you round UP a number in Python?
2,356,501
165
2010-03-01T14:40:04Z
35,125,872
10
2016-02-01T08:23:29Z
[ "python", "floating-point", "integer", "rounding" ]
This problem is killing me. How does one roundup a number UP in Python? I tried round(number) but it round the number down. Example: ``` round(2.3) = 2.0 and not 3, what I would like ``` The I tried int(number + .5) but it round the number down again! Example: ``` int(2.3 + .5) = 2 ``` Then I tried round(number + ...
If working with integers, one way of rounding up is to take advantage of the fact that `//` rounds down: Just do the division on the negative number, then negate the answer. No import, floating point, or conditional needed. ``` rounded_up = -(-numerator // denominator) ``` For example: ``` >>> print(-(-101 // 5)) 21...
Importing sound files into Python as NumPy arrays (alternatives to audiolab)
2,356,779
6
2010-03-01T15:20:55Z
2,359,690
7
2010-03-01T22:46:13Z
[ "python", "audio", "numpy", "scipy" ]
I've been using [Audiolab](http://cournape.github.com/audiolab/) to import sound files in the past, and it worked quite well. However: * It doesn't support some formats, like mp3, because the underlying libsndfile [refuses to support them](http://www.mega-nerd.com/libsndfile/FAQ.html#Q020) * It [doesn't work in Python...
Audiolab is working for me on Ubuntu 9.04 with Python 2.6.2, so it might be a Windows problem. In your link to the forum, the author also suggests that it is a Windows error. In the past, this option has worked for me, too: ``` from scipy.io import wavfile fs, data = wavfile.read(filename) ``` Just beware that `data...
How to check whether string might be type-cast to float in Python?
2,356,925
17
2010-03-01T15:39:26Z
2,357,034
12
2010-03-01T15:54:48Z
[ "python", "floating-point" ]
Is there some function like `str.isnumeric` but applicable to float? ``` '13.37'.isnumeric() #False ``` I still use this: ``` def isFloat(string): try: float(string) return True except ValueError: return False ```
As Imran says, your code is absolutely fine as shown. However, it does encourage clients of `isFloat` down the "Look Before You Leap" path instead of the more Pythonic "Easier to Ask Forgiveness than Permission" path. It's more Pythonic for clients to assume they have a string representing a float but be ready to han...
What is the proper way to comment functions in python?
2,357,230
69
2010-03-01T16:21:13Z
2,357,251
132
2010-03-01T16:23:09Z
[ "python" ]
Is there a generally accepted way to do this? Is this acceptable: ``` ######################################################### # Create a new user ######################################################### def add(self): ```
The correct way to do it is to provide a docstring. That way, `help(add)` will also spit out your comment. ``` def add(self): """Create a new user. Line 2 of comment... And so on... """ ``` That's three double quotes to open the comment and another three double quotes to end it. You can also use any ...
What is the proper way to comment functions in python?
2,357,230
69
2010-03-01T16:21:13Z
2,357,256
16
2010-03-01T16:23:45Z
[ "python" ]
Is there a generally accepted way to do this? Is this acceptable: ``` ######################################################### # Create a new user ######################################################### def add(self): ```
Use a [docstring](http://www.python.org/dev/peps/pep-0257/): > a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the `__doc__` special attribute of that object. > > All modules should normally have docstrings, and all functions and classes ...
What is the proper way to comment functions in python?
2,357,230
69
2010-03-01T16:21:13Z
2,357,274
18
2010-03-01T16:27:08Z
[ "python" ]
Is there a generally accepted way to do this? Is this acceptable: ``` ######################################################### # Create a new user ######################################################### def add(self): ```
Use a docstring, as others have already written. You can even go one step further and add a [doctest](http://docs.python.org/library/doctest.html?highlight=doctest#module-doctest) to your docstring, making automated testing of your functions a snap.
numpy: extending arrays along a new axis?
2,357,686
18
2010-03-01T17:24:15Z
2,357,785
16
2010-03-01T17:42:29Z
[ "python", "arrays", "numpy" ]
Surely there must be a way to do this... I can't work it out. I have a (9,4) array, and I want to repeat it along a 3rd axis 4096 times... So it becomes simply (9,4,4096), with each value from the 9,4 array simply repeated 4096 times down the new axis. If my dubious 3D diagram makes sense (the diagonal is a z-axis) ...
Here is one way: ``` import scipy X = scipy.rand(9,4,1) Y = X.repeat(4096,2) ``` If `X` is given to you as only (9,4), then ``` import scipy X = scipy.rand(9,4) Y = X.reshape(9,4,1).repeat(4096,2) ```
numpy: extending arrays along a new axis?
2,357,686
18
2010-03-01T17:24:15Z
2,360,784
8
2010-03-02T03:48:07Z
[ "python", "arrays", "numpy" ]
Surely there must be a way to do this... I can't work it out. I have a (9,4) array, and I want to repeat it along a 3rd axis 4096 times... So it becomes simply (9,4,4096), with each value from the 9,4 array simply repeated 4096 times down the new axis. If my dubious 3D diagram makes sense (the diagonal is a z-axis) ...
You can also rely on the broadcasting rules to repeat-fill a re-sized array: ``` import numpy X = numpy.random.rand(9,4) Y = numpy.resize(X,(4096,9,4)) ``` If you don't like the axes ordered this way, you can then transpose: ``` Z = Y.transpose(1,2,0) ```
How can I implement a tree in Python? Are there any built in data structures in Python like in Java?
2,358,045
58
2010-03-01T18:24:27Z
2,358,063
11
2010-03-01T18:28:31Z
[ "python", "data-structures", "tree", "python-3.x" ]
I am trying to construct a general tree. Are there any built in data structures in Python to implement a tree?
There aren't trees built in, but you can easily construct one by subclassing a Node type from List and writing the traversal methods. If you do this, I've found [bisect](http://docs.python.org/library/bisect.html) useful. There are also many implementations on [PyPi](http://pypi.python.org/pypi) that you can browse. ...
How can I implement a tree in Python? Are there any built in data structures in Python like in Java?
2,358,045
58
2010-03-01T18:24:27Z
2,358,075
62
2010-03-01T18:29:51Z
[ "python", "data-structures", "tree", "python-3.x" ]
I am trying to construct a general tree. Are there any built in data structures in Python to implement a tree?
Python doesn't have the quite the extensive range of "built-in" data structures as Java does. However, because Python is dynamic, a general tree is easy to create. For example, a binary tree might be: ``` class Tree(object): def __init__(self): self.left = None self.right = None self.data =...
How can I implement a tree in Python? Are there any built in data structures in Python like in Java?
2,358,045
58
2010-03-01T18:24:27Z
10,322,593
10
2012-04-25T19:39:46Z
[ "python", "data-structures", "tree", "python-3.x" ]
I am trying to construct a general tree. Are there any built in data structures in Python to implement a tree?
You can try: ``` from collections import defaultdict def hash(): return defaultdict(hash) users = hash() users['harold']['username'] = 'hrldcpr' users['handler']['username'] = 'matthandlersux' ``` As suggested here: <https://gist.github.com/2012250>
How can I implement a tree in Python? Are there any built in data structures in Python like in Java?
2,358,045
58
2010-03-01T18:24:27Z
19,040,443
7
2013-09-26T23:38:46Z
[ "python", "data-structures", "tree", "python-3.x" ]
I am trying to construct a general tree. Are there any built in data structures in Python to implement a tree?
I implemented a rooted tree as a dictionary `{child:parent}`. So for instance with the root node `0`, a tree might look like that: ``` tree={1:0, 2:0, 3:1, 4:2, 5:3} ``` This structure made it quite easy to go upward along a path from any node to the root, which was relevant for the problem I was working on.
How can I implement a tree in Python? Are there any built in data structures in Python like in Java?
2,358,045
58
2010-03-01T18:24:27Z
28,015,122
10
2015-01-18T21:40:49Z
[ "python", "data-structures", "tree", "python-3.x" ]
I am trying to construct a general tree. Are there any built in data structures in Python to implement a tree?
A generic tree is a node with zero or more children, each one a proper (tree) node. It isn't the same as a binary tree, they're different data structures, although both shares some terminology. There isn't any builtin data structure for generic trees in Python, but it's easily implemented with classes. ``` class Tree...
How can I implement a tree in Python? Are there any built in data structures in Python like in Java?
2,358,045
58
2010-03-01T18:24:27Z
29,531,977
8
2015-04-09T07:07:59Z
[ "python", "data-structures", "tree", "python-3.x" ]
I am trying to construct a general tree. Are there any built in data structures in Python to implement a tree?
``` class Node: """ Class Node """ def __init__(self, value): self.left = None self.data = value self.right = None class Tree: """ Class tree will provide a tree as well as utility functions. """ def createNode(self, data): """ Utility function t...
Making Django development server faster at serving static media
2,358,450
9
2010-03-01T19:26:44Z
2,358,484
7
2010-03-01T19:31:30Z
[ "python", "django" ]
I'm using the Django `manage.py runserver` for developing my application (obviously), but it takes **10 seconds** to completely load a page because the development server is very, very slow at serving static media. Is there any way to speed it up or some kind of workaround? I'm using Windows 7.
Consider using [`mod_wsgi`](http://code.google.com/p/modwsgi/) instead, and having httpd handle the static media.
If I'm only planning to use MySQL, and if speed is a priority, is there any convincing reason to use SQLAlchemy?
2,358,822
3
2010-03-01T20:24:25Z
2,358,852
7
2010-03-01T20:28:31Z
[ "python", "mysql", "sqlalchemy", "pylons" ]
SQLAlchemy seems really heavyweight if all I use is MySQL. Why are convincing reasons for/against the use of SQLAlchemy in an application that only uses MySQL.
ORM means that your OO application actually makes sense when interpreted as the interaction of objects. No ORM means that you must wallow in the impedance mismatch between SQL and Objects. Working without an ORM means lots of redundant code to map between SQL query result sets, individual SQL statements and objects. ...
Python - lexical analysis and tokenization
2,358,890
9
2010-03-01T20:32:35Z
2,359,619
9
2010-03-01T22:36:45Z
[ "python", "transform", "lexical-analysis" ]
I'm looking to speed along my discovery process here quite a bit, as this is my first venture into the world of lexical analysis. Maybe this is even the wrong path. First, I'll describe my problem: I've got very large properties files (in the order of 1,000 properties), which when distilled, are really just about 15 i...
There's an excellent article on [Using Regular Expressions for Lexical Analysis](http://effbot.org/zone/xml-scanner.htm) at [effbot.org](http://effbot.org/). Adapting the tokenizer to your problem: ``` import re token_pattern = r""" (?P<identifier>[a-zA-Z_][a-zA-Z0-9_]*) |(?P<integer>[0-9]+) |(?P<dot>\.) |(?P<open_v...
How can you programmatically inspect the stack trace of an exception in Python?
2,359,248
17
2010-03-01T21:37:14Z
2,359,522
13
2010-03-01T22:20:14Z
[ "python", "exception-handling", "stack-trace", "traceback" ]
When an exception occurs in Python, can you inspect the stack? Can you determine its depth? I've looked at the [traceback](http://docs.python.org/library/traceback.html) module, but I can't figure out how to use it. My goal is to catch any exceptions that occur during the parsing of an eval expression, without catchin...
`traceback` is enough - and I suppose that documentation describes it rather well. Simplified example: ``` import sys import traceback try: eval('a') except NameError: traceback.print_exc(file=sys.stdout) ```
Solving embarassingly parallel problems using Python multiprocessing
2,359,253
65
2010-03-01T21:38:18Z
2,364,667
50
2010-03-02T16:16:29Z
[ "python", "concurrency", "multiprocessing", "embarrassingly-parallel" ]
How does one use [multiprocessing](http://docs.python.org/library/multiprocessing.html) to tackle [embarrassingly parallel problems](http://en.wikipedia.org/wiki/Embarrassingly_parallel)? Embarassingly parallel problems typically consist of three basic parts: 1. **Read** input data (from a file, database, tcp connect...
My solution has an extra bell and whistle to make sure that the order of the output has the same as the order of the input. I use multiprocessing.queue's to send data between processes, sending stop messages so each process knows to quit checking the queues. I think the comments in the source should make it clear what'...
How to find elements by 'id' field in SVG file using Python
2,359,317
3
2010-03-01T21:49:49Z
2,359,880
9
2010-03-01T23:26:33Z
[ "python", "xml", "dom", "svg", "minidom" ]
Below is an excerpt from an .svg file (which is xml): ``` <text xml:space="preserve" style="font-size:14.19380379px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;line-height:125%;writing-mode:lr-tb;text-anchor:start;fill:#000000;fill-opacity:1;stroke:non...
Sorry, I don't know my way around minidom. Also, I had to find the namespace declarations from a sample svg document so that your excerpt could load. I personally use lxml.etree. I'd recommend that you use XPATH for addressing parts of your XML document. It's pretty powerful and there's help here on SO if you're strug...
Correctness about variable scope
2,359,726
7
2010-03-01T22:54:20Z
2,359,771
8
2010-03-01T23:02:29Z
[ "python", "scope" ]
I'm currently developing some things in Python and I have a question about variables scope. This is the code: ``` a = None anything = False if anything: a = 1 else: a = 2 print a # prints 2 ``` If I remove the first line (a = None) the code still works as before. However in this case I'd be declaring the va...
As a rule of thumb, scopes are created in three places: 1. File-scope - otherwise known as module scope 2. Class-scope - created inside `class` blocks 3. Function-scope - created inside `def` blocks (There are a few exceptions to these.) Assigning to a name reserves it in the scope namespace, marked as unbound until...
Dealing with UTF-8 numbers in Python
2,359,832
10
2010-03-01T23:16:40Z
2,359,858
12
2010-03-01T23:22:37Z
[ "python", "utf-8", "character-encoding", "byte-order-mark" ]
Suppose I am reading a file containing 3 comma separated numbers. The file was saved with with an unknown encoding, so far I am dealing with ANSI and UTF-8. If the file was in UTF-8 and it had 1 row with values 115,113,12 then: ``` with open(file) as f: a,b,c=map(int,f.readline().split(',')) ``` would throw this:...
What you're seeing is a UTF-8 encoded [BOM](http://en.wikipedia.org/wiki/Byte-order_mark), or "Byte Order Mark". The BOM is not usually used for UTF-8 files, so the best way to handle it might be to open the file with a UTF-8 codec, and skip over the `U+FEFF` character if present.
Dealing with UTF-8 numbers in Python
2,359,832
10
2010-03-01T23:16:40Z
2,360,047
17
2010-03-02T00:01:27Z
[ "python", "utf-8", "character-encoding", "byte-order-mark" ]
Suppose I am reading a file containing 3 comma separated numbers. The file was saved with with an unknown encoding, so far I am dealing with ANSI and UTF-8. If the file was in UTF-8 and it had 1 row with values 115,113,12 then: ``` with open(file) as f: a,b,c=map(int,f.readline().split(',')) ``` would throw this:...
``` import codecs with codecs.open(file, "r", "utf-8-sig") as f: a, b, c= map(int, f.readline().split(",")) ``` This works in Python 2.6.4. The `codecs.open` call opens the file and returns data as unicode, decoding from UTF-8 and ignoring the initial BOM.
Pure Python in Xcode?
2,359,994
3
2010-03-01T23:49:13Z
2,360,374
7
2010-03-02T01:41:35Z
[ "python", "xcode" ]
Could anyone tell me how to use pure Python without Cocoa support in Xcode? I can only find the Cocoa-Python template on the Internet. Thanks in advance.
If you are just trying to write pure Python command line tools, using Xcode is like using a big sledge hammer to hit a tiny nail, in other words, probably not the best tool for the job. There are some old posts out there about how to set up a pure Python Xcode project, like [this one](http://www.mactech.com/articles/ma...
Concurrent downloads - Python
2,360,291
9
2010-03-02T01:14:57Z
2,361,129
12
2010-03-02T05:41:45Z
[ "python", "html", "concurrency", "web-crawler" ]
the plan is this: I download a webpage, collect a list of images parsed in the DOM and then download these. After this I would iterate through the images in order to evaluate which image is best suited to represent the webpage. Problem is that images are downloaded 1 by 1 and this can take quite some time. --- It w...
Speeding up crawling is basically [Eventlet](http://eventlet.net/)'s main use case. It's deeply fast -- we have an application that has to hit 2,000,000 urls in a few minutes. It makes use of the fastest event interface on your system (epoll, generally), and uses greenthreads (which are built on top of coroutines and a...
Google App Engine: Give arguments to a script from URL handler?
2,360,638
2
2010-03-02T03:00:08Z
2,360,718
11
2010-03-02T03:28:30Z
[ "python", "google-app-engine" ]
Here is a portion of my `app.yaml` file: ``` handlers: - url: /remote_api script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py login: admin - url: /detail/(\d)+ script: Detail.py - url: /.* script: Index.py ``` I want that capture group (the one signified by `(\d)`) to be available to the script `De...
I see two questions, how to pass elements of the url path as variables in the handler, and how to get the catch-all to render properly. Both of these have more to do with the main() method in the handler than the app.yaml 1) to pass the id in the `/detail/(\d)` url, you want something like this: ``` class DetailHand...
What exactly does "import *" import?
2,360,724
15
2010-03-02T03:31:45Z
2,360,782
8
2010-03-02T03:47:36Z
[ "python", "namespaces", "python-import" ]
In Python, what exactly does `import *` import? Does it import `__init__.py` found in the containing folder? For example, is it necessary to declare `from project.model import __init__`, or is `from project.model import *` sufficient?
It import (into the current namespace) whatever names the module (or package) lists in its `__all__` attribute -- missing such an attribute, all names that don't start with `_`. It's mostly intended as a handy shortcut for use only in interactive interpreter sessions: as other answers suggest, **don't** use it in a pr...
What exactly does "import *" import?
2,360,724
15
2010-03-02T03:31:45Z
2,360,808
23
2010-03-02T03:56:25Z
[ "python", "namespaces", "python-import" ]
In Python, what exactly does `import *` import? Does it import `__init__.py` found in the containing folder? For example, is it necessary to declare `from project.model import __init__`, or is `from project.model import *` sufficient?
The "advantage" of `from xyz import *` as opposed to other forms of import is that it imports *everything* (well, almost... [see (a) below] everything) from the designated module under the current module. This allows using the various objects (variables, classes, methods...) from the imported module **without prefixing...
How do I correctly install dulwich to get hg-git working on Windows?
2,360,944
47
2010-03-02T04:40:47Z
2,564,931
8
2010-04-02T03:57:15Z
[ "python", "windows", "mercurial", "hg-git", "dulwich" ]
I'm trying to use the hg-git Mercurial extension on Windows (Windows 7 64-bit, to be specific). I have Mercurial and Git installed. I have Python 2.5 (32-bit) installed. I followed the instructions on <http://hg-git.github.com/> to install the extension. The initial easy\_install failed because it was unable to compil...
If you can install TortoiseHg, it includes dulwich and other requirements.
How do I correctly install dulwich to get hg-git working on Windows?
2,360,944
47
2010-03-02T04:40:47Z
2,733,516
16
2010-04-28T22:25:07Z
[ "python", "windows", "mercurial", "hg-git", "dulwich" ]
I'm trying to use the hg-git Mercurial extension on Windows (Windows 7 64-bit, to be specific). I have Mercurial and Git installed. I have Python 2.5 (32-bit) installed. I followed the instructions on <http://hg-git.github.com/> to install the extension. The initial easy\_install failed because it was unable to compil...
> That makes me think dulwich is not > installed correctly, or not in the > path. You're absolutely right. Mercurial binary distributions for Windows are 'frozen' - they use the Python code and interpreter bundled with them and therefore independent of packages installed in system PYTHONPATH. When you specify path to ...
How do I correctly install dulwich to get hg-git working on Windows?
2,360,944
47
2010-03-02T04:40:47Z
6,998,710
10
2011-08-09T15:28:17Z
[ "python", "windows", "mercurial", "hg-git", "dulwich" ]
I'm trying to use the hg-git Mercurial extension on Windows (Windows 7 64-bit, to be specific). I have Mercurial and Git installed. I have Python 2.5 (32-bit) installed. I followed the instructions on <http://hg-git.github.com/> to install the extension. The initial easy\_install failed because it was unable to compil...
I found a simpler solution at <http://candidcode.com/2010/01/12/a-guide-to-converting-from-mercurial-hg-to-git-on-a-windows-client/> And then I found a yet simpler solution myself: To use the hg-git Mercurial extension on Windows: 1. install the official Mercurial binaries 2. put dulwich folder from dulwich sourc...