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
Getting the pattern back from a compiled re?
190,967
17
2008-10-10T11:58:40Z
190,975
21
2008-10-10T12:01:41Z
[ "python", "regex" ]
Assume I have created a compiled re: ``` x = re.compile('^\d+$') ``` Is there a way to extract the pattern string (^\d+$) back from the x?
You can get it back with ``` x.pattern ``` from the Python [documentation on Regular Expression Objects](https://docs.python.org/3/library/re.html#re.regex.pattern)
How to get a complete list of object's methods and attributes?
191,010
152
2008-10-10T12:18:32Z
191,029
100
2008-10-10T12:25:22Z
[ "python" ]
``` dir(re.compile(pattern)) ``` does not return pattern as one of the lists's elements. Namely it returns: ``` ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] ``` According to the manual, it is supposed to contain > the object's attributes' names, the > nam...
For the **complete** list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the `getattr` built-in function. As the user can reimplement `__getattr__`, suddenly allowing any kind of attribute, there is no possible generic way to generate that li...
How to get a complete list of object's methods and attributes?
191,010
152
2008-10-10T12:18:32Z
191,679
35
2008-10-10T14:46:09Z
[ "python" ]
``` dir(re.compile(pattern)) ``` does not return pattern as one of the lists's elements. Namely it returns: ``` ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] ``` According to the manual, it is supposed to contain > the object's attributes' names, the > nam...
That is why the new `__dir__()` method has been added in python 2.6 see: * <http://docs.python.org/whatsnew/2.6.html#other-language-changes> (scroll down a little bit) * <http://bugs.python.org/issue1591665>
How to get a complete list of object's methods and attributes?
191,010
152
2008-10-10T12:18:32Z
10,313,703
15
2012-04-25T10:19:45Z
[ "python" ]
``` dir(re.compile(pattern)) ``` does not return pattern as one of the lists's elements. Namely it returns: ``` ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] ``` According to the manual, it is supposed to contain > the object's attributes' names, the > nam...
Here is a practical addition to the answers of PierreBdR and Moe: -- for Python >= 2.6 *and new-style classes*, dir() seems to be enough; -- *for old-style classes*, we can at least do what a [standard module](http://docs.python.org/library/rlcompleter.html) does to support tab completion: in addition to `dir()`, lo...
Python Webframework Confusion
191,062
10
2008-10-10T12:40:08Z
191,069
15
2008-10-10T12:43:02Z
[ "python", "pylons", "cherrypy", "web-frameworks", "turbogears" ]
Could someone please explain to me how the current python webframworks fit together? The three I've heard of are CherryPy, TurboGears and Pylons. However I'm confused because TurboGears seems to use CherryPy as the 'Controller' (although isn't CherryPy a framework in in it's own right?), and TurbGears 2 is going to be...
There are more to it ofcourse. Here's a comprehensive list and details! [**Web Frameworks for Python**](http://wiki.python.org/moin/WebFrameworks) Extract from above link: > ## Popular Full-Stack Frameworks > > A web application may use a > combination of a base HTTP application > server, a storage mechanism such a...
Python Webframework Confusion
191,062
10
2008-10-10T12:40:08Z
191,805
7
2008-10-10T15:15:33Z
[ "python", "pylons", "cherrypy", "web-frameworks", "turbogears" ]
Could someone please explain to me how the current python webframworks fit together? The three I've heard of are CherryPy, TurboGears and Pylons. However I'm confused because TurboGears seems to use CherryPy as the 'Controller' (although isn't CherryPy a framework in in it's own right?), and TurbGears 2 is going to be...
Give a try to web2py. It is point and click (you do not even need to install Python, comes with it). You develop using a web interface and you can deploy almost everywhere, including iPhone, Oracle and Google App Engine. Before trying web2py, try install some of the other Python frameworks, you will appreciate it even ...
How to convert a file to utf-8 in Python?
191,359
35
2008-10-10T13:50:26Z
191,403
40
2008-10-10T13:59:07Z
[ "python", "encoding", "file", "utf-8" ]
I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part. I'd like to do the equivalent of: ``` iconv -t utf-8 $file > converted/$file # this is shell code ``` Thanks!
You can use the [codecs module](https://docs.python.org/2/library/codecs.html), like this: ``` import codecs BLOCKSIZE = 1048576 # or some other, desired size in bytes with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile: with codecs.open(targetFileName, "w", "utf-8") as targetFile: ...
How to convert a file to utf-8 in Python?
191,359
35
2008-10-10T13:50:26Z
191,455
20
2008-10-10T14:07:07Z
[ "python", "encoding", "file", "utf-8" ]
I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part. I'd like to do the equivalent of: ``` iconv -t utf-8 $file > converted/$file # this is shell code ``` Thanks!
This worked for me in a small test: ``` sourceEncoding = "iso-8859-1" targetEncoding = "utf-8" source = open("source") target = open("target", "w") target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding)) ```
How to convert a file to utf-8 in Python?
191,359
35
2008-10-10T13:50:26Z
192,086
10
2008-10-10T16:14:45Z
[ "python", "encoding", "file", "utf-8" ]
I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part. I'd like to do the equivalent of: ``` iconv -t utf-8 $file > converted/$file # this is shell code ``` Thanks!
Thanks for the replies, it works! And since the source files are in mixed formats, I added a list of source formats to be tried in sequence (`sourceFormats`), and on `UnicodeDecodeError` I try the next format: ``` from __future__ import with_statement import os import sys import codecs from chardet.universaldetector...
Converting XML to JSON using Python?
191,536
82
2008-10-10T14:19:44Z
191,617
35
2008-10-10T14:34:55Z
[ "python", "xml", "json" ]
I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can. So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're look...
There is no "one-to-one" mapping between XML and JSON, so converting one to the other necessarily requires some understanding of what you want to *do* with the results. That being said, Python's standard library has [several modules for parsing XML](http://docs.python.org/2/library/xml.html) (including DOM, SAX, and E...
Converting XML to JSON using Python?
191,536
82
2008-10-10T14:19:44Z
10,201,405
169
2012-04-18T01:06:05Z
[ "python", "xml", "json" ]
I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can. So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're look...
[xmltodict](https://github.com/martinblech/xmltodict) (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this ["standard"](http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html). It is [Expat](http://docs.python.org/library/pyexpat.html)-based, so i...
Configuring python
191,700
2
2008-10-10T14:52:04Z
191,744
11
2008-10-10T15:02:11Z
[ "python", "memory" ]
I am new to python and struggling to find how to control the amount of memory a python process can take? I am running python on a Cento OS machine with more than 2 GB of main memory size. Python is taking up only 128mb of this and I want to allocate it more. I tried to search all over the internet on this for last half...
Forget all that, python just allocates more memory as needed, there is not a myriad of comandline arguments for the VM as in java, just let it run. For all comandline switches you can just run python -h or read man python.
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
192,116
9
2008-10-10T16:20:40Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
You can use the "dir()" function to do this. ``` >>> import sys >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder , 'call_tracing', 'callstats', 'copyright', 'displ...
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
192,184
85
2008-10-10T16:36:28Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
``` def dump(obj): for attr in dir(obj): print "obj.%s = %s" % (attr, getattr(obj, attr)) ``` There are many 3rd-party functions out there that add things like exception handling, national/special character printing, recursing into nested objects etc. according to their authors' preferences. But they all basical...
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
192,207
26
2008-10-10T16:44:50Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
*dir* has been mentioned, but that'll only give you the attributes' names. If you want their values as well try \_\_dict\_\_. ``` class O: def __init__ (self): self.value = 3 o = O() ``` >>> o.\_\_dict\_\_ {'value': 3}
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
192,365
263
2008-10-10T17:27:06Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
You are really mixing together two different things. Use [`dir()`](https://docs.python.org/3/library/functions.html#dir), [`vars()`](https://docs.python.org/3/library/functions.html#vars) or the [`inspect`](https://docs.python.org/3/library/inspect.html) module to get what you are interested in (I use `__builtins__` a...
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
193,539
485
2008-10-11T01:16:32Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
You want vars() mixed with pprint: ``` from pprint import pprint pprint (vars(your_object)) ```
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
193,808
15
2008-10-11T07:29:09Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
To print the current state of the object you might: ``` >>> obj # in an interpreter ``` or ``` print repr(obj) # in a script ``` or ``` print obj ``` For your classes define `__str__` or `__repr__` methods. From the [Python documentation](http://www.python.org/doc/2.5.2/ref/customization.html): > `__repr__(self)...
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
13,391,460
8
2012-11-15T04:11:48Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
Might be worth checking out -- [Is there a Python equivalent to Perl's Data::Dumper?](http://stackoverflow.com/questions/2540567/is-there-a-python-equivalent-to-perls-datadumper) My recommendation is this -- <https://gist.github.com/1071857> Note that perl has a module called Data::Dumper which translates object da...
How do I log an exception at warning- or info-level with trace back using the python logging framework?
192,261
24
2008-10-10T17:02:08Z
193,153
32
2008-10-10T21:49:50Z
[ "python", "exception", "logging" ]
Using something like this: ``` try: #Something... except BaseException, excep: logger = logging.getLogger("componet") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) ``` I would rather not have it on the error-level cause in my special case ...
From The [logging documentation](http://docs.python.org/library/logging.html#logging.Logger.debug): > There are two keyword arguments in > kwargs which are inspected: exc\_info > which, if it does not evaluate as > false, causes exception information to > be added to the logging message. If an > exception tuple (in th...
In Django how do I notify a parent when a child is saved in a foreign key relationship?
192,367
14
2008-10-10T17:27:35Z
192,525
17
2008-10-10T18:18:56Z
[ "python", "django", "django-models" ]
I have the following two models: ``` class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.no...
What you want to look into is [Django's signals](http://docs.djangoproject.com/en/dev/ref/signals/) (check out [this page](http://docs.djangoproject.com/en/dev/topics/signals/) too), specifically the model signals--more specifically, the **post\_save** signal. Signals are Django's version of a plugin/hook system. The p...
TFS Webservice Documentation
192,579
11
2008-10-10T18:36:02Z
192,792
13
2008-10-10T19:43:39Z
[ "python", "web-services", "api", "tfs" ]
We use a lot of of python to do much of our deployment and would be handy to connect to our TFS server to get information on iteration paths, tickets etc. I can see the webservice but unable to find any documentation. Just wondering if anyone knew of anything?
The web services are not documented by Microsoft as it is not an officially supported route to talk to TFS. The officially supported route is to use their [.NET API](http://msdn.microsoft.com/en-us/library/bb130146(VS.80).aspx). In the case of your sort of application, the course of action I usually recommend is to cr...
Can you monkey patch methods on core types in python?
192,649
39
2008-10-10T18:56:12Z
192,703
33
2008-10-10T19:15:42Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Ruby can add methods to the Number class and other core types to get effects like: ``` 1.should_equal(1) ``` But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified? *Update: Rather than talking about different definitions of mon...
What exactly do you mean by Monkey Patch here? There are [several slightly different definitions](http://wikipedia.org/wiki/Monkey_patch). If you mean, "can you change a class's methods at runtime?", then the answer is emphatically yes: ``` class Foo: pass # dummy class Foo.bar = lambda self: 42 x = Foo() print x...
Can you monkey patch methods on core types in python?
192,649
39
2008-10-10T18:56:12Z
192,857
55
2008-10-10T20:01:31Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Ruby can add methods to the Number class and other core types to get effects like: ``` 1.should_equal(1) ``` But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified? *Update: Rather than talking about different definitions of mon...
No, you cannot. In Python, all data (classes, methods, functions, etc) defined in C extension modules (including builtins) are immutable. This is because C modules are shared between multiple interpreters in the same process, so monkeypatching them would also affect unrelated interpreters in the same process. However,...
Can you monkey patch methods on core types in python?
192,649
39
2008-10-10T18:56:12Z
193,660
13
2008-10-11T04:50:58Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Ruby can add methods to the Number class and other core types to get effects like: ``` 1.should_equal(1) ``` But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified? *Update: Rather than talking about different definitions of mon...
Python's core types are immutable by design, as other users have pointed out: ``` >>> int.frobnicate = lambda self: whatever() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't set attributes of built-in/extension type 'int' ``` You certainly *could* achieve the effect you desc...
Can you monkey patch methods on core types in python?
192,649
39
2008-10-10T18:56:12Z
4,025,310
20
2010-10-26T15:37:39Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Ruby can add methods to the Number class and other core types to get effects like: ``` 1.should_equal(1) ``` But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified? *Update: Rather than talking about different definitions of mon...
``` def should_equal_def(self, value): if self != value: raise ValueError, "%r should equal %r" % (self, value) class MyPatchedInt(int): should_equal=should_equal_def class MyPatchedStr(str): should_equal=should_equal_def import __builtin__ __builtin__.str = MyPatchedStr __builtin__.int = MyPatch...
Can you monkey patch methods on core types in python?
192,649
39
2008-10-10T18:56:12Z
17,246,179
17
2013-06-22T00:33:56Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Ruby can add methods to the Number class and other core types to get effects like: ``` 1.should_equal(1) ``` But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified? *Update: Rather than talking about different definitions of mon...
You can do this, but it takes a little bit of hacking. Fortunately, there's a module now called "Forbidden Fruit" that gives you the power to patch methods of built-in types very simply. You can find it at <http://clarete.github.io/forbiddenfruit/?goback=.gde_50788_member_228887816> or <https://pypi.python.org/pypi/...
XML parsing - ElementTree vs SAX and DOM
192,907
54
2008-10-10T20:22:24Z
192,913
7
2008-10-10T20:25:05Z
[ "python", "xml", "dom", "sax", "elementtree" ]
Python has several ways to parse XML... I understand the very basics of parsing with **SAX**. It functions as a stream parser, with an event-driven API. I understand the **DOM** parser also. It reads the XML into memory and coverts it to objects that can be accessed with Python. Generally speaking, it was easy to ch...
ElementTree's parse() is like DOM, whereas iterparse() is like SAX. In my opinion, ElementTree is better than DOM and SAX in that it provides API easier to work with.
XML parsing - ElementTree vs SAX and DOM
192,907
54
2008-10-10T20:22:24Z
194,248
52
2008-10-11T16:02:41Z
[ "python", "xml", "dom", "sax", "elementtree" ]
Python has several ways to parse XML... I understand the very basics of parsing with **SAX**. It functions as a stream parser, with an event-driven API. I understand the **DOM** parser also. It reads the XML into memory and coverts it to objects that can be accessed with Python. Generally speaking, it was easy to ch...
ElementTree is much easier to use, because it represents an XML tree (basically) as a structure of lists, and attributes are represented as dictionaries. ElementTree needs much less memory for XML trees than DOM (and thus is faster), and the parsing overhead via `iterparse` is comparable to SAX. Additionally, `iterpar...
XML parsing - ElementTree vs SAX and DOM
192,907
54
2008-10-10T20:22:24Z
15,452,402
10
2013-03-16T17:33:15Z
[ "python", "xml", "dom", "sax", "elementtree" ]
Python has several ways to parse XML... I understand the very basics of parsing with **SAX**. It functions as a stream parser, with an event-driven API. I understand the **DOM** parser also. It reads the XML into memory and coverts it to objects that can be accessed with Python. Generally speaking, it was easy to ch...
# Minimal DOM implementation: Link: <http://docs.python.org/2/library/xml.dom.minidom.html#module-xml.dom.minidom> Python supplies a full, W3C-standard implementation of XML DOM (*xml.dom*) and a minimal one, *xml.dom.minidom*. This latter one is simpler and smaller than the full implementation. However, from a "pars...
Standalone Python applications in Linux
193,077
27
2008-10-10T21:26:26Z
193,101
7
2008-10-10T21:34:01Z
[ "python", "linux" ]
How can I distribute a standalone Python application in Linux? I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, an...
You can't easily do it in a distribution-neutral format. The only reliable dependency tracking mechanisms are built into the package management systems on the distributions and will vary from distribution to distribution. You'll effectively have to do rpm for fedora, debs for ubuntu and debian etc. Py2exe works fine o...
Standalone Python applications in Linux
193,077
27
2008-10-10T21:26:26Z
193,135
9
2008-10-10T21:44:11Z
[ "python", "linux" ]
How can I distribute a standalone Python application in Linux? I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, an...
You might want to look at the dependency declarations in [setuptools](http://peak.telecommunity.com/DevCenter/setuptools?action=highlight&value=EasyInstall#declaring-dependencies). This might provide a way to assure that the right packages are either available in the environment or can be installed by someone with appr...
Standalone Python applications in Linux
193,077
27
2008-10-10T21:26:26Z
193,963
21
2008-10-11T11:05:10Z
[ "python", "linux" ]
How can I distribute a standalone Python application in Linux? I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, an...
Create a deb (for everything Debian-derived) and an rpm (for Fedora/SuSE). Add the right dependencies to the packaging and you can be reasonably sure that it will work.
Standalone Python applications in Linux
193,077
27
2008-10-10T21:26:26Z
909,055
10
2009-05-26T05:32:13Z
[ "python", "linux" ]
How can I distribute a standalone Python application in Linux? I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, an...
You can use [cx\_Freeze](http://cx-freeze.sourceforge.net/) to do this. It's just like py2exe (bundles together the interpreter and and startup script and all required libraries and modules), but works on both Linux and Windows. It collects the dependencies from the environment in which it is run, which means that the...
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
193,181
212
2008-10-10T22:03:40Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In...
Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple. * `/scripts` or `/bin` for that kind of command-line interface stuff * `/tests` for your tests * `/lib` for your C-language libraries * `/doc` for most documentation * `/apidoc` for the...
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
193,280
12
2008-10-10T22:57:39Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In...
In my experience, it's just a matter of iteration. Put your data and code wherever you think they go. Chances are, you'll be wrong anyway. But once you get a better idea of exactly how things are going to shape up, you're in a much better position to make these kinds of guesses. As far as extension sources, we have a ...
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
3,419,951
126
2010-08-05T23:29:58Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In...
This [blog post by Jean-Paul Calderone](http://as.ynchrono.us/2007/12/filesystem-structure-of-python-project_21.html) is commonly given as an answer in #python on Freenode. > ## Filesystem structure of a Python project > > Do: > > * name the directory something related to your project. For example, if your project is ...
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
5,169,006
18
2011-03-02T14:37:19Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In...
It's worth reading through Python's documentation on packaging, too. <http://docs.python.org/tutorial/modules.html#packages> Also make sure you're familiar with the rest of the information on that page.
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
5,998,845
146
2011-05-13T23:49:13Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In...
According to Jean-Paul Calderone's [Filesystem structure of a Python project](http://as.ynchrono.us/2007/12/filesystem-structure-of-python-project_21.html): ``` Project/ |-- bin/ | |-- project | |-- project/ | |-- test/ | | |-- __init__.py | | |-- test_main.py | | | |-- __init__.py | |-- main.py |...
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
19,871,661
69
2013-11-09T02:22:39Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In...
Check out [Open Sourcing a Python Project the Right Way](http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/). Let me excerpt the *project layout* part of that excellent article: > When setting up a project, the layout (or directory structure) is important to get right. A sensible l...
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
22,554,594
11
2014-03-21T09:17:46Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In...
Try starting the project using the [python\_boilerplate](https://pypi.python.org/pypi/python_boilerplate_template) template. It largely follows the best practices (e.g. [those here](http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/)), but is better suited in case you find yourself w...
Microphone access in Python
193,789
10
2008-10-11T07:06:48Z
247,349
16
2008-10-29T15:53:36Z
[ "python", "windows", "microphone" ]
Can I access a users microphone in Python? Sorry I forgot not everyone is a mind reader: Windows at minimum XP but Vista support would be VERY good.
I got the job done with [pyaudio](http://people.csail.mit.edu/hubert/pyaudio/) It comes with a binary installer for windows and there's even an example on how to record through the microphone and save to a wave file. Nice! I used it on Windows XP, not sure how it will do on Vista though, sorry.
What are good rules of thumb for Python imports?
193,919
60
2008-10-11T09:59:35Z
193,927
9
2008-10-11T10:10:13Z
[ "python", "python-import" ]
I am a little confused by the multitude of ways in which you can import modules in Python. ``` import X import X as Y from A import B ``` I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen a...
I would normally use `import X` on module level. If you only need a single object from a module, use `from X import Y`. Only use `import X as Y` in case you're otherwise confronted with a name clash. I only use imports on function level to import stuff I need when the module is used as the main module, like: ``` def...
What are good rules of thumb for Python imports?
193,919
60
2008-10-11T09:59:35Z
193,931
52
2008-10-11T10:15:40Z
[ "python", "python-import" ]
I am a little confused by the multitude of ways in which you can import modules in Python. ``` import X import X as Y from A import B ``` I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen a...
In production code in our company, we try to follow the following rules. We place imports at the beginning of the file, right after the main file's docstring, e.g.: ``` """ Registry related functionality. """ import wx # ... ``` Now, if we import a class that is one of few in the imported module, we import the name ...
What are good rules of thumb for Python imports?
193,919
60
2008-10-11T09:59:35Z
194,422
30
2008-10-11T18:34:42Z
[ "python", "python-import" ]
I am a little confused by the multitude of ways in which you can import modules in Python. ``` import X import X as Y from A import B ``` I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen a...
Let me just paste a part of conversation on django-dev mailing list started by Guido van Rossum: > [...] > For example, it's part of the Google Python style guides[1] that all > imports must import a module, not a class or function from that > module. There are way more classes and functions than there are > modules, ...
Running a web app in Grails vs Django
195,101
5
2008-10-12T04:36:49Z
195,152
9
2008-10-12T06:23:56Z
[ "python", "django", "grails", "groovy", "web-applications" ]
I'm currently in the planning stage for a web application and I find myself trying to decide on using Grails or Django. From an operation perspective: 1. Which ecosystem is easier to maintain (migrations, backup, disaster recovery etc.)? If using grails it'll probably be a typical tomcat + mysql on linux. If django it...
You can run grails in 256 megs of ram. Many members of the community are doing so. That being said I would say in either platform you want much more ram than that to make sure your performant. But I might also reccomend checking out www.linode.com. You can get quality hosting for a very reasonable cost and adding a bit...
Running compiled python (py2exe) as administrator in Vista
195,109
7
2008-10-12T04:46:16Z
1,445,547
34
2009-09-18T16:15:43Z
[ "python", "windows-vista", "permissions", "py2exe" ]
Is it possible to programaticly run compiled Python (comiled via py2exe) as administrator in Vista? Some more clarification: I have written a program that modifies the windows hosts file (c:\Windows\system32\drivers\etc\hosts) in Vista the program will not run and will fail with an exception unless you right-click a...
Following the examples from `Python2x\Lib\site-packages\py2exe\samples\user_access_control` just add `uac_info="requireAdministrator"` to console or windows dict: ``` windows = [{ 'script': "admin.py", 'uac_info': "requireAdministrator", },] ```
Python Decimal
195,116
13
2008-10-12T05:03:05Z
195,124
10
2008-10-12T05:11:37Z
[ "python" ]
Does anyone know of a faster decimal implementation in python. As example below demonstrates, standard python decimal is ~100 times slower than float. ``` from timeit import Timer def run(val, the_class): test = the_class(1) for c in xrange(10000): d = the_class(val) d + test d - test...
The [GMP](http://gmplib.org) library is one of the best arbitrary precision math libraries around, and there is a Python binding available at [GMPY](http://www.aleax.it/gmpy.html). I would try that method.
Python Decimal
195,116
13
2008-10-12T05:03:05Z
8,192,918
20
2011-11-19T08:47:41Z
[ "python" ]
Does anyone know of a faster decimal implementation in python. As example below demonstrates, standard python decimal is ~100 times slower than float. ``` from timeit import Timer def run(val, the_class): test = the_class(1) for c in xrange(10000): d = the_class(val) d + test d - test...
You can try [cdecimal](http://www.bytereef.org/mpdecimal/index.html): ``` from cdecimal import Decimal ```
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
195,534
56
2008-10-12T14:14:19Z
196,039
7
2008-10-12T20:45:41Z
[ "python", "apache", "nginx", "mod-wsgi" ]
What to use for a medium to large python WSGI application, Apache + mod\_wsgi or Nginx + mod\_wsgi? Which combination will need more memory and CPU time? Which one is faster? Which is known for being more stable than the other? I am also thinking to use CherryPy's WSGI server but I hear it's not very suit...
One thing that CherryPy's webserver has going for it is that it's a pure python webserver (AFAIK), which may or may not make deployment easier for you. Plus, I could see the benefits of using it if you're just using a server for WSGI and static content. (shameless plug warning: I wrote the WSGI code that I'm about to ...
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
195,534
56
2008-10-12T14:14:19Z
196,580
13
2008-10-13T02:44:24Z
[ "python", "apache", "nginx", "mod-wsgi" ]
What to use for a medium to large python WSGI application, Apache + mod\_wsgi or Nginx + mod\_wsgi? Which combination will need more memory and CPU time? Which one is faster? Which is known for being more stable than the other? I am also thinking to use CherryPy's WSGI server but I hear it's not very suit...
The main difference is that nginx is built to handle large numbers of connections in a much smaller memory space. This makes it very well suited for apps that are doing comet like connections that can have many idle open connections. This also gives it quite a smaller memory foot print. From a raw performance perspect...
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
195,534
56
2008-10-12T14:14:19Z
409,017
16
2009-01-03T13:04:18Z
[ "python", "apache", "nginx", "mod-wsgi" ]
What to use for a medium to large python WSGI application, Apache + mod\_wsgi or Nginx + mod\_wsgi? Which combination will need more memory and CPU time? Which one is faster? Which is known for being more stable than the other? I am also thinking to use CherryPy's WSGI server but I hear it's not very suit...
The author of nginx mod\_wsgi explains some differences to Apache mod\_wsgi [in this mailing list message](http://osdir.com/ml/web.nginx.english/2008-05/msg00451.html).
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
195,534
56
2008-10-12T14:14:19Z
1,038,043
67
2009-06-24T12:26:01Z
[ "python", "apache", "nginx", "mod-wsgi" ]
What to use for a medium to large python WSGI application, Apache + mod\_wsgi or Nginx + mod\_wsgi? Which combination will need more memory and CPU time? Which one is faster? Which is known for being more stable than the other? I am also thinking to use CherryPy's WSGI server but I hear it's not very suit...
For nginx/mod\_wsgi, ensure you read: <http://blog.dscpl.com.au/2009/05/blocking-requests-and-nginx-version-of.html> Because of how nginx is an event driven system underneath, it has behavioural characteristics which are detrimental to blocking applications such as is the case with WSGI based applications. Worse case...
What is the time complexity of popping elements from list in Python?
195,625
16
2008-10-12T15:58:59Z
195,647
13
2008-10-12T16:15:39Z
[ "python" ]
I wonder what is the time complexity of pop method of list objects in Python (in CPython particulary). Also does the value of N for list.pop(N) affects the complexity?
Pop() for the last element ought to be O(1) since you only need to return the element referred to by the last element in the array and update the index of the last element. I would expect pop(N) to be O(N) and require on average N/2 operations since you would need to move any elements beyond the Nth one, one position u...
What is the time complexity of popping elements from list in Python?
195,625
16
2008-10-12T15:58:59Z
195,839
23
2008-10-12T18:47:42Z
[ "python" ]
I wonder what is the time complexity of pop method of list objects in Python (in CPython particulary). Also does the value of N for list.pop(N) affects the complexity?
Yes, it is O(1) to pop the last element of a Python list, and O(N) to pop an arbitrary element (since the whole rest of the list has to be shifted). Here's a great article on how Python lists are stored and manipulated: <http://effbot.org/zone/python-list.htm>
How to avoid computation every time a python module is reloaded
195,626
6
2008-10-12T15:59:48Z
195,962
17
2008-10-12T20:12:25Z
[ "python", "nltk" ]
I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I save the computation result somewhere so that the next import/reload do...
Just to clarify: the code in the body of a module is *not* executed every time the module is imported - it is run only once, after which future imports find the already created module, rather than recreating it. Take a look at sys.modules to see the list of cached modules. However, if your problem is the time it takes...
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
196,391
189
2008-10-13T00:30:32Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/funct...
I think you are not asking the right question-- A string in python has no property corresponding to 'ascii', utf-8, or any other encoding. The source of your string (whether you read it from a file, input from a keyboard, etc.) may have encoded a unicode string in ascii to produce your string, but that's where you nee...
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
196,392
78
2008-10-13T00:30:43Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/funct...
``` def is_ascii(s): return all(ord(c) < 128 for c in s) ```
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
198,205
10
2008-10-13T16:38:25Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/funct...
How about doing this? ``` import string def isAscii(s): for c in s: if c not in string.ascii_letters: return False return True ```
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
200,267
16
2008-10-14T07:36:59Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/funct...
Your question is incorrect; the error you see is not a result of how you built python, but of a confusion between byte strings and unicode strings. Byte strings (e.g. "foo", or 'bar', in python syntax) are sequences of octets; numbers from 0-255. Unicode strings (e.g. u"foo" or u'bar') are sequences of unicode code po...
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
6,988,354
16
2011-08-08T20:47:22Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/funct...
Ran into something like this recently - for future reference ``` import chardet encoding = chardet.detect(string) if encoding['encoding'] == 'ascii': print 'string is in ascii' ``` which you could use with: ``` string_ascii = string.decode(encoding['encoding']).encode('ascii') ```
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
12,064,457
7
2012-08-21T23:24:35Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/funct...
I found this question while trying determine how to use/encode/decode a string whose encoding I wasn't sure of (and how to escape/convert special characters in that string). My first step should have been to check the type of the string- I didn't realize there I could get good data about its formatting from type(s). [...
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
18,403,812
31
2013-08-23T13:14:49Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/funct...
Python 3 way: ``` isascii = lambda s: len(s) == len(s.encode()) ```
How do I emulate Python's named printf parameters in Ruby?
196,841
8
2008-10-13T06:25:29Z
12,563,022
14
2012-09-24T10:19:55Z
[ "python", "ruby", "string", "printf" ]
In Python, you can do this: ``` print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30}) ``` What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.) **EDIT:** One of the really excellent benefits of this is that you can store the pr...
You can also use ``` printf "1: %<key1>s 2: %<key2>s\n", {:key1 => "value1", :key2 => "value2"} ``` or ``` data = {:key1 => "value1", :key2 => "value2"} printf "1: %<key1>s 2: %<key2>s\n", data ``` or (this needs ruby 1.9, for the other examples I'm not sure) ``` data = {key1: "value1", key2: "value2"} printf "1:...
How do I emulate Python's named printf parameters in Ruby?
196,841
8
2008-10-13T06:25:29Z
13,027,855
14
2012-10-23T09:53:41Z
[ "python", "ruby", "string", "printf" ]
In Python, you can do this: ``` print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30}) ``` What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.) **EDIT:** One of the really excellent benefits of this is that you can store the pr...
you do it like this: ``` values = {:hello => 'world', :world => 'hello'} puts "%{world} %{hello}" % values ``` Read this for more info: <http://ruby.runpaint.org/strings#sprintf-hash> If you need something more sophisticated, read about ERB, and google template engines. If you need to generate web pages, emails etc....
How to ensure user submit only english text
196,924
9
2008-10-13T07:32:12Z
196,950
7
2008-10-13T07:47:57Z
[ "javascript", "python", "nlp" ]
I am building a project involving natural language processing, since the nlp module currently only deal with english text, so I have to make sure the user submitted content (not long, only several words) is in english. Are there established ways to achieve this? Python or Javascript way preferred.
If the content is long enough I would suggest some [frequency analysis](http://en.wikipedia.org/wiki/Frequency_analysis) on the letters. But for a few words I think your best bet is to compare them to an English dictionary and accept the input if half of them match.
How to check if OS is Vista in Python?
196,930
24
2008-10-13T07:35:14Z
196,931
8
2008-10-13T07:35:25Z
[ "python", "windows", "windows-vista", "wxpython", "pywin32" ]
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)? Essentially, I need a function that called will return True iff current OS is Vista: ``` >>> isWindowsVista() T...
The simplest solution I found is this one: ``` import sys def isWindowsVista(): '''Return True iff current OS is Windows Vista.''' if sys.platform != "win32": return False import win32api VER_NT_WORKSTATION = 1 version = win32api.GetVersionEx(1) if not version or len(version) < 9: ...
How to check if OS is Vista in Python?
196,930
24
2008-10-13T07:35:14Z
196,962
8
2008-10-13T07:55:47Z
[ "python", "windows", "windows-vista", "wxpython", "pywin32" ]
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)? Essentially, I need a function that called will return True iff current OS is Vista: ``` >>> isWindowsVista() T...
The solution used in Twisted, which doesn't need pywin32: ``` def isVista(): if getattr(sys, "getwindowsversion", None) is not None: return sys.getwindowsversion()[0] == 6 else: return False ``` Note that it will also match Windows Server 2008.
How to check if OS is Vista in Python?
196,930
24
2008-10-13T07:35:14Z
200,148
39
2008-10-14T06:10:23Z
[ "python", "windows", "windows-vista", "wxpython", "pywin32" ]
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)? Essentially, I need a function that called will return True iff current OS is Vista: ``` >>> isWindowsVista() T...
Python has the lovely 'platform' module to help you out. ``` >>> import platform >>> platform.win32_ver() ('XP', '5.1.2600', 'SP2', 'Multiprocessor Free') >>> platform.system() 'Windows' >>> platform.version() '5.1.2600' >>> platform.release() 'XP' ``` NOTE: As mentioned in the comments proper values may not be retur...
Can you list the keyword arguments a Python function receives?
196,960
64
2008-10-13T07:55:18Z
196,978
25
2008-10-13T08:09:15Z
[ "python", "arguments", "introspection" ]
I have a dict, which I need to pass key/values as keyword arguments.. For example.. ``` d_args = {'kw1': 'value1', 'kw2': 'value2'} example(**d_args) ``` This works fine, *but* if there are values in the d\_args dict that are not accepted by the `example` function, it obviously dies.. Say, if the example function is ...
This will print names of all passable arguments, keyword and non-keyword ones: ``` def func(one, two="value"): y = one, two return y print func.func_code.co_varnames[:func.func_code.co_argcount] ``` This is because first `co_varnames` are always parameters (next are local variables, like `y` in the example ab...
Can you list the keyword arguments a Python function receives?
196,960
64
2008-10-13T07:55:18Z
197,053
98
2008-10-13T09:02:23Z
[ "python", "arguments", "introspection" ]
I have a dict, which I need to pass key/values as keyword arguments.. For example.. ``` d_args = {'kw1': 'value1', 'kw2': 'value2'} example(**d_args) ``` This works fine, *but* if there are values in the d\_args dict that are not accepted by the `example` function, it obviously dies.. Say, if the example function is ...
A little nicer than inspecting the code object directly and working out the variables is to use the inspect module. ``` >>> import inspect >>> def func(a,b,c=42, *args, **kwargs): pass >>> inspect.getargspec(func) (['a', 'b', 'c'], 'args', 'kwargs', (42,)) ``` If you want to know if its callable with a particular set...
Docstrings for data?
197,387
20
2008-10-13T12:24:04Z
197,499
13
2008-10-13T12:55:53Z
[ "python", "docstring" ]
Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion? ``` class MyClass(object): def my_function(): """This docstring works!""" return True my_list = [] """This docstring does not work!""" ```
To my knowledge, it is not possible to assign docstrings to module data members. [PEP 224](http://www.python.org/dev/peps/pep-0224/) suggests this feature, but the PEP was rejected. I suggest you document the data members of a module in the module's docstring: ``` # module.py: """About the module. module.data: cont...
Docstrings for data?
197,387
20
2008-10-13T12:24:04Z
197,566
9
2008-10-13T13:23:42Z
[ "python", "docstring" ]
Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion? ``` class MyClass(object): def my_function(): """This docstring works!""" return True my_list = [] """This docstring does not work!""" ```
It **is** possible to make documentation of module's data, with use of [epydoc](http://epydoc.sourceforge.net/) syntax. Epydoc is one of the most frequently used documentation tools for Python. The syntax for documenting is `#:` above the variable initialization line, like this: ``` # module.py: #: Very important da...
Docstrings for data?
197,387
20
2008-10-13T12:24:04Z
199,179
10
2008-10-13T22:08:20Z
[ "python", "docstring" ]
Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion? ``` class MyClass(object): def my_function(): """This docstring works!""" return True my_list = [] """This docstring does not work!""" ```
As codeape explains, it's not possible to document general data members. However, it *is* possible to document `property` data members: ``` class Foo: def get_foo(self): ... def set_foo(self, val): ... def del_foo(self): ... foo = property(get_foo, set_foo, del_foo, '''Doc string here''') ``` This will gi...
Dealing with a string containing multiple character encodings
197,759
9
2008-10-13T14:26:10Z
197,990
7
2008-10-13T15:29:10Z
[ "python", "string", "unicode", "encoding" ]
I'm not exactly sure how to ask this question really, and I'm no where close to finding an answer, so I hope someone can help me. I'm writing a Python app that connects to a remote host and receives back byte data, which I unpack using Python's built-in struct module. My problem is with the strings, as they include mu...
Here's a relatively simple example of how do it... ``` # -*- coding: utf-8 -*- import re # Test Data ENCODING_RAW_DATA = ( ('latin_1', 'L', u'Hello'), # Latin 1 ('iso8859_2', 'E', u'dobrý večer'), # Central Europe ('iso8859_9', 'T', u'İyi akşamlar'), # Turkish ('iso8859_13', 'B', u'Į...
Can I pickle a python dictionary into a sqlite3 text field?
198,692
25
2008-10-13T19:11:13Z
198,748
13
2008-10-13T19:31:36Z
[ "python", "sqlite", "pickle" ]
Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)
If you want to store a pickled object, you'll need to use a blob, since it is binary data. However, you can, say, base64 encode the pickled object to get a string that can be stored in a text field. Generally, though, doing this sort of thing is indicative of bad design, since you're storing opaque data you lose the a...
Can I pickle a python dictionary into a sqlite3 text field?
198,692
25
2008-10-13T19:11:13Z
2,340,858
35
2010-02-26T10:23:14Z
[ "python", "sqlite", "pickle" ]
Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)
I needed to achieve the same thing too. I turns out it caused me quite a headache before I finally figured out, [thanks to this post](http://coding.derkeiler.com/Archive/Python/comp.lang.python/2008-12/msg00352.html), how to actually make it work in a binary format. ### To insert/update: ``` pdata = cPickle.dumps(da...
I'm looking for a pythonic way to insert a space before capital letters
199,059
8
2008-10-13T21:16:40Z
199,075
16
2008-10-13T21:20:55Z
[ "python", "regex", "text-files" ]
I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word". My limited regex experience just stalled out on me - can someone think of a decent regex to d...
You could try: ``` >>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord") 'Word Word Word' ```
I'm looking for a pythonic way to insert a space before capital letters
199,059
8
2008-10-13T21:16:40Z
199,120
22
2008-10-13T21:37:39Z
[ "python", "regex", "text-files" ]
I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word". My limited regex experience just stalled out on me - can someone think of a decent regex to d...
If there are consecutive capitals, then Gregs result could not be what you look for, since the \w consumes the caracter in front of the captial letter to be replaced. ``` >>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWWWWWWWord") 'Word Word WW WW WW Word' ``` A look-behind would solve this: ``` >>> re.sub(r"(?<=\w)(...
How can I port a legacy Java/J2EE website to a modern scripting language (PHP,Python/Django, etc)?
199,556
4
2008-10-14T00:23:28Z
199,607
7
2008-10-14T00:45:59Z
[ "java", "php", "python", "django", "java-ee" ]
I want to move a legacy Java web application (J2EE) to a scripting language - any scripting language - in order to improve programming efficiency. What is the easiest way to do this? Are there any automated tools that can convert the bulk of the business logic?
If you already have a large amount of business logic implemented in Java, then I see two possibilities for you. The first is to use a high level language that runs within the JVM and has a web framework, such as [Groovy](http://groovy.codehaus.org/)/[Grails](http://grails.org/) or [JRuby](http://jruby.codehaus.org/) a...
How can I port a legacy Java/J2EE website to a modern scripting language (PHP,Python/Django, etc)?
199,556
4
2008-10-14T00:23:28Z
199,736
11
2008-10-14T01:43:21Z
[ "java", "php", "python", "django", "java-ee" ]
I want to move a legacy Java web application (J2EE) to a scripting language - any scripting language - in order to improve programming efficiency. What is the easiest way to do this? Are there any automated tools that can convert the bulk of the business logic?
Here's what you have to do. First, be sure you can walk before you run. Build something simple, possibly tangentially related to your main project. **DO NOT** build a piece of the final project and hope it will "evolve" into the final project. This never works out well. Why? You'll make dumb mistakes. But you can't d...
Get last answer
200,020
87
2008-10-14T04:31:49Z
200,027
130
2008-10-14T04:35:08Z
[ "python" ]
In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like `Ans` or `%` to retrieve the last computed value. Is there a similar facility in the Python shell?
Underscore. ``` >>> 5+5 10 >>> _ 10 >>> _ + 5 15 >>> _ 15 ```
Get last answer
200,020
87
2008-10-14T04:31:49Z
200,045
41
2008-10-14T04:53:38Z
[ "python" ]
In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like `Ans` or `%` to retrieve the last computed value. Is there a similar facility in the Python shell?
Just for the record, ipython takes this one step further and you can access every result with \_ and its numeric value ``` In [1]: 10 Out[1]: 10 In [2]: 32 Out[2]: 32 In [3]: _ Out[3]: 32 In [4]: _1 Out[4]: 10 In [5]: _2 Out[5]: 32 In [6]: _1 + _2 Out[6]: 42 In [7]: _6 Out[7]: 42 ``` And it is possible to edit ...
How do I remove a cookie that I've set on someone's computer?
200,250
5
2008-10-14T07:27:21Z
200,265
7
2008-10-14T07:35:43Z
[ "python", "apache", "http", "cookies" ]
I've got a web system where users log in, and it stores a cookie of their session. When they log in as someone else or log out I want to remove that original cookie that I stored. What's the best way to do that? I'm using Python and Apache, though I suppose the answer will remain the same for most languages.
Set the cookie again, as if you hadn't set it the first time, but specify an expiration date that is in the past.
Store simple user settings in Python
200,599
7
2008-10-14T10:04:46Z
200,611
7
2008-10-14T10:10:11Z
[ "python", "database", "website", "settings" ]
I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue. The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the u...
Using [cPickle](http://www.python.org/doc/2.5.2/lib/module-cPickle.html) on the dictionary would be my choice. Dictionaries are a natural fit for these kind of data, so given your requirements I see no reason not to use them. That, unless you are thinking about reading them from non-python applications, in which case y...
Store simple user settings in Python
200,599
7
2008-10-14T10:04:46Z
202,988
8
2008-10-14T21:50:29Z
[ "python", "database", "website", "settings" ]
I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue. The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the u...
I would use the [ConfigParser](http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html) module, which produces some pretty readable and user-editable output for your example: ``` [bob] colour_scheme: blue british: yes [joe] color_scheme: that's 'color', silly! british: no ``` The following code would produce the...
How can I unpack binary hex formatted data in Python?
200,738
5
2008-10-14T11:08:07Z
200,761
8
2008-10-14T11:17:11Z
[ "php", "python", "binary", "hex" ]
Using the PHP [pack()](http://www.php.net/pack) function, I have converted a string into a binary hex representation: ``` $string = md5(time); // 32 character length $packed = pack('H*', $string); ``` The H\* formatting means "Hex string, high nibble first". To unpack this in PHP, I would simply use the [unpack()](h...
In Python you use the [struct](http://www.python.org/doc/2.5.2/lib/module-struct.html) module for this. ``` >>> from struct import * >>> pack('hhl', 1, 2, 3) '\x00\x01\x00\x02\x00\x00\x00\x03' >>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03') (1, 2, 3) >>> calcsize('hhl') 8 ``` HTH
How can I unpack binary hex formatted data in Python?
200,738
5
2008-10-14T11:08:07Z
200,861
10
2008-10-14T11:59:32Z
[ "php", "python", "binary", "hex" ]
Using the PHP [pack()](http://www.php.net/pack) function, I have converted a string into a binary hex representation: ``` $string = md5(time); // 32 character length $packed = pack('H*', $string); ``` The H\* formatting means "Hex string, high nibble first". To unpack this in PHP, I would simply use the [unpack()](h...
There's no corresponding "hex nibble" code for struct.pack, so you'll either need to manually pack into bytes first, like: ``` hex_string = 'abcdef12' hexdigits = [int(x, 16) for x in hex_string] data = ''.join(struct.pack('B', (high <<4) + low) for high, low in zip(hexdigits[::2], hexdigits[1::2])) `...
How can I unpack binary hex formatted data in Python?
200,738
5
2008-10-14T11:08:07Z
201,325
10
2008-10-14T14:15:26Z
[ "php", "python", "binary", "hex" ]
Using the PHP [pack()](http://www.php.net/pack) function, I have converted a string into a binary hex representation: ``` $string = md5(time); // 32 character length $packed = pack('H*', $string); ``` The H\* formatting means "Hex string, high nibble first". To unpack this in PHP, I would simply use the [unpack()](h...
There's an easy way to do this with the `binascii` module: ``` >>> import binascii >>> print binascii.hexlify("ABCZ") '4142435a' ``` Unless I'm misunderstanding something about the nibble ordering (high-nibble first is the default), that should be perfectly sufficient! Furthermore, Python's `hashlib.md5` objects hav...
Shortest Sudoku Solver in Python - How does it work?
201,461
70
2008-10-14T14:46:15Z
201,550
8
2008-10-14T15:05:37Z
[ "python", "algorithm" ]
I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this: ``` def r(a):i=a.find('0');~i or exit(a);[m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18] from sys import*;r(argv[1]) ``` M...
unobfuscating it: ``` def r(a): i = a.find('0') # returns -1 on fail, index otherwise ~i or exit(a) # ~(-1) == 0, anthing else is not 0 # thus: if i == -1: exit(a) inner_lexp = [ (i-j)%9*(i/9 ^ j/9)*(i/27 ^ j/27 | i%9/3 ^ j%9/3) or a[j] for j in range(81)] # r appears...
Shortest Sudoku Solver in Python - How does it work?
201,461
70
2008-10-14T14:46:15Z
201,771
205
2008-10-14T16:00:21Z
[ "python", "algorithm" ]
I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this: ``` def r(a):i=a.find('0');~i or exit(a);[m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18] from sys import*;r(argv[1]) ``` M...
Well, you can make things a little easier by fixing up the syntax: ``` def r(a): i = a.find('0') ~i or exit(a) [m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)] or r(a[:i]+m+a[i+1:])for m in'%d'%5**18] from sys import * r(argv[1]) ``` Cleaning up a little: ``` from sys import exit, argv...
urllib.urlopen works but urllib2.urlopen doesn't
201,515
10
2008-10-14T14:57:41Z
201,737
16
2008-10-14T15:49:47Z
[ "python", "urllib2", "urllib" ]
I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". `urllib.urlopen` will successfully read the page but `urllib2.urlopen` will not. Here's a script which demonstrates the problem (this is the actual script and not a simplifi...
Sounds like you have proxy settings defined that urllib2 is picking up on. When it tries to proxy "127.0.0.01/", the proxy gives up and returns a 504 error. From [Obscure python urllib2 proxy gotcha](http://kember.net/articles/obscure-python-urllib2-proxy-gotcha): ``` proxy_support = urllib2.ProxyHandler({}) opener =...
python name a file same as a lib
201,846
2
2008-10-14T16:17:23Z
201,891
7
2008-10-14T16:30:44Z
[ "python" ]
i have the following script ``` import getopt, sys opts, args = getopt.getopt(sys.argv[1:], "h:s") for key,value in opts: print key, "=>", value ``` if i name this getopt.py and run it doesn't work as it tries to import itself is there a way around this, so i can keep this filename but specify on import that i w...
You shouldn't name your scripts like existing modules. Especially if standard. That said, you can touch sys.path to modify the library loading order ``` ~# cat getopt.py print "HI" ~# python Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credi...
which python framework to use?
202,939
9
2008-10-14T21:35:15Z
202,941
10
2008-10-14T21:37:55Z
[ "python", "frameworks", "web-frameworks" ]
I'm looking for a framework which is appropriate for beginners (in Python and web development). I already found out about Django and web.py. I think that one of the most important things for me is good documentation. Thanks for the help, Dan
I think Django has some of the best documentation of any project I've worked on. That's the reason we chose it over Turbogears two years ago, and it's been the best technology choice we've made.
which python framework to use?
202,939
9
2008-10-14T21:35:15Z
204,778
10
2008-10-15T13:51:45Z
[ "python", "frameworks", "web-frameworks" ]
I'm looking for a framework which is appropriate for beginners (in Python and web development). I already found out about Django and web.py. I think that one of the most important things for me is good documentation. Thanks for the help, Dan
[web.py](http://webpy.org/)? It's extremely simple, and Python'y. A basic hello-world web-application is.. ``` import web urls = ( '/(.*)', 'hello' ) class hello: def GET(self, name): i = web.input(times=1) if not name: name = 'world' for c in range(int(i.times)): ...
Creating self-contained python applications
203,487
19
2008-10-15T02:00:27Z
203,514
20
2008-10-15T02:17:35Z
[ "python", "windows", "executable", "self-contained" ]
I'm trying to create a self-contained version of [pisa](http://www.htmltopdf.org/) (html to pdf converter, [latest version](http://pypi.python.org/pypi/pisa/3.0.27)), but I can't succeed due to several errors. I've tried `py2exe`, `bb-freeze` and `cxfreeze`. This has to be in windows, which makes my life a bit harder....
Check out [pyinstaller](http://www.pyinstaller.org/), it makes standalone executables (as in one .EXE file, and that's it).
Does python support multiprocessor/multicore programming?
203,912
60
2008-10-15T06:59:50Z
203,943
23
2008-10-15T07:26:44Z
[ "python", "multicore" ]
What is the difference between multiprocessor programming and multicore programming? preferably show examples in python how to write a small program for multiprogramming & multicore programming
As mentioned in another post Python 2.6 has the [multiprocessing](http://docs.python.org/library/multiprocessing.html) module, which can take advantage of multiple cores/processors (it gets around GIL by starting multiple processes transparently). It offers some primitives similar to the threading module. You'll find s...
Does python support multiprocessor/multicore programming?
203,912
60
2008-10-15T06:59:50Z
204,150
84
2008-10-15T09:24:52Z
[ "python", "multicore" ]
What is the difference between multiprocessor programming and multicore programming? preferably show examples in python how to write a small program for multiprogramming & multicore programming
There is no such thing as "multiprocessor" or "multicore" programming. The distinction between "multiprocessor" and "multicore" *computers* is probably not relevant to you as an application programmer; it has to do with subtleties of how the cores share access to memory. In order to take advantage of a multicore (or m...
How do I execute a program from python? os.system fails due to spaces in path
204,017
206
2008-10-15T08:24:28Z
204,049
209
2008-10-15T08:37:39Z
[ "python", "shellexecute" ]
I have a python script that needs to execute an external program, but for some reason fails. If I have the following script: ``` import os; os.system("C:\\Temp\\a b c\\Notepad.exe"); raw_input(); ``` Then it fails with the following error: ``` 'C:\Temp\a' is not recognized as an internal or external command, operab...
[`subprocess.call`](http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module) will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e. ``` import subprocess subprocess.call(['C:\\Temp\\a...
How do I execute a program from python? os.system fails due to spaces in path
204,017
206
2008-10-15T08:24:28Z
206,215
50
2008-10-15T20:09:37Z
[ "python", "shellexecute" ]
I have a python script that needs to execute an external program, but for some reason fails. If I have the following script: ``` import os; os.system("C:\\Temp\\a b c\\Notepad.exe"); raw_input(); ``` Then it fails with the following error: ``` 'C:\Temp\a' is not recognized as an internal or external command, operab...
Here's a different way of doing it. If you're using windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated. ``` filepath = 'textfile.txt' import os os.sta...