title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
What is the best project structure for a Python application?
193,161
<p>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?</p> <p>Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages.</p> <p>In particular:</p> <ol> <li>Where do you put the source?</li> <li>Where do you put application startup scripts?</li> <li>Where do you put the IDE project cruft?</li> <li>Where do you put the unit/acceptance tests?</li> <li>Where do you put non-Python data such as config files?</li> <li>Where do you put non-Python sources such as C++ for pyd/so binary extension modules?</li> </ol>
405
2008-10-10T21:50:34Z
193,256
<p>Non-python data is best bundled inside your Python modules using the <code>package_data</code> support in <A HREF="http://peak.telecommunity.com/DevCenter/setuptools">setuptools</A>. One thing I strongly recommend is using namespace packages to create shared namespaces which multiple projects can use -- much like the Java convention of putting packages in <code>com.yourcompany.yourproject</code> (and being able to have a shared <code>com.yourcompany.utils</code> namespace).</p> <p>Re branching and merging, if you use a good enough source control system it will handle merges even through renames; <A HREF="http://www.bazaar-vcs.org/">Bazaar</A> is particularly good at this.</p> <p>Contrary to some other answers here, I'm +1 on having a <code>src</code> directory top-level (with <code>doc</code> and <code>test</code> directories alongside). Specific conventions for documentation directory trees will vary depending on what you're using; <A HREF="http://sphinx.pocoo.org/">Sphinx</A>, for instance, has its own conventions which its quickstart tool supports.</p> <p>Please, please leverage setuptools and pkg_resources; this makes it much easier for other projects to rely on specific versions of your code (and for multiple versions to be simultaneously installed with different non-code files, if you're using <code>package_data</code>).</p>
6
2008-10-10T22:39:22Z
[ "python", "directory-structure", "project-structure" ]
What is the best project structure for a Python application?
193,161
<p>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?</p> <p>Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages.</p> <p>In particular:</p> <ol> <li>Where do you put the source?</li> <li>Where do you put application startup scripts?</li> <li>Where do you put the IDE project cruft?</li> <li>Where do you put the unit/acceptance tests?</li> <li>Where do you put non-Python data such as config files?</li> <li>Where do you put non-Python sources such as C++ for pyd/so binary extension modules?</li> </ol>
405
2008-10-10T21:50:34Z
193,280
<p>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.</p> <p>As far as extension sources, we have a Code directory under trunk that contains a directory for python and a directory for various other languages. Personally, I'm more inclined to try putting any extension code into its own repository next time around.</p> <p>With that said, I go back to my initial point: don't make too big a deal out of it. Put it somewhere that seems to work for you. If you find something that doesn't work, it can (and should) be changed.</p>
12
2008-10-10T22:57:39Z
[ "python", "directory-structure", "project-structure" ]
What is the best project structure for a Python application?
193,161
<p>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?</p> <p>Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages.</p> <p>In particular:</p> <ol> <li>Where do you put the source?</li> <li>Where do you put application startup scripts?</li> <li>Where do you put the IDE project cruft?</li> <li>Where do you put the unit/acceptance tests?</li> <li>Where do you put non-Python data such as config files?</li> <li>Where do you put non-Python sources such as C++ for pyd/so binary extension modules?</li> </ol>
405
2008-10-10T21:50:34Z
3,419,951
<p>This <a href="http://as.ynchrono.us/2007/12/filesystem-structure-of-python-project_21.html">blog post by Jean-Paul Calderone</a> is commonly given as an answer in #python on Freenode.</p> <blockquote> <h2>Filesystem structure of a Python project</h2> <p>Do:</p> <ul> <li>name the directory something related to your project. For example, if your project is named "Twisted", name the top-level directory for its source files <code>Twisted</code>. When you do releases, you should include a version number suffix: <code>Twisted-2.5</code>.</li> <li>create a directory <code>Twisted/bin</code> and put your executables there, if you have any. Don't give them a <code>.py</code> extension, even if they are Python source files. Don't put any code in them except an import of and call to a main function defined somewhere else in your projects. (Slight wrinkle: since on Windows, the interpreter is selected by the file extension, your Windows users actually do want the .py extension. So, when you package for Windows, you may want to add it. Unfortunately there's no easy distutils trick that I know of to automate this process. Considering that on POSIX the .py extension is a only a wart, whereas on Windows the lack is an actual bug, if your userbase includes Windows users, you may want to opt to just have the .py extension everywhere.)</li> <li>If your project is expressable as a single Python source file, then put it into the directory and name it something related to your project. For example, <code>Twisted/twisted.py</code>. If you need multiple source files, create a package instead (<code>Twisted/twisted/</code>, with an empty <code>Twisted/twisted/__init__.py</code>) and place your source files in it. For example, <code>Twisted/twisted/internet.py</code>.</li> <li>put your unit tests in a sub-package of your package (note - this means that the single Python source file option above was a trick - you <strong>always</strong> need at least one other file for your unit tests). For example, <code>Twisted/twisted/test/</code>. Of course, make it a package with <code>Twisted/twisted/test/__init__.py</code>. Place tests in files like <code>Twisted/twisted/test/test_internet.py</code>.</li> <li>add <code>Twisted/README</code> and <code>Twisted/setup.py</code> to explain and install your software, respectively, if you're feeling nice.</li> </ul> <p>Don't:</p> <ul> <li>put your source in a directory called <code>src</code> or <code>lib</code>. This makes it hard to run without installing.</li> <li>put your tests outside of your Python package. This makes it hard to run the tests against an installed version.</li> <li>create a package that <strong>only</strong> has a <code>__init__.py</code> and then put all your code into <code>__init__.py</code>. Just make a module instead of a package, it's simpler.</li> <li>try to come up with magical hacks to make Python able to import your module or package without having the user add the directory containing it to their import path (either via PYTHONPATH or some other mechanism). You will <strong>not</strong> correctly handle all cases and users will get angry at you when your software doesn't work in their environment.</li> </ul> </blockquote>
126
2010-08-05T23:29:58Z
[ "python", "directory-structure", "project-structure" ]
What is the best project structure for a Python application?
193,161
<p>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?</p> <p>Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages.</p> <p>In particular:</p> <ol> <li>Where do you put the source?</li> <li>Where do you put application startup scripts?</li> <li>Where do you put the IDE project cruft?</li> <li>Where do you put the unit/acceptance tests?</li> <li>Where do you put non-Python data such as config files?</li> <li>Where do you put non-Python sources such as C++ for pyd/so binary extension modules?</li> </ol>
405
2008-10-10T21:50:34Z
5,169,006
<p>It's worth reading through Python's documentation on packaging, too.</p> <p><a href="http://docs.python.org/tutorial/modules.html#packages">http://docs.python.org/tutorial/modules.html#packages</a></p> <p>Also make sure you're familiar with the rest of the information on that page.</p>
18
2011-03-02T14:37:19Z
[ "python", "directory-structure", "project-structure" ]
What is the best project structure for a Python application?
193,161
<p>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?</p> <p>Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages.</p> <p>In particular:</p> <ol> <li>Where do you put the source?</li> <li>Where do you put application startup scripts?</li> <li>Where do you put the IDE project cruft?</li> <li>Where do you put the unit/acceptance tests?</li> <li>Where do you put non-Python data such as config files?</li> <li>Where do you put non-Python sources such as C++ for pyd/so binary extension modules?</li> </ol>
405
2008-10-10T21:50:34Z
5,998,845
<p>According to Jean-Paul Calderone's <a href="http://as.ynchrono.us/2007/12/filesystem-structure-of-python-project_21.html">Filesystem structure of a Python project</a>:</p> <pre><code>Project/ |-- bin/ | |-- project | |-- project/ | |-- test/ | | |-- __init__.py | | |-- test_main.py | | | |-- __init__.py | |-- main.py | |-- setup.py |-- README </code></pre>
146
2011-05-13T23:49:13Z
[ "python", "directory-structure", "project-structure" ]
What is the best project structure for a Python application?
193,161
<p>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?</p> <p>Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages.</p> <p>In particular:</p> <ol> <li>Where do you put the source?</li> <li>Where do you put application startup scripts?</li> <li>Where do you put the IDE project cruft?</li> <li>Where do you put the unit/acceptance tests?</li> <li>Where do you put non-Python data such as config files?</li> <li>Where do you put non-Python sources such as C++ for pyd/so binary extension modules?</li> </ol>
405
2008-10-10T21:50:34Z
19,871,661
<p>Check out <a href="http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/">Open Sourcing a Python Project the Right Way</a>.</p> <p>Let me excerpt the <em>project layout</em> part of that excellent article:</p> <blockquote> <p>When setting up a project, the layout (or directory structure) is important to get right. A sensible layout means that potential contributors don't have to spend forever hunting for a piece of code; file locations are intuitive. Since we're dealing with an existing project, it means you'll probably need to move some stuff around.</p> <p>Let's start at the top. Most projects have a number of top-level files (like setup.py, README.md, requirements.txt, etc). There are then three directories that every project should have:</p> <ul> <li>A docs directory containing project documentation</li> <li>A directory named with the project's name which stores the actual Python package</li> <li>A test directory in one of two places <ul> <li>Under the package directory containing test code and resources</li> <li>As a stand-alone top level directory To get a better sense of how your files should be organized, here's a simplified snapshot of the layout for one of my projects, sandman:</li> </ul></li> </ul> </blockquote> <pre><code>$ pwd ~/code/sandman $ tree . |- LICENSE |- README.md |- TODO.md |- docs | |-- conf.py | |-- generated | |-- index.rst | |-- installation.rst | |-- modules.rst | |-- quickstart.rst | |-- sandman.rst |- requirements.txt |- sandman | |-- __init__.py | |-- exception.py | |-- model.py | |-- sandman.py | |-- test | |-- models.py | |-- test_sandman.py |- setup.py </code></pre> <blockquote> <p>As you can see, there are some top level files, a docs directory (generated is an empty directory where sphinx will put the generated documentation), a sandman directory, and a test directory under sandman.</p> </blockquote>
69
2013-11-09T02:22:39Z
[ "python", "directory-structure", "project-structure" ]
What is the best project structure for a Python application?
193,161
<p>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?</p> <p>Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages.</p> <p>In particular:</p> <ol> <li>Where do you put the source?</li> <li>Where do you put application startup scripts?</li> <li>Where do you put the IDE project cruft?</li> <li>Where do you put the unit/acceptance tests?</li> <li>Where do you put non-Python data such as config files?</li> <li>Where do you put non-Python sources such as C++ for pyd/so binary extension modules?</li> </ol>
405
2008-10-10T21:50:34Z
22,554,594
<p>Try starting the project using the <a href="https://pypi.python.org/pypi/python_boilerplate_template">python_boilerplate</a> template. It largely follows the best practices (e.g. <a href="http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/">those here</a>), but is better suited in case you find yourself willing to split your project into more than one egg at some point (and believe me, with anything but the simplest projects, you will. One common situation is where you have to use a locally-modified version of someone else's library).</p> <ul> <li><p><strong>Where do you put the source?</strong></p> <ul> <li>For decently large projects it makes sense to split the source into several eggs. Each egg would go as a separate setuptools-layout under <code>PROJECT_ROOT/src/&lt;egg_name&gt;</code>.</li> </ul></li> <li><p><strong>Where do you put application startup scripts?</strong></p> <ul> <li>The ideal option is to have application startup script registered as an <code>entry_point</code> in one of the eggs.</li> </ul></li> <li><p><strong>Where do you put the IDE project cruft?</strong></p> <ul> <li>Depends on the IDE. Many of them keep their stuff in <code>PROJECT_ROOT/.&lt;something&gt;</code> in the root of the project, and this is fine.</li> </ul></li> <li><p><strong>Where do you put the unit/acceptance tests?</strong></p> <ul> <li>Each egg has a separate set of tests, kept in its <code>PROJECT_ROOT/src/&lt;egg_name&gt;/tests</code> directory. I personally prefer to use <code>py.test</code> to run them.</li> </ul></li> <li><p><strong>Where do you put non-Python data such as config files?</strong></p> <ul> <li>It depends. There can be different types of non-Python data. <ul> <li><em>"Resources"</em>, i.e. data that must be packaged within an egg. This data goes into the corresponding egg directory, somewhere within package namespace. It can be used via <code>pkg_resources</code> package.</li> <li><em>"Config-files"</em>, i.e. non-Python files that are to be regarded as external to the project source files, but have to be initialized with some values when application starts running. During development I prefer to keep such files in <code>PROJECT_ROOT/config</code>. For deployment there can be various options. On Windows one can use <code>%APP_DATA%/&lt;app-name&gt;/config</code>, on Linux, <code>/etc/&lt;app-name&gt;</code> or <code>/opt/&lt;app-name&gt;/config</code>.</li> <li><em>Generated files</em>, i.e. files that may be created or modified by the application during execution. I would prefer to keep them in <code>PROJECT_ROOT/var</code> during development, and under <code>/var</code> during Linux deployment.</li> </ul></li> </ul></li> <li><strong>Where do you put non-Python sources such as C++ for pyd/so binary extension modules?</strong> <ul> <li>Into <code>PROJECT_ROOT/src/&lt;egg_name&gt;/native</code></li> </ul></li> </ul> <p>Documentation would typically go into <code>PROJECT_ROOT/doc</code> or <code>PROJECT_ROOT/src/&lt;egg_name&gt;/doc</code> (this depends on whether you regard some of the eggs to be a separate large projects). Some additional configuration will be in files like <code>PROJECT_ROOT/buildout.cfg</code> and <code>PROJECT_ROOT/setup.cfg</code>.</p>
11
2014-03-21T09:17:46Z
[ "python", "directory-structure", "project-structure" ]
What is the best project structure for a Python application?
193,161
<p>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?</p> <p>Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages.</p> <p>In particular:</p> <ol> <li>Where do you put the source?</li> <li>Where do you put application startup scripts?</li> <li>Where do you put the IDE project cruft?</li> <li>Where do you put the unit/acceptance tests?</li> <li>Where do you put non-Python data such as config files?</li> <li>Where do you put non-Python sources such as C++ for pyd/so binary extension modules?</li> </ol>
405
2008-10-10T21:50:34Z
30,799,616
<p>The "Python Packaging Authority" has a sampleproject:</p> <p><a href="https://github.com/pypa/sampleproject" rel="nofollow">https://github.com/pypa/sampleproject</a></p> <p>IT is a sample project that exists as an aid to the Python Packaging User Guide's Tutorial on Packaging and Distributing Projects.</p>
3
2015-06-12T09:23:59Z
[ "python", "directory-structure", "project-structure" ]
What are best practices for developing consistent libraries?
193,701
<p>I am working on developing a pair of libraries to work with a REST API. Because I need to be able to use the API in very different settings I'm currently planning to have a version in PHP (for web applications) and a second version in Python (for desktop applications, and long running processes). Are there any best practices to follow in the development of the libraries to help maintain my own sanity?</p>
3
2008-10-11T05:34:54Z
193,709
<p>Well, the obvious one would be to keep your naming consistent. Functions and classes should be named similarly (if not identically) in both implementations. This usually happens naturally whenever you implement an API separately in two different languages. The big ticket item though (at least in my book) is to follow language-specific idioms. For example, let's assume that I were implementing a REST API in two languages I'm more familiar with: Ruby and Scala. The Ruby version might have a class <code>MyCompany::Foo</code> which contains method <code>bar_baz()</code>. Conversely, the Scala version of the same API would have a class <code>com.mycompany.rest.Foo</code> with a method <code>barBaz()</code>. It's just naming conventions, but I find it goes a long way to helping your API to feel "at home" in a particular language, even when the design was created elsewhere.</p> <p>Beyond that I have only one piece of advise: document, document, document. That's easily the best way to keep your sanity when dealing with a multi-implementation API spec.</p>
0
2008-10-11T05:42:41Z
[ "php", "python", "api", "rest" ]
What are best practices for developing consistent libraries?
193,701
<p>I am working on developing a pair of libraries to work with a REST API. Because I need to be able to use the API in very different settings I'm currently planning to have a version in PHP (for web applications) and a second version in Python (for desktop applications, and long running processes). Are there any best practices to follow in the development of the libraries to help maintain my own sanity?</p>
3
2008-10-11T05:34:54Z
193,713
<p>So, the problem with developing parallel libraries in different languages is that often times different languages will have different idioms for the same task. I know this from personal experience, having ported a library from Python to PHP. Idioms aren't just naming: for example, Python has a good deal of magic you can use with getters and setters to make object properties act magical; Python has monkeypatching; Python has named parameters.</p> <p>With a port, you want to pick a "base" language, and then attempt to mimic all the idioms in the other language (not easy to do); for parallel development, not doing anything too tricky and catering to the least common denominator is preferable. Then bolt on the syntax sugar.</p>
6
2008-10-11T05:46:00Z
[ "php", "python", "api", "rest" ]
What are best practices for developing consistent libraries?
193,701
<p>I am working on developing a pair of libraries to work with a REST API. Because I need to be able to use the API in very different settings I'm currently planning to have a version in PHP (for web applications) and a second version in Python (for desktop applications, and long running processes). Are there any best practices to follow in the development of the libraries to help maintain my own sanity?</p>
3
2008-10-11T05:34:54Z
193,714
<p>'Be your own client' : I've found that the technique of writing tests first is an excellent way of ensuring an API is easy to use. Writing tests first means you will be thinking like a 'consumer' of your API rather than just an implementor. </p>
2
2008-10-11T05:46:18Z
[ "php", "python", "api", "rest" ]
What are best practices for developing consistent libraries?
193,701
<p>I am working on developing a pair of libraries to work with a REST API. Because I need to be able to use the API in very different settings I'm currently planning to have a version in PHP (for web applications) and a second version in Python (for desktop applications, and long running processes). Are there any best practices to follow in the development of the libraries to help maintain my own sanity?</p>
3
2008-10-11T05:34:54Z
193,807
<p>Try to write a common unit test suite for both. Maybe by wrapping a class in one language for calling it from the other. If you can't do it, at least make sure the two versions of the tests are equivalent.</p>
2
2008-10-11T07:28:57Z
[ "php", "python", "api", "rest" ]
What are best practices for developing consistent libraries?
193,701
<p>I am working on developing a pair of libraries to work with a REST API. Because I need to be able to use the API in very different settings I'm currently planning to have a version in PHP (for web applications) and a second version in Python (for desktop applications, and long running processes). Are there any best practices to follow in the development of the libraries to help maintain my own sanity?</p>
3
2008-10-11T05:34:54Z
389,024
<p>AFAIKT there are a lot of bridges from to scripting languages. Let's take e.g Jruby, it's Ruby + Java, then there are things to embed Ruby in Python (or the other way). Then there are examples like Etoile where the base is Objective-C but also bridges to Python and Smalltalk, another approach on wide use: Wrapping C libraries, examples are libxml2, libcurl etc etc. Maybe this could be the base. Let's say your write all for Python but do implement a bridge to PHP. So you do not have that much parrallel development. </p> <p>Or maybe it's not the worst idea to base that stuff let's say on .NET, then you suddenly have a whole bunch of languages to your disposal which in principal should be usable from every other language on the .NET platform.</p>
0
2008-12-23T14:41:44Z
[ "php", "python", "api", "rest" ]
What are best practices for developing consistent libraries?
193,701
<p>I am working on developing a pair of libraries to work with a REST API. Because I need to be able to use the API in very different settings I'm currently planning to have a version in PHP (for web applications) and a second version in Python (for desktop applications, and long running processes). Are there any best practices to follow in the development of the libraries to help maintain my own sanity?</p>
3
2008-10-11T05:34:54Z
959,080
<p>why not use python for web applications too? there are several frameworks available: django, web2py - similar to django but many say it's simpler to use, there is also TurboGears, web.py, Pylons</p> <p>along the lines of bridging - you could use interprocess communication to have PHP and python application (in daemon mode) talk to each other.</p>
0
2009-06-06T05:41:05Z
[ "php", "python", "api", "rest" ]
Microphone access in Python
193,789
<p>Can I access a users microphone in Python?</p> <p>Sorry I forgot not everyone is a mind reader: Windows at minimum XP but Vista support would be VERY good.</p>
10
2008-10-11T07:06:48Z
193,823
<p>Best way to go about it would be to use the ctypes library and use WinMM from that. mixerOpen will open a microphone device and you can read the data easily from there. Should be very straightforward.</p>
3
2008-10-11T07:47:44Z
[ "python", "windows", "microphone" ]
Microphone access in Python
193,789
<p>Can I access a users microphone in Python?</p> <p>Sorry I forgot not everyone is a mind reader: Windows at minimum XP but Vista support would be VERY good.</p>
10
2008-10-11T07:06:48Z
202,421
<p>You might try <a href="http://code.google.com/p/pygalaxy/wiki/SWMixer" rel="nofollow" title="SWMixer">SWMixer</a>.</p>
2
2008-10-14T19:07:36Z
[ "python", "windows", "microphone" ]
Microphone access in Python
193,789
<p>Can I access a users microphone in Python?</p> <p>Sorry I forgot not everyone is a mind reader: Windows at minimum XP but Vista support would be VERY good.</p>
10
2008-10-11T07:06:48Z
247,349
<p>I got the job done with <a href="http://people.csail.mit.edu/hubert/pyaudio/">pyaudio</a></p> <p>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.</p>
16
2008-10-29T15:53:36Z
[ "python", "windows", "microphone" ]
What are good rules of thumb for Python imports?
193,919
<p>I am a little confused by the multitude of ways in which you can import modules in Python. </p> <pre><code>import X import X as Y from A import B </code></pre> <p>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 at a module level or a method/function level? In the <code>__init__.py</code> or in the module code itself?</p> <p>My question is not really answered by "<a href="http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file">Python packages - import by class, not file</a>" although it is obviously related.</p>
60
2008-10-11T09:59:35Z
193,927
<p>I would normally use <code>import X</code> on module level. If you only need a single object from a module, use <code>from X import Y</code>. </p> <p>Only use <code>import X as Y</code> in case you're otherwise confronted with a name clash.</p> <p>I only use imports on function level to import stuff I need when the module is used as the main module, like:</p> <pre><code>def main(): import sys if len(sys.argv) &gt; 1: pass </code></pre> <p>HTH</p>
9
2008-10-11T10:10:13Z
[ "python", "python-import" ]
What are good rules of thumb for Python imports?
193,919
<p>I am a little confused by the multitude of ways in which you can import modules in Python. </p> <pre><code>import X import X as Y from A import B </code></pre> <p>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 at a module level or a method/function level? In the <code>__init__.py</code> or in the module code itself?</p> <p>My question is not really answered by "<a href="http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file">Python packages - import by class, not file</a>" although it is obviously related.</p>
60
2008-10-11T09:59:35Z
193,931
<p>In production code in our company, we try to follow the following rules.</p> <p>We place imports at the beginning of the file, right after the main file's docstring, e.g.:</p> <pre><code>""" Registry related functionality. """ import wx # ... </code></pre> <p>Now, if we import a class that is one of few in the imported module, we import the name directly, so that in the code we only have to use the last part, e.g.:</p> <pre><code>from RegistryController import RegistryController from ui.windows.lists import ListCtrl, DynamicListCtrl </code></pre> <p>There are modules, however, that contain dozens of classes, e.g. list of all possible exceptions. Then we import the module itself and reference to it in the code:</p> <pre><code>from main.core import Exceptions # ... raise Exceptions.FileNotFound() </code></pre> <p>We use the <code>import X as Y</code> as rarely as possible, because it makes searching for usage of a particular module or class difficult. Sometimes, however, you have to use it if you wish to import two classes that have the same name, but exist in different modules, e.g.:</p> <pre><code>from Queue import Queue from main.core.MessageQueue import Queue as MessageQueue </code></pre> <p>As a general rule, we don't do imports inside methods -- they simply make code slower and less readable. Some may find this a good way to easily resolve cyclic imports problem, but a better solution is code reorganization.</p>
52
2008-10-11T10:15:40Z
[ "python", "python-import" ]
What are good rules of thumb for Python imports?
193,919
<p>I am a little confused by the multitude of ways in which you can import modules in Python. </p> <pre><code>import X import X as Y from A import B </code></pre> <p>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 at a module level or a method/function level? In the <code>__init__.py</code> or in the module code itself?</p> <p>My question is not really answered by "<a href="http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file">Python packages - import by class, not file</a>" although it is obviously related.</p>
60
2008-10-11T09:59:35Z
193,937
<p>The <code>import X as Y</code> is useful if you have different implementations of the same module/class.</p> <p>With some nested <code>try..import..except ImportError..import</code>s you can hide the implementation from your code. See <a href="http://codespeak.net/lxml/tutorial.html" rel="nofollow">lxml etree import example</a>:</p> <pre><code>try: from lxml import etree print("running with lxml.etree") except ImportError: try: # Python 2.5 import xml.etree.cElementTree as etree print("running with cElementTree on Python 2.5+") except ImportError: try: # Python 2.5 import xml.etree.ElementTree as etree print("running with ElementTree on Python 2.5+") except ImportError: try: # normal cElementTree install import cElementTree as etree print("running with cElementTree") except ImportError: try: # normal ElementTree install import elementtree.ElementTree as etree print("running with ElementTree") except ImportError: print("Failed to import ElementTree from any known place") </code></pre>
0
2008-10-11T10:23:48Z
[ "python", "python-import" ]
What are good rules of thumb for Python imports?
193,919
<p>I am a little confused by the multitude of ways in which you can import modules in Python. </p> <pre><code>import X import X as Y from A import B </code></pre> <p>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 at a module level or a method/function level? In the <code>__init__.py</code> or in the module code itself?</p> <p>My question is not really answered by "<a href="http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file">Python packages - import by class, not file</a>" although it is obviously related.</p>
60
2008-10-11T09:59:35Z
193,979
<p>I generally try to use the regular <code>import modulename</code>, unless the module name is long, or used often..</p> <p>For example, I would do..</p> <pre><code>from BeautifulSoup import BeautifulStoneSoup as BSS </code></pre> <p>..so I can do <code>soup = BSS(html)</code> instead of <code>BeautifulSoup.BeautifulStoneSoup(html)</code></p> <p>Or..</p> <pre><code>from xmpp import XmppClientBase </code></pre> <p>..instead of importing the entire of xmpp when I only use the XmppClientBase</p> <p>Using <code>import x as y</code> is handy if you want to import either very long method names , or to prevent clobbering an existing import/variable/class/method (something you should try to avoid completely, but it's not always possible)</p> <p>Say I want to run a main() function from another script, but I already have a main() function..</p> <pre><code>from my_other_module import main as other_module_main </code></pre> <p>..wouldn't replace my <code>main</code> function with my_other_module's <code>main</code></p> <p>Oh, one thing - don't do <code>from x import *</code> - it makes your code very hard to understand, as you cannot easily see where a method came from (<code>from x import *; from y import *; my_func()</code> - where is my_func defined?)</p> <p>In all cases, you <em>could</em> just do <code>import modulename</code> and then do <code>modulename.subthing1.subthing2.method("test")</code>...</p> <p>The <code>from x import y as z</code> stuff is purely for convenience - use it whenever it'll make your code easier to read or write!</p>
2
2008-10-11T11:27:35Z
[ "python", "python-import" ]
What are good rules of thumb for Python imports?
193,919
<p>I am a little confused by the multitude of ways in which you can import modules in Python. </p> <pre><code>import X import X as Y from A import B </code></pre> <p>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 at a module level or a method/function level? In the <code>__init__.py</code> or in the module code itself?</p> <p>My question is not really answered by "<a href="http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file">Python packages - import by class, not file</a>" although it is obviously related.</p>
60
2008-10-11T09:59:35Z
194,085
<p>Others have covered most of the ground here but I just wanted to add one case where I will use <code>import X as Y</code> (temporarily), when I'm trying out a new version of a class or module.</p> <p>So if we were migrating to a new implementation of a module, but didn't want to cut the code base over all at one time, we might write a <code>xyz_new</code> module and do this in the source files that we had migrated:</p> <pre><code>import xyz_new as xyz </code></pre> <p>Then, once we cut over the entire code base, we'd just replace the <code>xyz</code> module with <code>xyz_new</code> and change all of the imports back to</p> <pre><code>import xyz </code></pre>
3
2008-10-11T13:49:34Z
[ "python", "python-import" ]
What are good rules of thumb for Python imports?
193,919
<p>I am a little confused by the multitude of ways in which you can import modules in Python. </p> <pre><code>import X import X as Y from A import B </code></pre> <p>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 at a module level or a method/function level? In the <code>__init__.py</code> or in the module code itself?</p> <p>My question is not really answered by "<a href="http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file">Python packages - import by class, not file</a>" although it is obviously related.</p>
60
2008-10-11T09:59:35Z
194,096
<p>DON'T do this:</p> <pre><code>from X import * </code></pre> <p>unless you are absolutely sure that you will use each and every thing in that module. And even then, you should probably reconsider using a different approach.</p> <p>Other than that, it's just a matter of style.</p> <pre><code>from X import Y </code></pre> <p>is good and saves you lots of typing. I tend to use that when I'm using something in it fairly frequently But if you're importing a lot from that module, you could end up with an import statement that looks like this:</p> <pre><code>from X import A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P </code></pre> <p>You get the idea. That's when imports like</p> <pre><code>import X </code></pre> <p>become useful. Either that or if I'm not really using anything in X very frequently.</p>
3
2008-10-11T14:00:13Z
[ "python", "python-import" ]
What are good rules of thumb for Python imports?
193,919
<p>I am a little confused by the multitude of ways in which you can import modules in Python. </p> <pre><code>import X import X as Y from A import B </code></pre> <p>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 at a module level or a method/function level? In the <code>__init__.py</code> or in the module code itself?</p> <p>My question is not really answered by "<a href="http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file">Python packages - import by class, not file</a>" although it is obviously related.</p>
60
2008-10-11T09:59:35Z
194,422
<p>Let me just paste a part of conversation on django-dev mailing list started by Guido van Rossum:</p> <blockquote> <p>[...] 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, so recalling where a particular thing comes from is much easier if it is prefixed with a module name. Often multiple modules happen to define things with the same name -- so a reader of the code doesn't have to go back to the top of the file to see from which module a given name is imported. </p> </blockquote> <p><strong>Source:</strong> <a href="http://groups.google.com/group/django-developers/browse_thread/thread/78975372cdfb7d1a">http://groups.google.com/group/django-developers/browse_thread/thread/78975372cdfb7d1a</a></p> <p>1: <a href="http://code.google.com/p/soc/wiki/PythonStyleGuide#Module_and_package_imports">http://code.google.com/p/soc/wiki/PythonStyleGuide#Module_and_package_imports</a></p>
30
2008-10-11T18:34:42Z
[ "python", "python-import" ]
What are good rules of thumb for Python imports?
193,919
<p>I am a little confused by the multitude of ways in which you can import modules in Python. </p> <pre><code>import X import X as Y from A import B </code></pre> <p>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 at a module level or a method/function level? In the <code>__init__.py</code> or in the module code itself?</p> <p>My question is not really answered by "<a href="http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file">Python packages - import by class, not file</a>" although it is obviously related.</p>
60
2008-10-11T09:59:35Z
204,340
<p>When you have a well-written library, which is sometimes case in python, you ought just import it and use it as it. Well-written library tends to take life and language of its own, resulting in pleasant-to-read -code, where you rarely reference the library. When a library is well-written, you ought not need renaming or anything else too often.</p> <pre><code>import gat node = gat.Node() child = node.children() </code></pre> <p>Sometimes it's not possible to write it this way, or then you want to lift down things from library you imported.</p> <pre><code>from gat import Node, SubNode node = Node() child = SubNode(node) </code></pre> <p>Sometimes you do this for lot of things, if your import string overflows 80 columns, It's good idea to do this:</p> <pre><code>from gat import ( Node, SubNode, TopNode, SuperNode, CoolNode, PowerNode, UpNode ) </code></pre> <p>The best strategy is to keep all of these imports on the top of the file. Preferrably ordered alphabetically, import -statements first, then from import -statements.</p> <p>Now I tell you why this is the best convention.</p> <p>Python could perfectly have had an automatic import, which'd look from the main imports for the value when it can't be found from global namespace. But this is not a good idea. I explain shortly why. Aside it being more complicated to implement than simple import, programmers wouldn't be so much thinking about the depedencies and finding out from where you imported things ought be done some other way than just looking into imports.</p> <p>Need to find out depedencies is one reason why people hate "from ... import *". Some bad examples where you need to do this exist though, for example opengl -wrappings.</p> <p>So the import definitions are actually valuable as defining the depedencies of the program. It is the way how you should exploit them. From them you can quickly just check where some weird function is imported from.</p>
1
2008-10-15T11:07:41Z
[ "python", "python-import" ]
What are good rules of thumb for Python imports?
193,919
<p>I am a little confused by the multitude of ways in which you can import modules in Python. </p> <pre><code>import X import X as Y from A import B </code></pre> <p>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 at a module level or a method/function level? In the <code>__init__.py</code> or in the module code itself?</p> <p>My question is not really answered by "<a href="http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file">Python packages - import by class, not file</a>" although it is obviously related.</p>
60
2008-10-11T09:59:35Z
2,236,989
<p>I'm with Jason in the fact of not using</p> <pre><code>from X import * </code></pre> <p>But in my case (i'm not an expert programmer, so my code does not meet the coding style too well) I usually do in my programs a file with all the constants like program version, authors, error messages and all that stuff, so the file are just definitions, then I make the import</p> <pre><code>from const import * </code></pre> <p>That saves me a lot of time. But it's the only file that has that import, and it's because all inside that file are just variable declarations.</p> <p>Doing that kind of import in a file with classes and definitions might be useful, but when you have to read that code you spend lots of time locating functions and classes.</p>
0
2010-02-10T13:13:55Z
[ "python", "python-import" ]
What are good rules of thumb for Python imports?
193,919
<p>I am a little confused by the multitude of ways in which you can import modules in Python. </p> <pre><code>import X import X as Y from A import B </code></pre> <p>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 at a module level or a method/function level? In the <code>__init__.py</code> or in the module code itself?</p> <p>My question is not really answered by "<a href="http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file">Python packages - import by class, not file</a>" although it is obviously related.</p>
60
2008-10-11T09:59:35Z
16,070,330
<p>Someone above said that</p> <pre><code>from X import A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P </code></pre> <p>is equivalent to</p> <pre><code>import X </code></pre> <p><code>import X</code> allows direct modifications to A-P, while <code>from X import ...</code> creates copies of A-P. For <code>from X import A..P</code> you do not get updates to variables if they are modified. If you modify them, you only modify your copy, but X does know about your modifications.</p> <p>If A-P are functions, you won't know the difference.</p>
4
2013-04-17T21:10:34Z
[ "python", "python-import" ]
Recommended data format for describing the rules of chess
194,289
<p>I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky since some of the chess rules (e.g. King Castling, en passent, draws based on 3 or more repeated moves) are based not only on the board layout but also on the history of moves.</p> <p>I would prefer the format to be:</p> <ul> <li>textual</li> <li>human readable</li> <li>based on a standard (e.g. YAML, XML)</li> <li>easily parsable in a variety of languages</li> </ul> <p>But I am willing to sacrifice any of these for a suitable solution.</p> <p>My main question is: How can I build algorithms of such a complexity that operate on such complex state from a data format?</p> <p>A followup queston is: Can you provide an example of a similar problem solved in a similar manner that can act as a starting point?</p> <p><strong>Edit:</strong> In response to a request for clarity -- consider that I will have a server written in Python, one client written in C# and another client written in Java. I would like to avoid specifying the rules (e.g. for allowable piece movement, circumstances for check, etc.) in each place. I would prefer to specify these rules once in a language independant manner.</p>
8
2008-10-11T16:34:31Z
194,306
<p>Let's think. We're describing objects (locations and pieces) with states and behaviors. We need to note a current state and an ever-changing set of allowed state changes from a current state.</p> <p>This is programming. You don't want some "meta-language" that you can then parse in a regular programming language. Just use a programming language.</p> <p>Start with ordinary class definitions in an ordinary language. Get it all to work. Then, those class definitions are the definition of chess. </p> <p>With only miniscule exceptions, <strong>all</strong> programming languages are</p> <ul> <li>Textual</li> <li>Human readable</li> <li>Reasonably standardized</li> <li>Easily parsed by their respective compilers or interpreters.</li> </ul> <p>Just pick a language, and you're done. Since it will take a while to work out the nuances, you'll probably be happier with a dynamic language like Python or Ruby than with a static language like Java or C#.</p> <p>If you want portability. Pick a portable language. If you want the language embedded in a "larger" application, then, pick the language for your "larger" application.</p> <p><hr /></p> <p>Since the original requirements were incomplete, a secondary minor issue is how to have code that runs in conjunction with multiple clients.</p> <ol> <li><p>Don't have clients in multiple languages. Pick one. Java, for example, and stick with it. </p></li> <li><p>If you must have clients in multiple languages, then you need a language you can embed in all three language run-time environments. You have two choices.</p> <ul> <li><p>Embed an interpreter. For example Python, Tcl and JavaScript are lightweight interpreters that you can call from C or C# programs. This approach works for browsers, it can work for you. Java, via JNI can make use of this, also. There are BPEL rules engines that you can try this with.</p></li> <li><p>Spawn an interpreter as a separate subprocess. Open a named pipe or socket or something between your app and your spawned interpreter. Your Java and C# clients can talk with a Python subprocess. Your Python server can simply use this code.</p></li> </ul></li> </ol>
4
2008-10-11T16:48:28Z
[ "c#", "java", "python", "chess", "dataformat" ]
Recommended data format for describing the rules of chess
194,289
<p>I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky since some of the chess rules (e.g. King Castling, en passent, draws based on 3 or more repeated moves) are based not only on the board layout but also on the history of moves.</p> <p>I would prefer the format to be:</p> <ul> <li>textual</li> <li>human readable</li> <li>based on a standard (e.g. YAML, XML)</li> <li>easily parsable in a variety of languages</li> </ul> <p>But I am willing to sacrifice any of these for a suitable solution.</p> <p>My main question is: How can I build algorithms of such a complexity that operate on such complex state from a data format?</p> <p>A followup queston is: Can you provide an example of a similar problem solved in a similar manner that can act as a starting point?</p> <p><strong>Edit:</strong> In response to a request for clarity -- consider that I will have a server written in Python, one client written in C# and another client written in Java. I would like to avoid specifying the rules (e.g. for allowable piece movement, circumstances for check, etc.) in each place. I would prefer to specify these rules once in a language independant manner.</p>
8
2008-10-11T16:34:31Z
194,318
<p><strong>Edit:</strong> Overly wordy answer deleted.</p> <p>The short answer is, write the rules in Python. Use Iron Python to interface that to the C# client, and Jython for the Java client.</p>
2
2008-10-11T16:57:04Z
[ "c#", "java", "python", "chess", "dataformat" ]
Recommended data format for describing the rules of chess
194,289
<p>I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky since some of the chess rules (e.g. King Castling, en passent, draws based on 3 or more repeated moves) are based not only on the board layout but also on the history of moves.</p> <p>I would prefer the format to be:</p> <ul> <li>textual</li> <li>human readable</li> <li>based on a standard (e.g. YAML, XML)</li> <li>easily parsable in a variety of languages</li> </ul> <p>But I am willing to sacrifice any of these for a suitable solution.</p> <p>My main question is: How can I build algorithms of such a complexity that operate on such complex state from a data format?</p> <p>A followup queston is: Can you provide an example of a similar problem solved in a similar manner that can act as a starting point?</p> <p><strong>Edit:</strong> In response to a request for clarity -- consider that I will have a server written in Python, one client written in C# and another client written in Java. I would like to avoid specifying the rules (e.g. for allowable piece movement, circumstances for check, etc.) in each place. I would prefer to specify these rules once in a language independant manner.</p>
8
2008-10-11T16:34:31Z
194,321
<p>This is answering the followup question :-)</p> <p>I can point out that one of the most popular chess servers around documents its protocol <a href="ftp://ftp.chessclub.com/pub/icc/formats/formats.txt" rel="nofollow">here</a> (Warning, FTP link, and does not support passive FTP), but <strong>only to write interfaces to it</strong>, not for any other purpose. You could start writing a client for this server as a learning experience.</p> <p>One thing that's relevant is that good chess servers offer many more features than just a move relay.</p> <p>That said, there is a more basic protocol used to interface to chess engines, documented <a href="http://www.tim-mann.org/xboard/engine-intf.html" rel="nofollow">here</a>.</p> <p>Oh, and by the way: <a href="http://en.wikipedia.org/wiki/Board_representation_%28chess%29" rel="nofollow">Board Representation at Wikipedia</a></p> <p>Anything beyond board representation belongs to the program itself, as many have already pointed out.</p>
2
2008-10-11T17:00:56Z
[ "c#", "java", "python", "chess", "dataformat" ]
Recommended data format for describing the rules of chess
194,289
<p>I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky since some of the chess rules (e.g. King Castling, en passent, draws based on 3 or more repeated moves) are based not only on the board layout but also on the history of moves.</p> <p>I would prefer the format to be:</p> <ul> <li>textual</li> <li>human readable</li> <li>based on a standard (e.g. YAML, XML)</li> <li>easily parsable in a variety of languages</li> </ul> <p>But I am willing to sacrifice any of these for a suitable solution.</p> <p>My main question is: How can I build algorithms of such a complexity that operate on such complex state from a data format?</p> <p>A followup queston is: Can you provide an example of a similar problem solved in a similar manner that can act as a starting point?</p> <p><strong>Edit:</strong> In response to a request for clarity -- consider that I will have a server written in Python, one client written in C# and another client written in Java. I would like to avoid specifying the rules (e.g. for allowable piece movement, circumstances for check, etc.) in each place. I would prefer to specify these rules once in a language independant manner.</p>
8
2008-10-11T16:34:31Z
194,326
<p>There's already a widely used format specific to chess called <a href="http://en.wikipedia.org/wiki/Portable_Game_Notation" rel="nofollow">Portable Game Notation</a>. There's also <a href="http://www.red-bean.com/sgf/" rel="nofollow">Smart Game Format</a>, which is adaptable to many different games.</p>
2
2008-10-11T17:09:30Z
[ "c#", "java", "python", "chess", "dataformat" ]
Recommended data format for describing the rules of chess
194,289
<p>I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky since some of the chess rules (e.g. King Castling, en passent, draws based on 3 or more repeated moves) are based not only on the board layout but also on the history of moves.</p> <p>I would prefer the format to be:</p> <ul> <li>textual</li> <li>human readable</li> <li>based on a standard (e.g. YAML, XML)</li> <li>easily parsable in a variety of languages</li> </ul> <p>But I am willing to sacrifice any of these for a suitable solution.</p> <p>My main question is: How can I build algorithms of such a complexity that operate on such complex state from a data format?</p> <p>A followup queston is: Can you provide an example of a similar problem solved in a similar manner that can act as a starting point?</p> <p><strong>Edit:</strong> In response to a request for clarity -- consider that I will have a server written in Python, one client written in C# and another client written in Java. I would like to avoid specifying the rules (e.g. for allowable piece movement, circumstances for check, etc.) in each place. I would prefer to specify these rules once in a language independant manner.</p>
8
2008-10-11T16:34:31Z
194,332
<p>I would suggest Prolog for describing the rules. </p>
2
2008-10-11T17:14:31Z
[ "c#", "java", "python", "chess", "dataformat" ]
Recommended data format for describing the rules of chess
194,289
<p>I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky since some of the chess rules (e.g. King Castling, en passent, draws based on 3 or more repeated moves) are based not only on the board layout but also on the history of moves.</p> <p>I would prefer the format to be:</p> <ul> <li>textual</li> <li>human readable</li> <li>based on a standard (e.g. YAML, XML)</li> <li>easily parsable in a variety of languages</li> </ul> <p>But I am willing to sacrifice any of these for a suitable solution.</p> <p>My main question is: How can I build algorithms of such a complexity that operate on such complex state from a data format?</p> <p>A followup queston is: Can you provide an example of a similar problem solved in a similar manner that can act as a starting point?</p> <p><strong>Edit:</strong> In response to a request for clarity -- consider that I will have a server written in Python, one client written in C# and another client written in Java. I would like to avoid specifying the rules (e.g. for allowable piece movement, circumstances for check, etc.) in each place. I would prefer to specify these rules once in a language independant manner.</p>
8
2008-10-11T16:34:31Z
194,417
<p>Drools has a modern human readable rules implementation -- https://www.jboss.org/drools/. They have a way users can enter their rules in Excel. A lot more users can understand what is in Excel than in other tools.</p>
0
2008-10-11T18:31:16Z
[ "c#", "java", "python", "chess", "dataformat" ]
Recommended data format for describing the rules of chess
194,289
<p>I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky since some of the chess rules (e.g. King Castling, en passent, draws based on 3 or more repeated moves) are based not only on the board layout but also on the history of moves.</p> <p>I would prefer the format to be:</p> <ul> <li>textual</li> <li>human readable</li> <li>based on a standard (e.g. YAML, XML)</li> <li>easily parsable in a variety of languages</li> </ul> <p>But I am willing to sacrifice any of these for a suitable solution.</p> <p>My main question is: How can I build algorithms of such a complexity that operate on such complex state from a data format?</p> <p>A followup queston is: Can you provide an example of a similar problem solved in a similar manner that can act as a starting point?</p> <p><strong>Edit:</strong> In response to a request for clarity -- consider that I will have a server written in Python, one client written in C# and another client written in Java. I would like to avoid specifying the rules (e.g. for allowable piece movement, circumstances for check, etc.) in each place. I would prefer to specify these rules once in a language independant manner.</p>
8
2008-10-11T16:34:31Z
199,233
<p>What I've gathered from the responses so far:</p> <p><strong>For chess board data representations:</strong></p> <p>See the Wikipedia article on [chess board representations](http://en.wikipedia.org/wiki/Board_representation_(chess)).</p> <p><strong>For chess move data representations:</strong></p> <p>See the Wikipedia articles on <a href="http://en.wikipedia.org/wiki/Portable_Game_Notation" rel="nofollow">Portable Game Notation</a> and <a href="http://en.wikipedia.org/wiki/Algebraic_chess_notation" rel="nofollow">Algebraic Chess Notation</a></p> <p><strong>For chess rules representations:</strong></p> <p>This must be done using a programming language. If one wants to reduce the amount of code written in the case where the rules will be implemented in more than one language then there are a few options</p> <ol> <li>Use a language where an embedable interpreter exists for the target languages (e.g. Lua, Python).</li> <li>Use a Virtual Machine that the common languages can compile to (e.g. IronPython for C#, JPython for Java).</li> <li>Use a background daemon or sub-process for the rules with which the target languages can communicate.</li> <li>Reimplement the rules algorithms in each target language.</li> </ol> <p>Although I would have liked a declarative syntax that could have been interpreted by mutliple languages to enforce the rules of chess my research has lead me to no likely candidate. I have a suspicion that <a href="http://en.wikipedia.org/wiki/Constraint_programming" rel="nofollow">Constraint Based Programming</a> may be a possible route given that solvers exist for many languages but I am not sure they would truly fulfill this requirement. Thanks for all the attention and perhaps in the future an answer will appear.</p>
2
2008-10-13T22:22:23Z
[ "c#", "java", "python", "chess", "dataformat" ]
Recommended data format for describing the rules of chess
194,289
<p>I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky since some of the chess rules (e.g. King Castling, en passent, draws based on 3 or more repeated moves) are based not only on the board layout but also on the history of moves.</p> <p>I would prefer the format to be:</p> <ul> <li>textual</li> <li>human readable</li> <li>based on a standard (e.g. YAML, XML)</li> <li>easily parsable in a variety of languages</li> </ul> <p>But I am willing to sacrifice any of these for a suitable solution.</p> <p>My main question is: How can I build algorithms of such a complexity that operate on such complex state from a data format?</p> <p>A followup queston is: Can you provide an example of a similar problem solved in a similar manner that can act as a starting point?</p> <p><strong>Edit:</strong> In response to a request for clarity -- consider that I will have a server written in Python, one client written in C# and another client written in Java. I would like to avoid specifying the rules (e.g. for allowable piece movement, circumstances for check, etc.) in each place. I would prefer to specify these rules once in a language independant manner.</p>
8
2008-10-11T16:34:31Z
217,035
<p>To represent the current state of a board (including castling possibilities etc) you can use <a href="http://en.wikipedia.org/wiki/Forsyth-Edwards_Notation" rel="nofollow">Forsyth-Edwards Notation</a>, which will give you a short ascii representation. e.g.:</p> <pre> rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 </pre> <p>Would be the opening board position.</p> <p>Then to represent a particular move from a position you could use <a href="http://en.wikipedia.org/wiki/ICCF_numeric_notation" rel="nofollow">numeric move notation</a> (as used in correspondence chess), which give you a short (4-5 digits) representation of a move on the board.</p> <p>As to represent the rules - I'd love to know myself. Currently the rules for my chess engine are just written in Python and probably aren't as declarative as I'd like.</p>
0
2008-10-19T21:53:34Z
[ "c#", "java", "python", "chess", "dataformat" ]
Recommended data format for describing the rules of chess
194,289
<p>I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky since some of the chess rules (e.g. King Castling, en passent, draws based on 3 or more repeated moves) are based not only on the board layout but also on the history of moves.</p> <p>I would prefer the format to be:</p> <ul> <li>textual</li> <li>human readable</li> <li>based on a standard (e.g. YAML, XML)</li> <li>easily parsable in a variety of languages</li> </ul> <p>But I am willing to sacrifice any of these for a suitable solution.</p> <p>My main question is: How can I build algorithms of such a complexity that operate on such complex state from a data format?</p> <p>A followup queston is: Can you provide an example of a similar problem solved in a similar manner that can act as a starting point?</p> <p><strong>Edit:</strong> In response to a request for clarity -- consider that I will have a server written in Python, one client written in C# and another client written in Java. I would like to avoid specifying the rules (e.g. for allowable piece movement, circumstances for check, etc.) in each place. I would prefer to specify these rules once in a language independant manner.</p>
8
2008-10-11T16:34:31Z
297,803
<p>I would agree with the comment left by ΤΖΩΤΖΙΟΥ, viz. just let the server do the validation and let the clients submit a potential move. If that's not the way you want to take the design, then just write the rules in Python as suggested by S. Lott and others.</p> <p>It really shouldn't be that hard. You can break the rules down into three major categories:<br /> - Rules that rely on the state of the board (castling, en passant, draws, check, checkmate, passing through check, is it even this player's turn, etc.)<br /> - Rules that apply to all pieces (can't occupy the same square as another piece of your own colour, moving to a square w/ opponent's piece == capture, can't move off the board)<br /> - Rules that apply to each individual piece. (pawns can't move backwards, castles can't move diagonally, etc)</p> <p>Each rule can be implemented as a function, and then for each half-move, validity is determined by seeing if it passes all of the validations.</p> <p>For each potential move submitted, you would just need to check the rules in the following order:</p> <ol> <li>is the proposed move potentially valid? (the right "shape" for the piece)</li> <li>does it fit the restraints of the board? (is the piece blocked, would it move off the edge)</li> <li>does the move violate state requirements? (am I in check after this move? do I move through check? is this en passant capture legal?)</li> </ol> <p>If all of those are ok, then the server should accept the move as legal…</p>
0
2008-11-18T03:48:18Z
[ "c#", "java", "python", "chess", "dataformat" ]
Python Code Organization Question : Eggs + Packages + Buildout + Unit Tests + SVN
194,339
<p>I have several python projects that share common modules. Until now, I've been ... ahem ... keeping multiple copies of the common code and synchronizing by hand. But I'd clearly prefer to do something else.</p> <p>It looks to me now, as if zc.Buildout maybe what I need. I guess that what I should be doing is putting each reusable component of my system into a separate egg, and then using buildout to assemble them into projects.</p> <p>I'm also thinking that for any particular module, I should put the unit-tests into a separate package or egg, so that I'm not also installing copies of the component's unit-tests in every project. I only want to unit-test in a place where my library is developed, not where it's just being used.</p> <p>So maybe I want something like this</p> <pre><code>projects lib1 tests code lib2 tests code app1 tests appcode app2 tests appcode </code></pre> <p>etc.</p> <p>Where both app1 and app2 are independent applications with their own code and tests, but are also including and using both lib1 and lib2. And lib1/test, lib1/code, lib2/test, lib2code, app1, app2 are separate eggs. Does this sound right?</p> <p>However, I now get confused. I assume that when I develop app1, I want buildout to pull copies of lib1, lib2 and app1 into a separate working directory rather than put copies of these libraries under app1 directly. But how does this work with my SVN source-control? If the working directory is dynamically constructed with buildout, it can't be a live SVN directory from which I can check the changes back into the repository?</p> <p>Have I misunderstood how buildout is meant to be used? Would I be better going for a completely different approach? How do you mix source-control with module-reuse between projects?</p> <p>Update : thanks to the two people who've currently answered this question. I'm experimenting more with this.</p>
8
2008-10-11T17:21:05Z
194,472
<p>This is why you have the <a href="http://www.python.org/doc/2.5.2/lib/module-site.html" rel="nofollow">site</a> module. It sets the internal <code>sys.path</code> to include all packages and modules from</p> <ul> <li><code>lib/site-packages</code> -- including directories, eggs and <code>.pth</code> files.</li> <li><code>PYTHONPATH</code></li> </ul> <p>This way there is exactly one working copy of your libraries.</p> <p>There are an unlimited ways to make use of this. Here are two.</p> <ol> <li><p>In each lib, write a <code>setup.py</code> that deploys your lib properly. When you make changes, you do an <code>svn up</code> to collect the changes and a <code>python setup.py install</code> to deploy the one working copy that every application shares.</p></li> <li><p>In each app, either depend on things being in the <code>PYTHONPATH</code> environment variable. Be sure that <code>projects/lib1</code> and <code>projects/lib2</code> are won the <code>PYTHONPATH</code>. Each app then shares the one working copy of the various libraries.</p></li> </ol>
2
2008-10-11T19:22:32Z
[ "python", "svn", "code-organization", "buildout", "egg" ]
Python Code Organization Question : Eggs + Packages + Buildout + Unit Tests + SVN
194,339
<p>I have several python projects that share common modules. Until now, I've been ... ahem ... keeping multiple copies of the common code and synchronizing by hand. But I'd clearly prefer to do something else.</p> <p>It looks to me now, as if zc.Buildout maybe what I need. I guess that what I should be doing is putting each reusable component of my system into a separate egg, and then using buildout to assemble them into projects.</p> <p>I'm also thinking that for any particular module, I should put the unit-tests into a separate package or egg, so that I'm not also installing copies of the component's unit-tests in every project. I only want to unit-test in a place where my library is developed, not where it's just being used.</p> <p>So maybe I want something like this</p> <pre><code>projects lib1 tests code lib2 tests code app1 tests appcode app2 tests appcode </code></pre> <p>etc.</p> <p>Where both app1 and app2 are independent applications with their own code and tests, but are also including and using both lib1 and lib2. And lib1/test, lib1/code, lib2/test, lib2code, app1, app2 are separate eggs. Does this sound right?</p> <p>However, I now get confused. I assume that when I develop app1, I want buildout to pull copies of lib1, lib2 and app1 into a separate working directory rather than put copies of these libraries under app1 directly. But how does this work with my SVN source-control? If the working directory is dynamically constructed with buildout, it can't be a live SVN directory from which I can check the changes back into the repository?</p> <p>Have I misunderstood how buildout is meant to be used? Would I be better going for a completely different approach? How do you mix source-control with module-reuse between projects?</p> <p>Update : thanks to the two people who've currently answered this question. I'm experimenting more with this.</p>
8
2008-10-11T17:21:05Z
195,102
<p>I've use the following structure quite effectively. in SVN.</p> <pre><code>Lib1/ branches/ tags/ trunk/ lib1/ tests/ setup.py Lib2 branches/ tags/ trunk/ lib2/ tests/ setup.py App1 branches/ tags/ trunk/ app1/ tests/ setup.py App2 branches/ tags/ trunk/ app2/ tests/ setup.py </code></pre> <p>I would then create my dev workspace( I use eclipse/pydev) as follows, checking out from either trunk or a branch.</p> <pre><code>Lib1/ lib1/ tests/ setup.py Lib2/ lib2/ tests/ setup.py App1/ app1/ tests/ setup.py App2/ app2/ tests/ setup.py </code></pre> <p>I would then use either eclipse project dependencies setup python path, which works well with eclipse code completion. setup.py also works but does not support having multiple workspaces well.</p> <p>For deployment, I use create a single zip with the following structure.</p> <pre><code>App1/ lib1-1.1.0-py2.5.egg/ lib2-1.1.0-py2.5.egg/ app1/ sitecustomize.py App2/ lib1-1.2.0-py2.5.egg/ lib2-1.2.0-py2.5.egg/ app2/ sitecustomize.py </code></pre> <p>I don't use setup install because I want to support multiple versions of the app, also I have some control of the runtime environment, so I don't package python with my deployment but should be easy to add Python into the deployment package if it's needed.</p>
2
2008-10-12T04:37:08Z
[ "python", "svn", "code-organization", "buildout", "egg" ]
Python Code Organization Question : Eggs + Packages + Buildout + Unit Tests + SVN
194,339
<p>I have several python projects that share common modules. Until now, I've been ... ahem ... keeping multiple copies of the common code and synchronizing by hand. But I'd clearly prefer to do something else.</p> <p>It looks to me now, as if zc.Buildout maybe what I need. I guess that what I should be doing is putting each reusable component of my system into a separate egg, and then using buildout to assemble them into projects.</p> <p>I'm also thinking that for any particular module, I should put the unit-tests into a separate package or egg, so that I'm not also installing copies of the component's unit-tests in every project. I only want to unit-test in a place where my library is developed, not where it's just being used.</p> <p>So maybe I want something like this</p> <pre><code>projects lib1 tests code lib2 tests code app1 tests appcode app2 tests appcode </code></pre> <p>etc.</p> <p>Where both app1 and app2 are independent applications with their own code and tests, but are also including and using both lib1 and lib2. And lib1/test, lib1/code, lib2/test, lib2code, app1, app2 are separate eggs. Does this sound right?</p> <p>However, I now get confused. I assume that when I develop app1, I want buildout to pull copies of lib1, lib2 and app1 into a separate working directory rather than put copies of these libraries under app1 directly. But how does this work with my SVN source-control? If the working directory is dynamically constructed with buildout, it can't be a live SVN directory from which I can check the changes back into the repository?</p> <p>Have I misunderstood how buildout is meant to be used? Would I be better going for a completely different approach? How do you mix source-control with module-reuse between projects?</p> <p>Update : thanks to the two people who've currently answered this question. I'm experimenting more with this.</p>
8
2008-10-11T17:21:05Z
421,758
<p>I'd consider each application and library an egg and use one of the examples already given in terms of laying it out in SVN. Really, the VCS end of things should not be an issue. </p> <p>Then, for testing each application/library or combination, I'd set up a virtualenv and install each package either via setup.py develop or via actually installing it. Virtualenvwrapper is also a helpful tool to manage these environments as you can simply do things like:</p> <pre><code>mkvirtualenv lib1-dev </code></pre> <p>And then later:</p> <pre><code>workon lib1-dev </code></pre> <p>Virtualenv uses the PYTHONPATH to gain finer control of the packages installed. Likewise, you can use create environments with:</p> <pre><code>virtualenv --no-site-packages some-env </code></pre> <p>And it will leave out any references to your actual system site-packages. This is helpful because not only can you test your library/application, but you can also verify you have the correct dependencies on installation. </p>
1
2009-01-07T19:38:52Z
[ "python", "svn", "code-organization", "buildout", "egg" ]
Python Code Organization Question : Eggs + Packages + Buildout + Unit Tests + SVN
194,339
<p>I have several python projects that share common modules. Until now, I've been ... ahem ... keeping multiple copies of the common code and synchronizing by hand. But I'd clearly prefer to do something else.</p> <p>It looks to me now, as if zc.Buildout maybe what I need. I guess that what I should be doing is putting each reusable component of my system into a separate egg, and then using buildout to assemble them into projects.</p> <p>I'm also thinking that for any particular module, I should put the unit-tests into a separate package or egg, so that I'm not also installing copies of the component's unit-tests in every project. I only want to unit-test in a place where my library is developed, not where it's just being used.</p> <p>So maybe I want something like this</p> <pre><code>projects lib1 tests code lib2 tests code app1 tests appcode app2 tests appcode </code></pre> <p>etc.</p> <p>Where both app1 and app2 are independent applications with their own code and tests, but are also including and using both lib1 and lib2. And lib1/test, lib1/code, lib2/test, lib2code, app1, app2 are separate eggs. Does this sound right?</p> <p>However, I now get confused. I assume that when I develop app1, I want buildout to pull copies of lib1, lib2 and app1 into a separate working directory rather than put copies of these libraries under app1 directly. But how does this work with my SVN source-control? If the working directory is dynamically constructed with buildout, it can't be a live SVN directory from which I can check the changes back into the repository?</p> <p>Have I misunderstood how buildout is meant to be used? Would I be better going for a completely different approach? How do you mix source-control with module-reuse between projects?</p> <p>Update : thanks to the two people who've currently answered this question. I'm experimenting more with this.</p>
8
2008-10-11T17:21:05Z
7,620,767
<p>Do not separate the tests from your code, you need to keep the two closely together. It's not as if tests take up that much disk space or any memory! And tests can be extremely instructive to your library users.</p> <p>For library packages, include a <code>buildout.cfg</code> and <code>bootstrap.py</code> file with your package to make running the tests easy. See, for example, the <a href="https://github.com/plone/plone.reload" rel="nofollow">plone.reload package</a>; note how it uses <a href="http://pypi.python.org/pypi/zc.recipe.testrunner" rel="nofollow">zc.recipe.testrunner</a> parts to create a test script that'll autodiscover your tests and run them. This way you can ensure that your library packages are always tested!</p> <p>Then, your app packages only need to test the integration and application-specific code. Again, include the tests with the package itself, you want to not forget about your tests when working on the code. Use <code>zc.recipe.testrunner</code> parts in your buildout to discover and run these.</p> <p>Last but not least, use <a href="http://pypi.python.org/pypi/mr.developer" rel="nofollow">mr.developer</a> to manage your packages. With mr.developer, you can check out packages as your work on them, or rely on the released versions if you do not need to work on the code. A larger project will have many dependencies, many of which do not need you tweaking the code. With mr.developer you can pull in source code at will and turn these into development eggs, until such time you release that code and you can dismiss the checkout again.</p> <p>To see an actual example of such a project buildout, look no further than the <a href="https://github.com/plone/buildout.coredev" rel="nofollow">Plone core development buildout</a>.</p> <p>The <code>sources.cfg</code> file contains a long list of SCM locations for various packages, but normally released versions of eggs are used, until you explicitly activate the packages you plan to work on. <code>checkouts.cfg</code> lists all the packages checked out by default; these packages have changes that will be part of the next version of Plone and have not yet been released. If you work on Plone, you want these around because you cannot ignore these changes. And <code>testing.cfg</code> lists all the packages you need to test if you want to test Plone, a big list.</p> <p>Note that Plone's sources come from a wide variety of locations. Once you start using buildout and mr.developer to manage your packages, you are free to pull your source code from anywhere.</p>
5
2011-10-01T14:15:43Z
[ "python", "svn", "code-organization", "buildout", "egg" ]
Running a web app in Grails vs Django
195,101
<p>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:</p> <ol> <li><p>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'll be apache + mysql on linux.</p></li> <li><p>Does django or grails have a better choice of cheap and flexible hosting? Initially it'll probably be low bandwidth requirements. I'm not sure about the exact specs required, but from what I've been reading it seems like django would require far less server resources (even 256MB server is ok) than grails.</p></li> </ol>
5
2008-10-12T04:36:49Z
195,137
<p>i think python tend to have lower hosting requirements (i.e., grails needs a jvm, and most el-cheapo hosts dont provide one, where as they usually provide python support). Plus google app engine supports django (to some extend). </p> <p>But if you got the dough, grails is so much better imho. </p>
0
2008-10-12T05:46:45Z
[ "python", "django", "grails", "groovy", "web-applications" ]
Running a web app in Grails vs Django
195,101
<p>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:</p> <ol> <li><p>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'll be apache + mysql on linux.</p></li> <li><p>Does django or grails have a better choice of cheap and flexible hosting? Initially it'll probably be low bandwidth requirements. I'm not sure about the exact specs required, but from what I've been reading it seems like django would require far less server resources (even 256MB server is ok) than grails.</p></li> </ol>
5
2008-10-12T04:36:49Z
195,152
<p>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 of ram for grails will not break your budget. Also if your interested in cloud based solutions Morph is hosting grails apps. <a href="http://developer.mor.ph/grails" rel="nofollow">http://developer.mor.ph/grails</a></p> <p>I like Django, but I for the maturity of the platform and the amount of quality Java work out there in terms of libaries and frameworks I chose grails. In truth I think they are both good solutions but you cannot deny that your options are much greater with grails.</p>
9
2008-10-12T06:23:56Z
[ "python", "django", "grails", "groovy", "web-applications" ]
Running a web app in Grails vs Django
195,101
<p>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:</p> <ol> <li><p>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'll be apache + mysql on linux.</p></li> <li><p>Does django or grails have a better choice of cheap and flexible hosting? Initially it'll probably be low bandwidth requirements. I'm not sure about the exact specs required, but from what I've been reading it seems like django would require far less server resources (even 256MB server is ok) than grails.</p></li> </ol>
5
2008-10-12T04:36:49Z
197,592
<p>I think from an operations perspective things are going to be close enough that you can base your decision on other criteria. If you can afford a virtual private server with at least 256 MB RAM you will be able to deploy Grails applications. If the cost seems like a lot check out Sun. They are really pushing hosting solutions based on their product stack and there are some greats deals available. I have free hosting from Layered Tech for a year through Ostatic.</p>
2
2008-10-13T13:34:41Z
[ "python", "django", "grails", "groovy", "web-applications" ]
Running a web app in Grails vs Django
195,101
<p>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:</p> <ol> <li><p>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'll be apache + mysql on linux.</p></li> <li><p>Does django or grails have a better choice of cheap and flexible hosting? Initially it'll probably be low bandwidth requirements. I'm not sure about the exact specs required, but from what I've been reading it seems like django would require far less server resources (even 256MB server is ok) than grails.</p></li> </ol>
5
2008-10-12T04:36:49Z
288,617
<p>With Java hosting you don't need to do all the stupid tricks with apache, or nginx. Jetty itself can host everything you need, that's how the guys at www.mor.ph do it, and they find it to be pretty fast.</p> <p>The memory usage that way is pretty minimal, I host mine on a 256MB Ubuntu server from RapidXen, so it's about $10/month.</p> <p>I tried developing in Django, and while it runs all the scripts faster (like bootstrapping, or test cases) it's not as well-crafted in my oppinion</p>
5
2008-11-13T22:44:52Z
[ "python", "django", "grails", "groovy", "web-applications" ]
Running a web app in Grails vs Django
195,101
<p>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:</p> <ol> <li><p>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'll be apache + mysql on linux.</p></li> <li><p>Does django or grails have a better choice of cheap and flexible hosting? Initially it'll probably be low bandwidth requirements. I'm not sure about the exact specs required, but from what I've been reading it seems like django would require far less server resources (even 256MB server is ok) than grails.</p></li> </ol>
5
2008-10-12T04:36:49Z
4,260,564
<p>You can host Grails apps cheaply on EATJ: <a href="http://smithnicholas.wordpress.com/2010/09/20/deploying-your-grails-application-on-eatj/" rel="nofollow">http://smithnicholas.wordpress.com/2010/09/20/deploying-your-grails-application-on-eatj/</a></p>
1
2010-11-23T20:29:02Z
[ "python", "django", "grails", "groovy", "web-applications" ]
Running compiled python (py2exe) as administrator in Vista
195,109
<p>Is it possible to programaticly run compiled Python (comiled via py2exe) as administrator in Vista?</p> <p>Some more clarification:<br /> 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 and run as administrator even when the user has administrator privileges, unlike in XP where it will run if the user has administration rights, so I need a way to elevate it to the correct privileges programaticly.</p>
7
2008-10-12T04:46:16Z
195,247
<p>Do you mean that you want Windows to prompt for elevation when your program is run? This is controlled by adding a UAC manifest to the EXE's resources. <a href="http://blogs.msdn.com/shawnfa/archive/2006/04/06/568563.aspx">This blog entry</a> explains how to create the manifest and how to compile it into a .RES file.</p> <p>I don't know what facilities py2exe has for embedding custom .RES files, so you might need to use the MT.EXE tool from the Platform SDK to embed the manifest in your program. MT.EXE doesn't need .RES files; it can merge the .manifest file directly.</p>
5
2008-10-12T08:55:22Z
[ "python", "windows-vista", "permissions", "py2exe" ]
Running compiled python (py2exe) as administrator in Vista
195,109
<p>Is it possible to programaticly run compiled Python (comiled via py2exe) as administrator in Vista?</p> <p>Some more clarification:<br /> 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 and run as administrator even when the user has administrator privileges, unlike in XP where it will run if the user has administration rights, so I need a way to elevate it to the correct privileges programaticly.</p>
7
2008-10-12T04:46:16Z
196,208
<p>Following up Roger Lipscombe's comment, I've used a manifest file in py2exe without any real knowledge of what I was doing. So this <em>might</em> work:</p> <pre><code># in setup.py # manifest copied from http://blogs.msdn.com/shawnfa/archive/2006/04/06/568563.aspx manifest = ''' &lt;assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"&gt; &lt;asmv3:trustInfo xmlns:asmv3="urn:schemas-microsoft-com:asm.v3"&gt; &lt;asmv3:security&gt; &lt;asmv3:requestedPrivileges&gt; &lt;asmv3:requestedExecutionLevel level="asInvoker" uiAccess="false" /&gt; &lt;/asmv3:requestedPrivileges&gt; &lt;/asmv3:security&gt; &lt;/asmv3:trustInfo&gt; &lt;/assembly&gt; ''' setup(name='MyApp', #... windows=[ { #... 'other_resources':[(24, 1, manifest)], }] ) </code></pre> <p>You may need to do some fiddling though..</p>
3
2008-10-12T22:17:44Z
[ "python", "windows-vista", "permissions", "py2exe" ]
Running compiled python (py2exe) as administrator in Vista
195,109
<p>Is it possible to programaticly run compiled Python (comiled via py2exe) as administrator in Vista?</p> <p>Some more clarification:<br /> 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 and run as administrator even when the user has administrator privileges, unlike in XP where it will run if the user has administration rights, so I need a way to elevate it to the correct privileges programaticly.</p>
7
2008-10-12T04:46:16Z
1,445,547
<p>Following the examples from <code>Python2x\Lib\site-packages\py2exe\samples\user_access_control</code> just add <code>uac_info="requireAdministrator"</code> to console or windows dict:</p> <pre><code>windows = [{ 'script': "admin.py", 'uac_info': "requireAdministrator", },] </code></pre>
34
2009-09-18T16:15:43Z
[ "python", "windows-vista", "permissions", "py2exe" ]
Python Decimal
195,116
<p>Does anyone know of a faster decimal implementation in python. As example below demonstrates, standard python decimal is ~100 times slower than float.</p> <pre><code>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 d * test d / test d ** test str(d) abs(d) if __name__ == "__main__": a = Timer("run(123.345, float)", "from decimal_benchmark import run") print "FLOAT", a.timeit(1) a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal") print "DECIMAL", a.timeit(1) FLOAT 0.040635041427 DECIMAL 3.39666790146 </code></pre> <p>Thanks, Maksim</p>
13
2008-10-12T05:03:05Z
195,124
<p>The <a href="http://gmplib.org">GMP</a> library is one of the best arbitrary precision math libraries around, and there is a Python binding available at <a href="http://www.aleax.it/gmpy.html">GMPY</a>. I would try that method.</p>
10
2008-10-12T05:11:37Z
[ "python" ]
Python Decimal
195,116
<p>Does anyone know of a faster decimal implementation in python. As example below demonstrates, standard python decimal is ~100 times slower than float.</p> <pre><code>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 d * test d / test d ** test str(d) abs(d) if __name__ == "__main__": a = Timer("run(123.345, float)", "from decimal_benchmark import run") print "FLOAT", a.timeit(1) a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal") print "DECIMAL", a.timeit(1) FLOAT 0.040635041427 DECIMAL 3.39666790146 </code></pre> <p>Thanks, Maksim</p>
13
2008-10-12T05:03:05Z
195,140
<p>You should compare <em>Decimal</em> to <em>Long Integer</em> performance, not floating point. Floating point is mostly hardware these days. <em>Decimal</em> is used for <strong>decimal precision</strong>, while <em>Floating Point</em> is for wider range. Use the <em>decimal</em> package for monetary calculations.</p> <p>To quote the <em>decimal</em> package manual:</p> <blockquote> <p>Decimal numbers can be represented exactly. In contrast, numbers like 1.1 do not have an exact representation in binary floating point. End users typically would not expect 1.1 to display as 1.1000000000000001 as it does with binary floating point. </p> <p>The exactness carries over into arithmetic. In decimal floating point, "0.1 + 0.1 + 0.1 - 0.3" is exactly equal to zero. In binary floating point, result is 5.5511151231257827e-017. While near to zero, the differences prevent reliable equality testing and differences can accumulate. For this reason, decimal would be preferred in accounting applications which have strict equality invariants. </p> </blockquote>
2
2008-10-12T05:55:38Z
[ "python" ]
Python Decimal
195,116
<p>Does anyone know of a faster decimal implementation in python. As example below demonstrates, standard python decimal is ~100 times slower than float.</p> <pre><code>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 d * test d / test d ** test str(d) abs(d) if __name__ == "__main__": a = Timer("run(123.345, float)", "from decimal_benchmark import run") print "FLOAT", a.timeit(1) a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal") print "DECIMAL", a.timeit(1) FLOAT 0.040635041427 DECIMAL 3.39666790146 </code></pre> <p>Thanks, Maksim</p>
13
2008-10-12T05:03:05Z
8,192,918
<p>You can try <a href="http://www.bytereef.org/mpdecimal/index.html">cdecimal</a>:</p> <pre><code>from cdecimal import Decimal </code></pre>
20
2011-11-19T08:47:41Z
[ "python" ]
Python Decimal
195,116
<p>Does anyone know of a faster decimal implementation in python. As example below demonstrates, standard python decimal is ~100 times slower than float.</p> <pre><code>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 d * test d / test d ** test str(d) abs(d) if __name__ == "__main__": a = Timer("run(123.345, float)", "from decimal_benchmark import run") print "FLOAT", a.timeit(1) a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal") print "DECIMAL", a.timeit(1) FLOAT 0.040635041427 DECIMAL 3.39666790146 </code></pre> <p>Thanks, Maksim</p>
13
2008-10-12T05:03:05Z
13,876,446
<p>python Decimal is very slow, one can use float or a faster implementation of Decimal cDecimal.</p>
0
2012-12-14T10:04:14Z
[ "python" ]
Python Decimal
195,116
<p>Does anyone know of a faster decimal implementation in python. As example below demonstrates, standard python decimal is ~100 times slower than float.</p> <pre><code>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 d * test d / test d ** test str(d) abs(d) if __name__ == "__main__": a = Timer("run(123.345, float)", "from decimal_benchmark import run") print "FLOAT", a.timeit(1) a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal") print "DECIMAL", a.timeit(1) FLOAT 0.040635041427 DECIMAL 3.39666790146 </code></pre> <p>Thanks, Maksim</p>
13
2008-10-12T05:03:05Z
24,408,798
<p>Use <a href="http://www.bytereef.org/mpdecimal/index.html" rel="nofollow">cDecimal</a>.</p> <p>Adding the following to your benchmark:</p> <pre><code>a = Timer("run('123.345', Decimal)", "import sys; import cdecimal; sys.modules['decimal'] = cdecimal; from decimal_benchmark import run; from decimal import Decimal") print "CDECIMAL", a.timeit(1) </code></pre> <p>My results are:</p> <pre><code>FLOAT 0.0257983528473 DECIMAL 2.45782495288 CDECIMAL 0.0687125069413 </code></pre> <p>(Python 2.7.6/32, Win7/64, AMD Athlon II 2.1GHz)</p>
0
2014-06-25T12:33:07Z
[ "python" ]
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
195,534
<p>What to use for a medium to large python WSGI application, Apache + mod_wsgi or Nginx + mod_wsgi?<br /><br /> Which combination will need more memory and CPU time?<br /> Which one is faster?<br/> Which is known for being more stable than the other?<br /><br /> I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very high-load application, what do you know about this? <br /><br /> <strong><em>Note</strong>: I didn't use any Python Web Framework, I just wrote the whole thing from scratch.</em><br /> <strong><em>Note'</strong>: Other suggestions are also welcome.</em> <br /></p>
56
2008-10-12T14:14:19Z
196,039
<p>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.</p> <p>(shameless plug warning: I wrote the WSGI code that I'm about to mention)</p> <p><a href="http://www.kamaelia.org/Home">Kamaelia</a> will have WSGI support coming in the next release. The cool thing is that you'll likely be able to either use the pre-made one or build your own using the existing HTTP and WSGI code.</p> <p>(end shameless plug)</p> <p>With that said, given the current options, I would personally probably go with CherryPy because it seems to be the simplest to configure and I can understand python code moreso than I can understand C code.</p> <p>You may do best to try each of them out and see what the pros and cons of each one are for your specific application though.</p>
7
2008-10-12T20:45:41Z
[ "python", "apache", "nginx", "mod-wsgi" ]
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
195,534
<p>What to use for a medium to large python WSGI application, Apache + mod_wsgi or Nginx + mod_wsgi?<br /><br /> Which combination will need more memory and CPU time?<br /> Which one is faster?<br/> Which is known for being more stable than the other?<br /><br /> I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very high-load application, what do you know about this? <br /><br /> <strong><em>Note</strong>: I didn't use any Python Web Framework, I just wrote the whole thing from scratch.</em><br /> <strong><em>Note'</strong>: Other suggestions are also welcome.</em> <br /></p>
56
2008-10-12T14:14:19Z
196,580
<p>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.</p> <p>From a raw performance perspective, nginx is faster, but not so much faster that I would include that as a determining factor.</p> <p>Apache has the advantage in the area of modules available, and the fact that it is pretty much standard. Any web host you go with will have it installed, and most techs are going to be very familiar with it.</p> <p>Also, if you use mod_wsgi, it is your wsgi server so you don't even need cherrypy.</p> <p>Other than that, the best advice I can give is try setting up your app under both and do some benchmarking, since no matter what any one tells you, your mileage may vary.</p>
13
2008-10-13T02:44:24Z
[ "python", "apache", "nginx", "mod-wsgi" ]
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
195,534
<p>What to use for a medium to large python WSGI application, Apache + mod_wsgi or Nginx + mod_wsgi?<br /><br /> Which combination will need more memory and CPU time?<br /> Which one is faster?<br/> Which is known for being more stable than the other?<br /><br /> I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very high-load application, what do you know about this? <br /><br /> <strong><em>Note</strong>: I didn't use any Python Web Framework, I just wrote the whole thing from scratch.</em><br /> <strong><em>Note'</strong>: Other suggestions are also welcome.</em> <br /></p>
56
2008-10-12T14:14:19Z
409,017
<p>The author of nginx mod_wsgi explains some differences to Apache mod_wsgi <a href="http://osdir.com/ml/web.nginx.english/2008-05/msg00451.html">in this mailing list message</a>.</p>
16
2009-01-03T13:04:18Z
[ "python", "apache", "nginx", "mod-wsgi" ]
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
195,534
<p>What to use for a medium to large python WSGI application, Apache + mod_wsgi or Nginx + mod_wsgi?<br /><br /> Which combination will need more memory and CPU time?<br /> Which one is faster?<br/> Which is known for being more stable than the other?<br /><br /> I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very high-load application, what do you know about this? <br /><br /> <strong><em>Note</strong>: I didn't use any Python Web Framework, I just wrote the whole thing from scratch.</em><br /> <strong><em>Note'</strong>: Other suggestions are also welcome.</em> <br /></p>
56
2008-10-12T14:14:19Z
1,038,043
<p>For nginx/mod_wsgi, ensure you read:</p> <p><a href="http://blog.dscpl.com.au/2009/05/blocking-requests-and-nginx-version-of.html">http://blog.dscpl.com.au/2009/05/blocking-requests-and-nginx-version-of.html</a></p> <p>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 scenario is that with multiprocess nginx configuration, you can see user requests be blocked even though some nginx worker processes may be idle. Apache/mod_wsgi doesn't have this issue as Apache processes will only accept requests when it has the resources to actually handle the request. Apache/mod_wsgi will thus give more predictable and reliable behaviour.</p>
67
2009-06-24T12:26:01Z
[ "python", "apache", "nginx", "mod-wsgi" ]
What is the time complexity of popping elements from list in Python?
195,625
<p>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? </p>
16
2008-10-12T15:58:59Z
195,647
<p>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 up in the array of pointers.</p>
13
2008-10-12T16:15:39Z
[ "python" ]
What is the time complexity of popping elements from list in Python?
195,625
<p>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? </p>
16
2008-10-12T15:58:59Z
195,839
<p>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).</p> <p>Here's a great article on how Python lists are stored and manipulated: <a href="http://effbot.org/zone/python-list.htm">http://effbot.org/zone/python-list.htm</a></p>
23
2008-10-12T18:47:42Z
[ "python" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
195,645
<p>I assume you've pasted the dict literal into the source, and that's what's taking a minute? I don't know how to get around that, but you could probably avoid instantiating this dict upon <em>import</em>... You could lazily-instantiate it the first time it's actually used.</p>
2
2008-10-12T16:14:43Z
[ "python", "nltk" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
195,702
<p>You can use a <a href="http://www.python.org/doc/2.5.2/lib/module-shelve.html" rel="nofollow">shelve</a> to store your data on disc instead of loading the whole data into memory. So startup time will be very fast, but the trade-off will be slower access time. </p> <p>Shelve will pickle the dict values too, but will do the (un)pickle not at startup for all the items, but only at access time for each item itself.</p>
1
2008-10-12T17:04:20Z
[ "python", "nltk" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
195,739
<p>Calculate your global var on the first use.</p> <pre><code>class Proxy: @property def global_name(self): # calculate your global var here, enable cache if needed ... _proxy_object = Proxy() GLOBAL_NAME = _proxy_object.global_name </code></pre> <p>Or better yet, access necessery data via special data object.</p> <pre><code>class Data: GLOBAL_NAME = property(...) data = Data() </code></pre> <p>Example:</p> <pre><code>from some_module import data print(data.GLOBAL_NAME) </code></pre> <p>See <a href="http://docs.djangoproject.com/en/dev/topics/settings/" rel="nofollow">Django settings</a>.</p>
3
2008-10-12T17:29:46Z
[ "python", "nltk" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
195,758
<p>You could try using the <a href="http://en.wikipedia.org/wiki/All_You_Zombies%E2%80%94" rel="nofollow">marshal</a> module instead of the c?Pickle one; it could be faster. This module is used by python to store values in a binary format. Note especially the following paragraph, to see if marshal fits your needs:</p> <blockquote> <p>Not all Python object types are supported; in general, only objects whose value is independent from a particular invocation of Python can be written and read by this module. The following types are supported: None, integers, long integers, floating point numbers, strings, Unicode objects, tuples, lists, sets, dictionaries, and code objects, where it should be understood that tuples, lists and dictionaries are only supported as long as the values contained therein are themselves supported; and recursive lists and dictionaries should not be written (they will cause infinite loops). </p> </blockquote> <p>Just to be on the safe side, before unmarshalling the dict, make sure that the Python version that unmarshals the dict is the same as the one that did the marshal, since there are no guarantees for backwards compatibility.</p>
2
2008-10-12T17:38:20Z
[ "python", "nltk" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
195,776
<p>Expanding on the delayed-calculation idea, why not turn the dict into a class that supplies (and caches) elements as necessary?</p> <p>You might also use psyco to speed up overall execution...</p>
0
2008-10-12T17:54:36Z
[ "python", "nltk" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
195,792
<p><em>OR</em> you could just use a database for storing the values in? Check out SQLObject, which makes it very easy to store stuff to a database.</p>
0
2008-10-12T18:08:54Z
[ "python", "nltk" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
195,962
<p>Just to clarify: the code in the body of a module is <em>not</em> 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.</p> <p>However, if your problem is the time it takes for the first import after the program is run, you'll probably need to use some other method than a python dict. Probably best would be to use an on-disk form, for instance a sqlite database, one of the dbm modules.</p> <p>For a minimal change in your interface, the shelve module may be your best option - this puts a pretty transparent interface between the dbm modules that makes them act like an arbitrary python dict, allowing any picklable value to be stored. Here's an example:</p> <pre><code># Create dict with a million items: import shelve d = shelve.open('path/to/my_persistant_dict') d.update(('key%d' % x, x) for x in xrange(1000000)) d.close() </code></pre> <p>Then in the next process, use it. There should be no large delay, as lookups are only performed for the key requested on the on-disk form, so everything doesn't have to get loaded into memory:</p> <pre><code>&gt;&gt;&gt; d = shelve.open('path/to/my_persistant_dict') &gt;&gt;&gt; print d['key99999'] 99999 </code></pre> <p>It's a bit slower than a real dict, and it <strong>will</strong> still take a long time to load if you do something that requires all the keys (eg. try to print it), but may solve your problem.</p>
17
2008-10-12T20:12:25Z
[ "python", "nltk" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
196,218
<p>A couple of things that will help speed up imports:</p> <ol> <li>You might try running python using the -OO flag when running python. This will do some optimizations that will reduce import time of modules.</li> <li>Is there any reason why you couldn't break the dictionary up into smaller dictionaries in separate modules that can be loaded more quickly?</li> <li>As a last resort, you could do the calculations asynchronously so that they won't delay your program until it needs the results. Or maybe even put the dictionary in a separate process and pass data back and forth using IPC if you want to take advantage of multi-core architectures.</li> </ol> <p>With that said, I agree that you shouldn't be experiencing any delay in importing modules after the first time you import it. Here are a couple of other general thoughts:</p> <ol> <li>Are you importing the module within a function? If so, this <em>can</em> lead to performance problems since it has to check and see if the module is loaded every time it hits the import statement.</li> <li>Is your program multi-threaded? I have seen occassions where executing code upon module import in a multi-threaded app can cause some wonkiness and application instability (most notably with the cgitb module).</li> <li>If this is a global variable, be aware that global variable lookup times can be significantly longer than local variable lookup times. In this case, you can achieve a significant performance improvement by binding the dictionary to a local variable if you're using it multiple times in the same context.</li> </ol> <p>With that said, it's a tad bit difficult to give you any specific advice without a little bit more context. More specifically, where are you importing it? And what are the computations?</p>
1
2008-10-12T22:31:37Z
[ "python", "nltk" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
201,077
<ol> <li><p>Factor the computationally intensive part into a separate module. Then at least on reload, you won't have to wait. </p></li> <li><p>Try dumping the data structure using protocol 2. The command to try would be <code>cPickle.dump(FD, protocol=2)</code>. From the docstring for <code>cPickle.Pickler</code>:</p> <blockquote> <pre><code>Protocol 0 is the only protocol that can be written to a file opened in text mode and read back successfully. When using a protocol higher than 0, make sure the file is opened in binary mode, both when pickling and unpickling. </code></pre> </blockquote></li> </ol>
1
2008-10-14T13:07:08Z
[ "python", "nltk" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
345,744
<p>If the 'shelve' solution turns out to be too slow or fiddly, there are other possibilities:</p> <ul> <li><a href="http://pypi.python.org/pypi/shove" rel="nofollow">shove</a></li> <li><a href="http://www.mems-exchange.org/software/durus/" rel="nofollow">Durus</a></li> <li><a href="http://www.zope.org" rel="nofollow">ZopeDB</a></li> <li><a href="http://www.pytables.org/" rel="nofollow">pyTables</a></li> </ul>
2
2008-12-06T01:56:12Z
[ "python", "nltk" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
431,452
<p>There's another pretty obvious solution for this problem. When code is reloaded the original scope is still available.</p> <p>So... doing something like this will make sure this code is executed only once.</p> <pre><code>try: FD except NameError: FD = FreqDist(word for word in brown.words()) </code></pre>
0
2009-01-10T18:06:13Z
[ "python", "nltk" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
1,184,838
<p><code>shelve</code> gets really slow with large data sets. I've been using <a href="http://streamhacker.com/2009/05/20/building-a-nltk-freqdist-on-redis/" rel="nofollow">redis</a> quite successfully, and wrote a <a href="http://bitbucket.org/japerk/nltk-extras/src/tip/probability.py" rel="nofollow">FreqDist wrapper</a> around it. It's very fast, and can be accessed concurrently.</p>
2
2009-07-26T15:28:23Z
[ "python", "nltk" ]
How to avoid computation every time a python module is reloaded
195,626
<p>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 doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.</p> <p>To give more information about my problem, </p> <pre><code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min </code></pre>
6
2008-10-12T15:59:48Z
2,213,775
<p>I'm going through this same issue... shelve, databases, etc... are all too slow for this type of problem. You'll need to take the hit once, insert it into an inmemory key/val store like Redis. It will just live there in memory (warning it could use up a good amount of memory so you may want a dedicated box). You'll never have to reload it and you'll just get looking in memory for keys</p> <pre><code>r = Redis() r.set(key, word) word = r.get(key) </code></pre>
1
2010-02-06T16:28:31Z
[ "python", "nltk" ]
What's the easiest way/best tutorials to get familiar with SQLAlchemy?
195,771
<p>What are best resources/tutorials for starting up with SQLAlchemy? Maybe some simple step by step stuff like creating a simple table and using it and going up from there.</p>
3
2008-10-12T17:49:09Z
195,784
<p>Personally, I'd buy <a href="http://oreilly.com/catalog/9780596516147/">this book</a> and cram it into the noggin over the course of a week or so.</p> <p>I've tried tackling SQLAlchemy on the job without learning the details first. I had a hard time with it, because I found the online documentation to be sparse and cryptic ("<em>read the source for more info...</em>"). SA also provides several levels of abstraction at which you can work and I wasn't confident that I was ever working at the correct level.</p>
5
2008-10-12T18:00:02Z
[ "python", "sqlalchemy" ]
What's the easiest way/best tutorials to get familiar with SQLAlchemy?
195,771
<p>What are best resources/tutorials for starting up with SQLAlchemy? Maybe some simple step by step stuff like creating a simple table and using it and going up from there.</p>
3
2008-10-12T17:49:09Z
196,072
<p>Probably the <a href="http://www.sqlalchemy.org/docs/04/ormtutorial.html" rel="nofollow" title="SQLAlchemy ORM Tutorial">SQLAlchemy ORM Tutorial</a>? I started with it.</p>
3
2008-10-12T21:00:05Z
[ "python", "sqlalchemy" ]
What's the easiest way/best tutorials to get familiar with SQLAlchemy?
195,771
<p>What are best resources/tutorials for starting up with SQLAlchemy? Maybe some simple step by step stuff like creating a simple table and using it and going up from there.</p>
3
2008-10-12T17:49:09Z
720,386
<p><a href="http://www.ibm.com/developerworks/aix/library/au-sqlalchemy/" rel="nofollow">Using SQLAlchemy</a> (IBM developerWorks)</p>
1
2009-04-06T06:32:56Z
[ "python", "sqlalchemy" ]
MySQLdb execute timeout
196,217
<p>Sometimes in our production environment occurs situation when connection between service (which is python program that uses MySQLdb) and mysql server is flacky, some packages are lost, some black magic happens and .execute() of MySQLdb.Cursor object never ends (or take great amount of time to end). </p> <p>This is very bad because it is waste of service worker threads. Sometimes it leads to exhausting of workers pool and service stops responding at all.</p> <p>So the question is: Is there a way to interrupt MySQLdb.Connection.execute operation after given amount of time?</p>
2
2008-10-12T22:27:58Z
196,308
<p>if the communication is such a problem, consider writing a 'proxy' that receives your SQL commands over the flaky connection and relays them to the MySQL server on a reliable channel (maybe running on the same box as the MySQL server). This way you have total control over failure detection and retrying.</p>
2
2008-10-12T23:45:47Z
[ "python", "mysql", "timeout" ]
MySQLdb execute timeout
196,217
<p>Sometimes in our production environment occurs situation when connection between service (which is python program that uses MySQLdb) and mysql server is flacky, some packages are lost, some black magic happens and .execute() of MySQLdb.Cursor object never ends (or take great amount of time to end). </p> <p>This is very bad because it is waste of service worker threads. Sometimes it leads to exhausting of workers pool and service stops responding at all.</p> <p>So the question is: Is there a way to interrupt MySQLdb.Connection.execute operation after given amount of time?</p>
2
2008-10-12T22:27:58Z
196,891
<p>You need to analyse exactly what the problem is. MySQL connections should eventually timeout if the server is gone; TCP keepalives are generally enabled. You may be able to tune the OS-level TCP timeouts.</p> <p>If the database is "flaky", then you definitely need to investigate how. It seems unlikely that the database really is the problem, more likely that networking in between is.</p> <p>If you are using (some) stateful firewalls of any kind, it's possible that they're losing some of the state, thus causing otherwise good long-lived connections to go dead.</p> <p>You might want to consider changing the idle timeout parameter in MySQL; otherwise, a long-lived, unused connection may go "stale", where the server and client both think it's still alive, but some stateful network element in between has "forgotten" about the TCP connection. An application trying to use such a "stale" connection will have a long wait before receiving an error (but it should eventually).</p>
1
2008-10-13T06:57:13Z
[ "python", "mysql", "timeout" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
196,360
<p>You could use the regular expression library which accepts the Posix standard [[:ASCII:]] definition.</p>
2
2008-10-13T00:18:25Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
196,391
<p>I think you are not asking the right question--</p> <p>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 need to go for an answer.</p> <p>Perhaps the question you can ask is: "Is this string the result of encoding a unicode string in ascii?" -- This you can answer by trying:</p> <pre><code>try: mystring.decode('ascii') except UnicodeDecodeError: print "it was not a ascii-encoded unicode string" else: print "It may have been an ascii-encoded unicode string" </code></pre>
189
2008-10-13T00:30:32Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
196,392
<pre><code>def is_ascii(s): return all(ord(c) &lt; 128 for c in s) </code></pre>
78
2008-10-13T00:30:43Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
198,205
<p>How about doing this?</p> <pre><code>import string def isAscii(s): for c in s: if c not in string.ascii_letters: return False return True </code></pre>
10
2008-10-13T16:38:25Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
200,267
<p>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.</p> <p>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 points; numbers from 0-1112064. But you appear to be interested in the character é, which (in your terminal) is a multi-byte sequence that represents a single character.</p> <p>Instead of <code>ord(u'é')</code>, try this:</p> <pre><code>&gt;&gt;&gt; [ord(x) for x in u'é'] </code></pre> <p>That tells you which sequence of code points "é" represents. It may give you [233], or it may give you [101, 770].</p> <p>Instead of <code>chr()</code> to reverse this, there is <code>unichr()</code>:</p> <pre><code>&gt;&gt;&gt; unichr(233) u'\xe9' </code></pre> <p>This character may actually be represented either a single or multiple unicode "code points", which themselves represent either graphemes or characters. It's either "e with an acute accent (i.e., code point 233)", or "e" (code point 101), followed by "an acute accent on the previous character" (code point 770). So this exact same character may be presented as the Python data structure <code>u'e\u0301'</code> or <code>u'\u00e9'</code>.</p> <p>Most of the time you shouldn't have to care about this, but it can become an issue if you are iterating over a unicode string, as iteration works by code point, not by decomposable character. In other words, <code>len(u'e\u0301') == 2</code> and <code>len(u'\u00e9') == 1</code>. If this matters to you, you can convert between composed and decomposed forms by using <a href="http://docs.python.org/library/unicodedata.html#unicodedata.normalize"><code>unicodedata.normalize</code></a>.</p> <p><a href="http://unicode.org/glossary/">The Unicode Glossary</a> can be a helpful guide to understanding some of these issues, by pointing how how each specific term refers to a different part of the representation of text, which is far more complicated than many programmers realize.</p>
16
2008-10-14T07:36:59Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
200,311
<p>A sting (<code>str</code>-type) in Python is a series of bytes. There is <strong>no way</strong> of telling just from looking at the string whether this series of bytes represent an ascii string, a string in a 8-bit charset like ISO-8859-1 or a string encoded with UTF-8 or UTF-16 or whatever.</p> <p>However if you know the encoding used, then you can <code>decode</code> the str into a unicode string and then use a regular expression (or a loop) to check if it contains characters outside of the range you are concerned about.</p>
2
2008-10-14T07:58:08Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
3,296,808
<p>I use the following to determine if the string is ascii or unicode:</p> <pre><code>&gt;&gt; print 'test string'.__class__.__name__ str &gt;&gt;&gt; print u'test string'.__class__.__name__ unicode &gt;&gt;&gt; </code></pre> <p>Then just use a conditional block to define the function:</p> <pre><code>def is_ascii(input): if input.__class__.__name__ == "str": return True return False </code></pre>
-2
2010-07-21T06:34:56Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
6,988,354
<p>Ran into something like this recently - for future reference</p> <pre><code>import chardet encoding = chardet.detect(string) if encoding['encoding'] == 'ascii': print 'string is in ascii' </code></pre> <p>which you could use with:</p> <pre><code>string_ascii = string.decode(encoding['encoding']).encode('ascii') </code></pre>
16
2011-08-08T20:47:22Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
12,064,457
<p>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).</p> <p>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). <a href="http://stackoverflow.com/a/4987367/727541">This answer was very helpful and got to the real root of my issues.</a></p> <p>If you're getting a rude and persistent</p> <blockquote> <p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 263: ordinal not in range(128)</p> </blockquote> <p>particularly when you're ENCODING, make sure you're not trying to unicode() a string that already IS unicode- for some terrible reason, you get ascii codec errors. (See also the <a href="http://packages.python.org/kitchen/unicode-frustrations.html">Python Kitchen recipe</a>, and the <a href="http://docs.python.org/howto/unicode.html">Python docs</a> tutorials for better understanding of how terrible this can be.)</p> <p>Eventually I determined that what I wanted to do was this:</p> <pre><code>escaped_string = unicode(original_string.encode('ascii','xmlcharrefreplace')) </code></pre> <p>Also helpful in debugging was setting the default coding in my file to utf-8 (put this at the beginning of your python file):</p> <pre><code># -*- coding: utf-8 -*- </code></pre> <p>That allows you to test special characters ('àéç') without having to use their unicode escapes (u'\xe0\xe9\xe7').</p> <pre><code>&gt;&gt;&gt; specials='àéç' &gt;&gt;&gt; specials.decode('latin-1').encode('ascii','xmlcharrefreplace') '&amp;#224;&amp;#233;&amp;#231;' </code></pre>
7
2012-08-21T23:24:35Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
17,516,466
<p>To prevent your code from crashes, you maybe want to use a <code>try-except</code> to catch <code>TypeErrors</code></p> <pre><code>&gt;&gt;&gt; ord("¶") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: ord() expected a character, but string of length 2 found </code></pre> <p>For example </p> <pre><code>def is_ascii(s): try: return all(ord(c) &lt; 128 for c in s) except TypeError: return False </code></pre>
0
2013-07-07T21:16:00Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
18,403,812
<p>Python 3 way:</p> <pre><code>isascii = lambda s: len(s) == len(s.encode()) </code></pre>
31
2013-08-23T13:14:49Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
30,392,263
<p>To improve Alexander's solution from the Python 2.6 (and in Python 3.x) you can use helper module curses.ascii and use curses.ascii.isascii() function or various other: <a href="https://docs.python.org/2.6/library/curses.ascii.html" rel="nofollow">https://docs.python.org/2.6/library/curses.ascii.html</a></p> <pre><code>from curses import ascii def isascii(s): return all(ascii.isascii(c) for c in s) </code></pre>
2
2015-05-22T08:48:46Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
32,357,552
<p>Vincent Marchetti has the right idea, but <code>str.decode</code> has been deprecated in Python 3. In Python 3 you can make the same test with <code>str.encode</code>:</p> <pre><code>try: mystring.encode('ascii') except UnicodeEncodeError: pass # string is not ascii else: pass # string is ascii </code></pre> <p>Note the exception you want to catch has also changed from <code>UnicodeDecodeError</code> to <code>UnicodeEncodeError</code>.</p>
3
2015-09-02T15:45:04Z
[ "python", "string", "unicode", "ascii" ]
How to check if a string in Python is in ASCII?
196,345
<p>I want to I check whether a string is in ASCII or not.</p> <p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord"><code>ord()</code>'s documentation</a>). </p> <p>Is there another way to check?</p>
120
2008-10-13T00:13:40Z
32,869,248
<pre><code>import re def is_ascii(s): return bool(re.match(r'[\x00-\x7F]+$', s)) </code></pre> <p>To include an empty string as ASCII, change the <code>+</code> to <code>*</code>.</p>
0
2015-09-30T14:51:52Z
[ "python", "string", "unicode", "ascii" ]
How can I search through Stack Overflow questions from a script?
196,755
<p>Given a string of keywords, such as "Python best practices", I would like to obtain the first 10 Stack Overflow questions that contain that keywords, sorted by relevance (?), say from a Python script. My goal is to end up with a list of tuples (title, URL).</p> <p>How can I accomplish this? Would you consider querying Google instead? (How would you do it from Python?)</p>
3
2008-10-13T05:03:47Z
196,758
<p>You could screen scrape the returned HTML from a valid HTTP request. But that would result in bad karma, and the loss of the ability to enjoy a good night's sleep.</p>
1
2008-10-13T05:09:04Z
[ "python", "search", "scripting", "stackexchange-api" ]
How can I search through Stack Overflow questions from a script?
196,755
<p>Given a string of keywords, such as "Python best practices", I would like to obtain the first 10 Stack Overflow questions that contain that keywords, sorted by relevance (?), say from a Python script. My goal is to end up with a list of tuples (title, URL).</p> <p>How can I accomplish this? Would you consider querying Google instead? (How would you do it from Python?)</p>
3
2008-10-13T05:03:47Z
196,763
<p>Since Stackoverflow already has this feature you just need to get the contents of the search results page and scrape the information you need. Here is the URL for a search by relevance:</p> <blockquote> <p><a href="http://stackoverflow.com/search?q=python+best+practices&amp;sort=relevance">http://stackoverflow.com/search?q=python+best+practices&amp;sort=relevance</a></p> </blockquote> <p>If you View Source, you'll see that the information you need for each question is on a line like this:</p> <pre><code>&lt;h3&gt;&lt;a href="/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150" class="answer-title"&gt;What are the best RSS feeds for programmers/developers?&lt;/a&gt;&lt;/h3&gt; </code></pre> <p>So you should be able to get the first ten by doing a regex search for a string of that form.</p>
5
2008-10-13T05:11:39Z
[ "python", "search", "scripting", "stackexchange-api" ]
How can I search through Stack Overflow questions from a script?
196,755
<p>Given a string of keywords, such as "Python best practices", I would like to obtain the first 10 Stack Overflow questions that contain that keywords, sorted by relevance (?), say from a Python script. My goal is to end up with a list of tuples (title, URL).</p> <p>How can I accomplish this? Would you consider querying Google instead? (How would you do it from Python?)</p>
3
2008-10-13T05:03:47Z
196,780
<p>Suggest that a REST API be added to SO. <a href="http://stackoverflow.uservoice.com" rel="nofollow">http://stackoverflow.uservoice.com/</a></p>
1
2008-10-13T05:28:47Z
[ "python", "search", "scripting", "stackexchange-api" ]
How can I search through Stack Overflow questions from a script?
196,755
<p>Given a string of keywords, such as "Python best practices", I would like to obtain the first 10 Stack Overflow questions that contain that keywords, sorted by relevance (?), say from a Python script. My goal is to end up with a list of tuples (title, URL).</p> <p>How can I accomplish this? Would you consider querying Google instead? (How would you do it from Python?)</p>
3
2008-10-13T05:03:47Z
196,800
<p>I would just use Pycurl to concatenate the search terms onto the query uri.</p>
0
2008-10-13T05:46:01Z
[ "python", "search", "scripting", "stackexchange-api" ]
How can I search through Stack Overflow questions from a script?
196,755
<p>Given a string of keywords, such as "Python best practices", I would like to obtain the first 10 Stack Overflow questions that contain that keywords, sorted by relevance (?), say from a Python script. My goal is to end up with a list of tuples (title, URL).</p> <p>How can I accomplish this? Would you consider querying Google instead? (How would you do it from Python?)</p>
3
2008-10-13T05:03:47Z
196,851
<pre><code>&gt;&gt;&gt; from urllib import urlencode &gt;&gt;&gt; params = urlencode({'q': 'python best practices', 'sort': 'relevance'}) &gt;&gt;&gt; params 'q=python+best+practices&amp;sort=relevance' &gt;&gt;&gt; from urllib2 import urlopen &gt;&gt;&gt; html = urlopen("http://stackoverflow.com/search?%s" % params).read() &gt;&gt;&gt; import re &gt;&gt;&gt; links = re.findall(r'&lt;h3&gt;&lt;a href="([^"]*)" class="answer-title"&gt;([^&lt;]*)&lt;/a&gt;&lt;/h3&gt;', html) &gt;&gt;&gt; links [('/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150', 'What are the best RSS feeds for programmers/developers?'), ('/questions/3088/best-ways-to-teach-a-beginner-to-program#13185', 'Best ways to teach a beginner to program?'), ('/questions/13678/textual-versus-graphical-programming-languages#13886', 'Textual versus Graphical Programming Languages'), ('/questions/58968/what-defines-pythonian-or-pythonic#59877', 'What defines &amp;#8220;pythonian&amp;#8221; or &amp;#8220;pythonic&amp;#8221;?'), ('/questions/592/cxoracle-how-do-i-access-oracle-from-python#62392', 'cx_Oracle - How do I access Oracle from Python? '), ('/questions/7170/recommendation-for-straight-forward-python-frameworks#83608', 'Recommendation for straight-forward python frameworks'), ('/questions/100732/why-is-if-not-someobj-better-than-if-someobj-none-in-python#100903', 'Why is if not someobj: better than if someobj == None: in Python?'), ('/questions/132734/presentations-on-switching-from-perl-to-python#134006', 'Presentations on switching from Perl to Python'), ('/questions/136977/after-c-python-or-java#138442', 'After C++ - Python or Java?')] &gt;&gt;&gt; from urlparse import urljoin &gt;&gt;&gt; links = [(urljoin('http://stackoverflow.com/', url), title) for url,title in links] &gt;&gt;&gt; links [('http://stackoverflow.com/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150', 'What are the best RSS feeds for programmers/developers?'), ('http://stackoverflow.com/questions/3088/best-ways-to-teach-a-beginner-to-program#13185', 'Best ways to teach a beginner to program?'), ('http://stackoverflow.com/questions/13678/textual-versus-graphical-programming-languages#13886', 'Textual versus Graphical Programming Languages'), ('http://stackoverflow.com/questions/58968/what-defines-pythonian-or-pythonic#59877', 'What defines &amp;#8220;pythonian&amp;#8221; or &amp;#8220;pythonic&amp;#8221;?'), ('http://stackoverflow.com/questions/592/cxoracle-how-do-i-access-oracle-from-python#62392', 'cx_Oracle - How do I access Oracle from Python? '), ('http://stackoverflow.com/questions/7170/recommendation-for-straight-forward-python-frameworks#83608', 'Recommendation for straight-forward python frameworks'), ('http://stackoverflow.com/questions/100732/why-is-if-not-someobj-better-than-if-someobj-none-in-python#100903', 'Why is if not someobj: better than if someobj == None: in Python?'), ('http://stackoverflow.com/questions/132734/presentations-on-switching-from-perl-to-python#134006', 'Presentations on switching from Perl to Python'), ('http://stackoverflow.com/questions/136977/after-c-python-or-java#138442', 'After C++ - Python or Java?')] </code></pre> <p>Converting this to a function should be trivial.</p> <p><strong>EDIT</strong>: Heck, I'll do it...</p> <pre><code>def get_stackoverflow(query): import urllib, urllib2, re, urlparse params = urllib.urlencode({'q': query, 'sort': 'relevance'}) html = urllib2.urlopen("http://stackoverflow.com/search?%s" % params).read() links = re.findall(r'&lt;h3&gt;&lt;a href="([^"]*)" class="answer-title"&gt;([^&lt;]*)&lt;/a&gt;&lt;/h3&gt;', html) links = [(urlparse.urljoin('http://stackoverflow.com/', url), title) for url,title in links] return links </code></pre>
5
2008-10-13T06:33:02Z
[ "python", "search", "scripting", "stackexchange-api" ]
What is the best way to escape Python strings in PHP?
196,771
<p>I have a PHP application which needs to output a python script, more specifically a bunch of variable assignment statements, eg.</p> <pre><code>subject_prefix = 'This String From User Input' msg_footer = """This one too.""" </code></pre> <p>The contents of subject_prefix et al need to be written to take user input; as such, I need to escape the contents of the strings. Writing something like the following isn't going to cut it; we're stuffed as soon as someone uses a quote or newline or anything else that I'm not aware of that could be hazardous:</p> <pre><code>echo "subject_prefix = '".$subject_prefix."'\n"; </code></pre> <p>So. Any ideas?</p> <p>(Rewriting the app in Python isn't possible due to time constraints. :P )</p> <p><strong>Edit, years later:</strong></p> <p>This was for integration between a web-app (written in PHP) and Mailman (written in Python). I couldn't modify the install of the latter, so I needed to come up with a way to talk in its language to manage its configuration.</p> <p>This was also a <em>really</em> bad idea.</p>
2
2008-10-13T05:20:56Z
196,783
<p>I suggest writing a function that will take two arguments: the text to be escaped and the type of quotes the string is in. Then, for example, if the type of quotes are single quotes, the function will escape the single quotes in the string and any other characters that need to be escaped (backslash?).</p> <pre><code>function escape_string($text, $type) { // Escape backslashes for all types of strings? $text = str_replace('\\', '\\\\', $text); switch($type) { case 'single': $text = str_replace("'", "\\'", $text); break; case 'double': $text = str_replace('"', '\\"', $text); break; // etc... } return $text; } </code></pre> <p>I'm assuming that for single-quoted strings you want to escape the single quotes, and with double-quoted strings you want to escape the double quotes...</p>
-2
2008-10-13T05:30:00Z
[ "php", "python", "user-input" ]
What is the best way to escape Python strings in PHP?
196,771
<p>I have a PHP application which needs to output a python script, more specifically a bunch of variable assignment statements, eg.</p> <pre><code>subject_prefix = 'This String From User Input' msg_footer = """This one too.""" </code></pre> <p>The contents of subject_prefix et al need to be written to take user input; as such, I need to escape the contents of the strings. Writing something like the following isn't going to cut it; we're stuffed as soon as someone uses a quote or newline or anything else that I'm not aware of that could be hazardous:</p> <pre><code>echo "subject_prefix = '".$subject_prefix."'\n"; </code></pre> <p>So. Any ideas?</p> <p>(Rewriting the app in Python isn't possible due to time constraints. :P )</p> <p><strong>Edit, years later:</strong></p> <p>This was for integration between a web-app (written in PHP) and Mailman (written in Python). I couldn't modify the install of the latter, so I needed to come up with a way to talk in its language to manage its configuration.</p> <p>This was also a <em>really</em> bad idea.</p>
2
2008-10-13T05:20:56Z
196,790
<p>I'd start by standardizing the string type I was using in python, to use triple-quoted strings ("""). This should reduce the incidents of problems from stray quotes in the input. You'll still need to escape it of course, but it should reduce the number of issues that are a concern.</p> <p>What I did to escape the strings would somewhat depend on what I'm worried about getting slipped in, and the context that they are getting printed out again. If you're just worried about quotes causing problems, you could simply check for and occurrences of """ and escape them. On the other hand if I was worried about the input itself being malicious (and it's user input, so you probably should), then I would look at options like strip_tags() or other similar functions.</p>
0
2008-10-13T05:34:47Z
[ "php", "python", "user-input" ]
What is the best way to escape Python strings in PHP?
196,771
<p>I have a PHP application which needs to output a python script, more specifically a bunch of variable assignment statements, eg.</p> <pre><code>subject_prefix = 'This String From User Input' msg_footer = """This one too.""" </code></pre> <p>The contents of subject_prefix et al need to be written to take user input; as such, I need to escape the contents of the strings. Writing something like the following isn't going to cut it; we're stuffed as soon as someone uses a quote or newline or anything else that I'm not aware of that could be hazardous:</p> <pre><code>echo "subject_prefix = '".$subject_prefix."'\n"; </code></pre> <p>So. Any ideas?</p> <p>(Rewriting the app in Python isn't possible due to time constraints. :P )</p> <p><strong>Edit, years later:</strong></p> <p>This was for integration between a web-app (written in PHP) and Mailman (written in Python). I couldn't modify the install of the latter, so I needed to come up with a way to talk in its language to manage its configuration.</p> <p>This was also a <em>really</em> bad idea.</p>
2
2008-10-13T05:20:56Z
196,964
<p>Another option may be to export the data as array or object as JSON string and modify the python code slightly to handle the new input. While the escaping via JSON is not 100% bulletproof it will be still better than own escaping routines.</p> <p>And you'll be able to handle errors if the JSON string is malformatted.</p> <p>There's a package for Python to encode and decode JSON: <a href="http://pypi.python.org/pypi/python-json/" rel="nofollow">python-json 3.4</a></p>
0
2008-10-13T07:57:21Z
[ "php", "python", "user-input" ]
What is the best way to escape Python strings in PHP?
196,771
<p>I have a PHP application which needs to output a python script, more specifically a bunch of variable assignment statements, eg.</p> <pre><code>subject_prefix = 'This String From User Input' msg_footer = """This one too.""" </code></pre> <p>The contents of subject_prefix et al need to be written to take user input; as such, I need to escape the contents of the strings. Writing something like the following isn't going to cut it; we're stuffed as soon as someone uses a quote or newline or anything else that I'm not aware of that could be hazardous:</p> <pre><code>echo "subject_prefix = '".$subject_prefix."'\n"; </code></pre> <p>So. Any ideas?</p> <p>(Rewriting the app in Python isn't possible due to time constraints. :P )</p> <p><strong>Edit, years later:</strong></p> <p>This was for integration between a web-app (written in PHP) and Mailman (written in Python). I couldn't modify the install of the latter, so I needed to come up with a way to talk in its language to manage its configuration.</p> <p>This was also a <em>really</em> bad idea.</p>
2
2008-10-13T05:20:56Z
200,315
<p><strong>Do not</strong> try write this function in PHP. You will inevitably get it wrong and your application will inevitably have an arbitrary remote execution exploit.</p> <p>First, consider what problem you are actually solving. I presume you are just trying to get data from PHP to Python. You might try to write a .ini file rather than a .py file. Python has an excellent ini syntax parser, <a href="http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html" rel="nofollow">ConfigParser</a>. You can write the obvious, and potentially incorrect, quoting function in PHP and nothing serious will happen if (read: when) you get it wrong.</p> <p>You could also write an XML file. There are too many XML parsers and emitters for PHP and Python for me to even list here.</p> <p>If I <strong>really</strong> can't convince you that this is a <em>terrible, terrible</em> idea, then you can at least use the pre-existing function that Python has for doing such a thing: <code>repr()</code>.</p> <p>Here's a handy PHP function which will run a Python script to do this for you:</p> <pre><code>&lt;?php function py_escape($input) { $descriptorspec = array( 0 =&gt; array("pipe", "r"), 1 =&gt; array("pipe", "w") ); $process = proc_open( "python -c 'import sys; sys.stdout.write(repr(sys.stdin.read()))'", $descriptorspec, $pipes); fwrite($pipes[0], $input); fclose($pipes[0]); $chunk_size = 8192; $escaped = fread($pipes[1], $chunk_size); if (strlen($escaped) == $chunk_size) { // This is important for security. die("That string's too big.\n"); } proc_close($process); return $escaped; } // Example usage: $x = "string \rfull \nof\t crappy stuff"; print py_escape($x); </code></pre> <p>The <code>chunk_size</code> check is intended to prevent an attack whereby your input ends up being two really long strings, which look like <code>("hello " + ("." * chunk_size))</code> and <code>'; os.system("do bad stuff")</code> respectively. Now, that naive attack won't work exactly, because Python won't let a single-quoted string end in the middle of a line, and those quotes in the <code>system()</code> call will themselves be quoted, but if the attacker manages to get a line continuation ("\") into the right place and use something like <code>os.system(map(chr, ...))</code> then they can inject some code that will run.</p> <p>I opted to simply read one chunk and give up if there was more output, rather than continuing to read and accumulate, because there are also limits on Python source file line length; for all I know, that could be another attack vector. Python is not intended to be secure against arbitrary people writing arbitrary source code on your system so this area is unlikely to be audited.</p> <p>The fact that I had to think of all this for this trivial example is just another example of why you shouldn't use python source code as a data interchange format.</p>
2
2008-10-14T07:58:38Z
[ "php", "python", "user-input" ]