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
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
286
2008-09-14T05:41:11Z
62,527
<p>For a file <code>module.py</code>, the unit test should normally be called <code>test_module.py</code>, following Pythonic naming conventions.</p> <p>There are several commonly accepted places to put <code>test_module.py</code>:</p> <ol> <li>In the same directory as <code>module.py</code>.</li> <li>In <code>../tests/test_module.py</code> (at the same level as the code directory).</li> <li>In <code>tests/test_module.py</code> (one level under the code directory).</li> </ol> <p>I prefer #1 for its simplicity of finding the tests and importing them. Whatever build system you're using can easily be configured to run files starting with <code>test_</code>. Actually, the <a href="https://docs.python.org/library/unittest.html#test-discovery">default <code>unittest</code> pattern used for test discovery is <code>test*.py</code></a>.</p>
102
2008-09-15T12:52:00Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
286
2008-09-14T05:41:11Z
63,645
<p>When writing a package called "foo", I will put unit tests into a separate package "foo_test". Modules and subpackages will then have the same name as the SUT package module. E.g. tests for a module foo.x.y are found in foo_test.x.y. The __init__.py files of each testing package then contain an AllTests suite that includes all test suites of the package. setuptools provides a convenient way to specify the main testing package, so that after "python setup.py develop" you can just use "python setup.py test" or "python setup.py test -s foo_test.x.SomeTestSuite" to the just a specific suite.</p>
0
2008-09-15T14:56:35Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
286
2008-09-14T05:41:11Z
77,145
<p>If the tests are simple, simply put them in the docstring -- most of the test frameworks for Python will be able to use that:</p> <pre><code>&gt;&gt;&gt; import module &gt;&gt;&gt; module.method('test') 'testresult' </code></pre> <p>For other more involved tests, I'd put them either in <code>../tests/test_module.py</code> or in <code>tests/test_module.py</code>.</p>
0
2008-09-16T21:10:12Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
286
2008-09-14T05:41:11Z
103,610
<p>I also tend to put my unit tests in the file itself, as Jeremy Cantrell above notes, although I tend to not put the test function in the main body, but rather put everything in an</p> <pre><code>if __name__ == '__main__': do tests... </code></pre> <p>block. This ends up adding documentation to the file as 'example code' for how to use the python file you are testing.</p> <p>I should add, I tend to write very tight modules/classes. If your modules require very large numbers of tests, you can put them in another, but even then, I'd still add:</p> <pre><code>if __name__ == '__main__': import tests.thisModule tests.thisModule.runtests </code></pre> <p>This lets anybody reading your source code know where to look for the test code.</p>
18
2008-09-19T16:46:53Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
286
2008-09-14T05:41:11Z
128,616
<p>We use </p> <p>app/src/code.py</p> <p>app/testing/code_test.py </p> <p>app/docs/..</p> <p>In each test file we insert "../src/" in sys.path. It's not the nicest solution but works. I think it would be great if someone came up w/ something like maven in java that gives you standard conventions that just work, no matter what project you work on.</p>
1
2008-09-24T17:44:16Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
286
2008-09-14T05:41:11Z
382,596
<p>I prefer toplevel tests directory. This does mean imports become a little more difficult. For that I have two solutions:</p> <ol> <li>Use setuptools. Then you can pass <code>test_suite='tests.runalltests.suite'</code> into <code>setup()</code>, and can run the tests simply: <code>python setup.py test</code></li> <li>Set PYTHONPATH when running the tests: <code>PYTHONPATH=. python tests/runalltests.py</code></li> </ol> <p>Here's how that stuff is supported by code in M2Crypto:</p> <ul> <li><a href="http://svn.osafoundation.org/m2crypto/trunk/setup.py" rel="nofollow">http://svn.osafoundation.org/m2crypto/trunk/setup.py</a></li> <li><a href="http://svn.osafoundation.org/m2crypto/trunk/tests/alltests.py" rel="nofollow">http://svn.osafoundation.org/m2crypto/trunk/tests/alltests.py</a></li> </ul> <p>If you prefer to run tests with nosetests you might need do something a little different.</p>
2
2008-12-19T23:48:07Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
286
2008-09-14T05:41:11Z
815,212
<p>We had the very same question when writing Pythoscope (<a href="http://pythoscope.org">http://pythoscope.org</a>), which generates unit tests for Python programs. We polled people on the testing in python list before we chose a directory, there were many different opinions. In the end we chose to put a "tests" directory in the same directory as the source code. In that directory we generate a test file for each module in the parent directory. </p>
23
2009-05-02T17:08:05Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
286
2008-09-14T05:41:11Z
2,363,162
<p>How I do it...</p> <p>Folder structure:</p> <pre><code>project/ src/ code.py tests/ setup.py </code></pre> <p>Setup.py points to src/ as the location containing my projects modules, then i run:</p> <pre><code>setup.py develop </code></pre> <p>Which adds my project into site-packages, pointing to my working copy. To run my tests i use:</p> <pre><code>setup.py tests </code></pre> <p>Using whichever test runner I've configured.</p>
4
2010-03-02T12:50:51Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
286
2008-09-14T05:41:11Z
22,704,148
<p>From my experience in developing Testing frameworks in Python, I would suggest to put python unit tests in a separate directory. Maintain a symmetric directory structure. This would be helpful in packaging just the core libraries and not package the unit tests. Below is implemented through a schematic diagram. </p> <pre><code> &lt;Main Package&gt; / \ / \ lib tests / \ [module1.py, module2.py, [ut_module1.py, ut_module2.py, module3.py module4.py, ut_module3.py, ut_module.py] __init__.py] </code></pre> <p>In this way when you package these libraries using an rpm, you can just package the main library modules (only). This helps maintainability particularly in agile environment. </p>
4
2014-03-28T04:22:38Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
286
2008-09-14T05:41:11Z
23,386,287
<h2>Only 1 test file</h2> <p>If doesn't have many test file, put in top-level directory is nice (I think this is python recommended way):</p> <pre><code>module/ lib/ __init__.py module.py test.py </code></pre> <h2>Many test file</h2> <p>If has many test file, put in a <code>tests</code> folder:</p> <pre><code>module/ lib/ __init__.py module.py tests/ test_module.py test_module2.py </code></pre> <p>but if put the tests in <code>tests</code> folder, test can't <code>import ..lib</code> in CLI because <code>__main__</code> can't import relative module, we can use <a href="https://nose.readthedocs.org/en/latest/"><kbd>nose</kbd></a>, or we can add parent directory to python import path, for that I will create a</p> <h3>env.py</h3> <pre><code>import sys import os # append module root directory to sys.path sys.path.append( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) ) </code></pre> <p>in</p> <pre><code>module/ tests/ test_module.py env.py </code></pre> <p>and <code>import env</code> before test import module</p> <h3>test_module.py</h3> <pre><code>import unittest # append parent directory to import path import env # now we can import the lib module from lib import module if __name__ == '__main__': unittest.main() </code></pre>
18
2014-04-30T10:58:51Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
286
2008-09-14T05:41:11Z
37,122,327
<p>I recommend you check some main Python projects on GitHub and get some ideas.</p> <p>When your code gets larger and you add more libraries it's better to create a test folder in the same directory you have setup.py and mirror your project directory structure for each test type (unittest, integration, ...)</p> <p>For example if you have a directory structure like:</p> <pre><code>myPackage/ myapp/ moduleA/ __init__.py module_A.py moduleB/ __init__.py module_B.py setup.py </code></pre> <p>After adding test folder you will have a directory structure like:</p> <pre><code>myPackage/ myapp/ moduleA/ __init__.py module_A.py moduleB/ __init__.py module_B.py test/ unit/ myapp/ moduleA/ module_A_test.py moduleB/ module_B_test.py integration/ myapp/ moduleA/ module_A_test.py moduleB/ module_B_test.py setup.py </code></pre> <p>Many properly written Python packages uses the same structure. A very good example is the Boto package. Check <a href="https://github.com/boto/boto" rel="nofollow">https://github.com/boto/boto</a></p>
2
2016-05-09T17:54:13Z
[ "python", "unit-testing", "code-organization" ]
Where do the Python unit tests go?
61,151
<p>If you're writing a library, or an app, where do the unit test files go? </p> <p>It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. </p> <p>Is there a best practice here?</p>
286
2008-09-14T05:41:11Z
39,740,835
<p>Every once in a while I find myself checking out topic of test placement, and every time majority of recommends a separate folder structure beside the library code, but I find that every time arguments are the same and are not that convincing. I end up putting my test modules somewhere beside the core modules. </p> <p>The main reason for doing this is: <strong>refactoring</strong>.</p> <p>When I move things around i do want test modules to move with the code, it's easy to loose test if they are in separate tree. Let's be honest, sooner or later you end up with totally folder different structure, like <a href="https://github.com/django/django" rel="nofollow">django</a>, <a href="https://github.com/pallets/flask" rel="nofollow">flask</a> and many others. Which is fine if you don't care.</p> <p>The main question you should ask yourself is this: </p> <p>Am I writing: </p> <ul> <li>a) reusable library or </li> <li>b) building a project than bundles together some semi-separated modules?</li> </ul> <p>If a: </p> <p>A separate folder and extra effort to maintain it's structure maybe better suited. Noone will complain on your tests getting <em>deployed to production</em>. </p> <p>But it's also as easy to exclude tests from being distributed when they are mixed with the core folders, <a href="http://setuptools.readthedocs.io/en/latest/setuptools.html?highlight=find_packages#using-find-packages" rel="nofollow">put this in the setup.py</a>:</p> <pre><code>find_packages("src", exclude=["*.tests", "*.tests.*", "tests.*", "tests"]) </code></pre> <p>If b: </p> <p>You may wish — as every one of us do — that you are writing reusable libraries, but most of the time their life is tied to the life of the project. Ability to easily maintain your project should be a priority. </p> <p>Then if did a good job and your module is a good fit for another project, it will probably get copied — not forked or made into a separate library — into this new project, and moving tests that lay beside in he same folder structure is easy in comparison to fishing up tests in a mess that a separate test folder had become. (You may argue that its shouldn't be a mess in the fist place but let's be realistic here).</p> <p>So the choice is still yours, but I wold argue that you with mixed up tests you achieve all the same things, as with separate folder, but with less effort on keeping things tidy. </p>
0
2016-09-28T07:31:38Z
[ "python", "unit-testing", "code-organization" ]
Python dictionary from an object's fields
61,517
<p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p> <pre><code>&gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } </code></pre> <p><strong>NOTE:</strong> It should not include methods. Only fields.</p> <p>Thanks</p>
174
2008-09-14T18:00:43Z
61,522
<p>The <code>dir</code> builtin will give you all the object's attributes, including special methods like <code>__str__</code>, <code>__dict__</code> and a whole bunch of others which you probably don't want. But you can do something like:</p> <pre><code>&gt;&gt;&gt; class Foo(object): ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; [name for name in dir(f) if not name.startswith('__')] [ 'bar', 'baz' ] &gt;&gt;&gt; dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__')) { 'bar': 'hello', 'baz': 'world' } </code></pre> <p>So can extend this to only return data attributes and not methods, by defining your <code>props</code> function like this:</p> <pre><code>import inspect def props(obj): pr = {} for name in dir(obj): value = getattr(obj, name) if not name.startswith('__') and not inspect.ismethod(value): pr[name] = value return pr </code></pre>
45
2008-09-14T18:07:55Z
[ "python", "dictionary", "attributes", "object", "metaprogramming" ]
Python dictionary from an object's fields
61,517
<p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p> <pre><code>&gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } </code></pre> <p><strong>NOTE:</strong> It should not include methods. Only fields.</p> <p>Thanks</p>
174
2008-09-14T18:00:43Z
61,551
<p>I've settled with a combination of both answers:</p> <pre><code>dict((key, value) for key, value in f.__dict__.iteritems() if not callable(value) and not key.startswith('__')) </code></pre>
19
2008-09-14T18:50:52Z
[ "python", "dictionary", "attributes", "object", "metaprogramming" ]
Python dictionary from an object's fields
61,517
<p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p> <pre><code>&gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } </code></pre> <p><strong>NOTE:</strong> It should not include methods. Only fields.</p> <p>Thanks</p>
174
2008-09-14T18:00:43Z
62,680
<p>Note that best practice in current versions of Python is to use <i>new-style</i> classes, i.e.</p> <pre><code>class Foo(object): ... </code></pre> <p>Also, there's a difference between an 'object' and a 'class'. To build a dictionary from an arbitrary <i>object</i>, it's sufficient to use <code>__dict__</code>. Usually, you'll declare your methods at class level and your attributes at instance level, so <code>__dict__</code> should be fine. For example:</p> <pre><code>&gt;&gt;&gt; class A(object): ... def __init__(self): ... self.b = 1 ... self.c = 2 ... def do_nothing(self): ... pass ... &gt;&gt;&gt; a = A() &gt;&gt;&gt; a.__dict__ {'c': 2, 'b': 1} </code></pre> <p>Alternatively, depending on what you want to do, it might be nice to inherit from dict. Then your class is <em>already</em> a dictionary, and if you want you can override getattr and/or setattr to call through and set the dict. For example:</p> <pre><code> class Foo(dict): def __init__(self): pass def __getattr__(self, attr): return self[attr] # etc... </code></pre>
227
2008-09-15T13:08:56Z
[ "python", "dictionary", "attributes", "object", "metaprogramming" ]
Python dictionary from an object's fields
61,517
<p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p> <pre><code>&gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } </code></pre> <p><strong>NOTE:</strong> It should not include methods. Only fields.</p> <p>Thanks</p>
174
2008-09-14T18:00:43Z
63,635
<blockquote> <p>To build a dictionary from an arbitrary <i>object</i>, it's sufficient to use <code>__dict__</code>.</p> </blockquote> <p>This misses attributes that the object inherits from its class. For example,</p> <pre><code>class c(object): x = 3 a = c() </code></pre> <p>hasattr(a, 'x') is true, but 'x' does not appear in a.__dict__</p>
10
2008-09-15T14:56:01Z
[ "python", "dictionary", "attributes", "object", "metaprogramming" ]
Python dictionary from an object's fields
61,517
<p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p> <pre><code>&gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } </code></pre> <p><strong>NOTE:</strong> It should not include methods. Only fields.</p> <p>Thanks</p>
174
2008-09-14T18:00:43Z
17,470,565
<p>Late answer but provided for completeness and the benefit of googlers:</p> <pre><code>def props(x): return dict((key, getattr(x, key)) for key in dir(x) if key not in dir(x.__class__)) </code></pre> <p>This will not show methods defined in the class, but it will still show fields including those assigned to lambdas or those which start with a double underscore.</p>
5
2013-07-04T12:40:05Z
[ "python", "dictionary", "attributes", "object", "metaprogramming" ]
Python dictionary from an object's fields
61,517
<p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p> <pre><code>&gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } </code></pre> <p><strong>NOTE:</strong> It should not include methods. Only fields.</p> <p>Thanks</p>
174
2008-09-14T18:00:43Z
23,937,693
<p>I think the easiest way is to create a <strong>getitem</strong> attribute for the class. If you need to write to the object, you can create a custom <strong>setattr</strong> . Here is an example for <strong>getitem</strong>:</p> <pre><code>&gt;&gt;&gt; class A(object): ... def __init__(self): ... self.b = 1 ... self.c = 2 ... def __getitem__(self, item): ... return self.__dict__[item] ... &gt;&gt;&gt; a = A() &gt;&gt;&gt; a.__getitem__('b') </code></pre> <p><strong>dict</strong> generates the objects attributes into a dictionary and the dictionary object can be used to get the item you need.</p>
1
2014-05-29T16:02:23Z
[ "python", "dictionary", "attributes", "object", "metaprogramming" ]
Python dictionary from an object's fields
61,517
<p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p> <pre><code>&gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } </code></pre> <p><strong>NOTE:</strong> It should not include methods. Only fields.</p> <p>Thanks</p>
174
2008-09-14T18:00:43Z
29,333,136
<p>I thought I'd take some time to show you how you can translate an object to dict via <code>dict(obj)</code>.</p> <pre class="lang-py prettyprint-override"><code>class A(object): d = '4' e = '5' f = '6' def __init__(self): self.a = '1' self.b = '2' self.c = '3' def __iter__(self): # first start by grabbing the Class items iters = dict((x,y) for x,y in A.__dict__.items() if x[:2] != '__') # then update the class items with the instance items iters.update(self.__dict__) # now 'yield' through the items for x,y in iters.items(): yield x,y a = A() print(dict(a)) # prints "{'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4', 'f': '6'}" </code></pre> <p>The key section of this code is the <code>__iter__</code> function. </p> <p>As the comments explain, the first thing we do is grab the Class items and prevent anything that starts with '__'.</p> <p>Once you've created that <code>dict</code>, then you can use the <code>update</code> dict function and pass in the instance <code>__dict__</code>.</p> <p>These will give you a complete class+instance dictionary of members. Now all that's left is to iterate over them and yield the returns.</p> <p>Also, if you plan on using this a lot, you can create an <code>@iterable</code> class decorator.</p> <pre class="lang-py prettyprint-override"><code>def iterable(cls): def iterfn(self): iters = dict((x,y) for x,y in cls.__dict__.items() if x[:2] != '__') iters.update(self.__dict__) for x,y in iters.items(): yield x,y cls.__iter__ = iterfn return cls @iterable class B(object): d = 'd' e = 'e' f = 'f' def __init__(self): self.a = 'a' self.b = 'b' self.c = 'c' b = B() print(dict(b)) </code></pre>
2
2015-03-29T18:32:42Z
[ "python", "dictionary", "attributes", "object", "metaprogramming" ]
Python dictionary from an object's fields
61,517
<p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p> <pre><code>&gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } </code></pre> <p><strong>NOTE:</strong> It should not include methods. Only fields.</p> <p>Thanks</p>
174
2008-09-14T18:00:43Z
31,770,231
<p>Instead of <code>x.__dict__</code>, it's actually more pythonic to use <code>vars(x)</code>.</p>
14
2015-08-02T08:57:29Z
[ "python", "dictionary", "attributes", "object", "metaprogramming" ]
Python dictionary from an object's fields
61,517
<p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p> <pre><code>&gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } </code></pre> <p><strong>NOTE:</strong> It should not include methods. Only fields.</p> <p>Thanks</p>
174
2008-09-14T18:00:43Z
34,662,287
<p>If you want to list part of your attributes, override <code>__dict__</code>:</p> <pre><code>def __dict__(self): d = { 'attr_1' : self.attr_1, ... } return d # Call __dict__ d = instance.__dict__() </code></pre> <p>This helps a lot if your <code>instance</code> get some large block data and you want to push <code>d</code> to Redis like message queue. </p>
3
2016-01-07T18:14:45Z
[ "python", "dictionary", "attributes", "object", "metaprogramming" ]
Is it pythonic for a function to return multiple values?
61,605
<p>In python, you can have a function return multiple values. Here's a contrived example:</p> <pre><code>def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) </code></pre> <p>This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").</p> <p>When should you draw the line and define a different method? </p>
66
2008-09-14T20:15:19Z
61,629
<p>Firstly, note that Python allows for the following (no need for the parenthesis):</p> <pre><code>q, r = divide(22, 7) </code></pre> <p>Regarding your question, there's no hard and fast rule either way. For simple (and usually contrived) examples, it may seem that it's always possible for a given function to have a single purpose, resulting in a single value. However, when using Python for real-world applications, you quickly run into many cases where returning multiple values is necessary, and results in cleaner code.</p> <p>So, I'd say do whatever makes sense, and don't try to conform to an artificial convention. Python supports multiple return values, so use it when appropriate.</p>
24
2008-09-14T20:42:01Z
[ "python", "function", "return-value" ]
Is it pythonic for a function to return multiple values?
61,605
<p>In python, you can have a function return multiple values. Here's a contrived example:</p> <pre><code>def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) </code></pre> <p>This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").</p> <p>When should you draw the line and define a different method? </p>
66
2008-09-14T20:15:19Z
61,636
<p>Absolutely (for the example you provided).</p> <h3>Tuples are first class citizens in Python</h3> <p>There is a builtin function <a href="http://docs.python.org/lib/built-in-funcs.html"><code>divmod()</code></a> that does exactly that.</p> <pre><code>q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x </code></pre> <p>There are other examples: <code>zip</code>, <code>enumerate</code>, <code>dict.items</code>. </p> <pre><code>for i, e in enumerate([1, 3, 3]): print "index=%d, element=%s" % (i, e) # reverse keys and values in a dictionary d = dict((v, k) for k, v in adict.items()) # or d = dict(zip(adict.values(), adict.keys())) </code></pre> <p>BTW, parentheses are not necessary most of the time. Citation from <a href="http://docs.python.org/lib/typesseq.html">Python Library Reference</a>: </p> <blockquote> <p><em>Tuples are constructed by the comma operator</em> (not within square brackets), with or without enclosing parentheses, but an empty tuple must have the enclosing parentheses, such as a, b, c or (). A single item tuple must have a trailing comma, such as (d,).</p> </blockquote> <h3>Functions should serve single purpose</h3> <p>Therefore they should return a single object. In your case this object is a tuple. Consider tuple as an ad-hoc compound data structure. There are languages where almost every single function returns multiple values (list in Lisp).</p> <p>Sometimes it is sufficient to return <code>(x, y)</code> instead of <code>Point(x, y)</code>.</p> <h3>Named tuples</h3> <p>With the introduction of named tuples in Python 2.6 it is preferable in many cases to return named tuples instead of plain tuples.</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; Point = collections.namedtuple('Point', 'x y') &gt;&gt;&gt; x, y = Point(0, 1) &gt;&gt;&gt; p = Point(x, y) &gt;&gt;&gt; x, y, p (0, 1, Point(x=0, y=1)) &gt;&gt;&gt; p.x, p.y, p[0], p[1] (0, 1, 0, 1) &gt;&gt;&gt; for i in p: ... print(i) ... 0 1 </code></pre>
84
2008-09-14T20:54:14Z
[ "python", "function", "return-value" ]
Is it pythonic for a function to return multiple values?
61,605
<p>In python, you can have a function return multiple values. Here's a contrived example:</p> <pre><code>def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) </code></pre> <p>This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").</p> <p>When should you draw the line and define a different method? </p>
66
2008-09-14T20:15:19Z
61,637
<p>The example you give is actually a python builtin function, called <code>divmod</code>. So someone, at some point in time, thought that it was pythonic enough to include in the core functionality.</p> <p>To me, if it makes the code cleaner, it is pythonic. Compare these two code blocks:</p> <pre><code>seconds = 1234 minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) seconds = 1234 minutes = seconds / 60 seconds = seconds % 60 hours = minutes / 60 minutes = minutes % 60 </code></pre>
12
2008-09-14T20:55:28Z
[ "python", "function", "return-value" ]
Is it pythonic for a function to return multiple values?
61,605
<p>In python, you can have a function return multiple values. Here's a contrived example:</p> <pre><code>def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) </code></pre> <p>This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").</p> <p>When should you draw the line and define a different method? </p>
66
2008-09-14T20:15:19Z
63,528
<p>It's fine to return multiple values using a tuple for simple functions such as <code>divmod</code>. If it makes the code readable, it's Pythonic.</p> <p>If the return value starts to become confusing, check whether the function is doing too much and split it if it is. If a big tuple is being used like an object, make it an object. Also, consider using <a href="http://code.activestate.com/recipes/500261/" rel="nofollow">named tuples</a>, which will be part of the standard library in Python 2.6.</p>
0
2008-09-15T14:43:01Z
[ "python", "function", "return-value" ]
Is it pythonic for a function to return multiple values?
61,605
<p>In python, you can have a function return multiple values. Here's a contrived example:</p> <pre><code>def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) </code></pre> <p>This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").</p> <p>When should you draw the line and define a different method? </p>
66
2008-09-14T20:15:19Z
63,549
<p>It's definitely pythonic. The fact that you can return multiple values from a function the boilerplate you would have in a language like C where you need to define a struct for every combination of types you return somewhere.</p> <p>However, if you reach the point where you are returning something crazy like 10 values from a single function, you should seriously consider bundling them in a class because at that point it gets unwieldy.</p>
1
2008-09-15T14:46:06Z
[ "python", "function", "return-value" ]
Is it pythonic for a function to return multiple values?
61,605
<p>In python, you can have a function return multiple values. Here's a contrived example:</p> <pre><code>def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) </code></pre> <p>This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").</p> <p>When should you draw the line and define a different method? </p>
66
2008-09-14T20:15:19Z
63,809
<p>Returning a tuple is cool. Also note the new namedtuple which was added in python 2.6 which may make this more palatable for you: <a href="http://docs.python.org/dev/library/collections.html#collections.namedtuple" rel="nofollow">http://docs.python.org/dev/library/collections.html#collections.namedtuple</a></p>
1
2008-09-15T15:14:04Z
[ "python", "function", "return-value" ]
Is it pythonic for a function to return multiple values?
61,605
<p>In python, you can have a function return multiple values. Here's a contrived example:</p> <pre><code>def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) </code></pre> <p>This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").</p> <p>When should you draw the line and define a different method? </p>
66
2008-09-14T20:15:19Z
64,110
<p>Yes, returning multiple values (i.e., a tuple) is definitely pythonic. As others have pointed out, there are plenty of examples in the Python standard library, as well as in well-respected Python projects. Two additional comments:</p> <ol> <li>Returning multiple values is sometimes very, very useful. Take, for example, a method that optionally handles an event (returning some value in doing so) and also returns success or failure. This might arise in a chain of responsibility pattern. In other cases, you want to return multiple, closely linked pieces of data---as in the example given. In this setting, returning multiple values is akin to returning a single instance of an anonymous class with several member variables.</li> <li><p>Python's handling of method arguments necessitates the ability to directly return multiple values. In C++, for example, method arguments can be passed by reference, so you can assign output values to them, in addition to the formal return value. In Python, arguments are passed "by reference" (but in the sense of Java, not C++). You can't assign new values to method arguments and have it reflected outside method scope. For example:</p> <pre><code>// C++ void test(int&amp; arg) { arg = 1; } int foo = 0; test(foo); // foo is now 1! </code></pre> <p>Compare with:</p> <pre><code># Python def test(arg): arg = 1 foo = 0 test(foo) # foo is still 0 </code></pre></li> </ol>
3
2008-09-15T15:47:23Z
[ "python", "function", "return-value" ]
Is it pythonic for a function to return multiple values?
61,605
<p>In python, you can have a function return multiple values. Here's a contrived example:</p> <pre><code>def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) </code></pre> <p>This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").</p> <p>When should you draw the line and define a different method? </p>
66
2008-09-14T20:15:19Z
66,967
<p>I'm fairly new to Python, but the tuple technique seems very pythonic to me. However, I've had another idea that may enhance readability. Using a dictionary allows access to the different values by name rather than position. For example:</p> <pre><code>def divide(x, y): return {'quotient': x/y, 'remainder':x%y } answer = divide(22, 7) print answer['quotient'] print answer['remainder'] </code></pre>
1
2008-09-15T21:05:57Z
[ "python", "function", "return-value" ]
Is it pythonic for a function to return multiple values?
61,605
<p>In python, you can have a function return multiple values. Here's a contrived example:</p> <pre><code>def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) </code></pre> <p>This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").</p> <p>When should you draw the line and define a different method? </p>
66
2008-09-14T20:15:19Z
640,632
<p>OT: RSRE's Algol68 has the curious "/:=" operator. eg.</p> <pre><code>INT quotient:=355, remainder; remainder := (quotient /:= 113); </code></pre> <p>Giving a quotient of 3, and a remainder of 16. </p> <p>Note: typically the value of "(x/:=y)" is discarded as quotient "x" is assigned by reference, but in RSRE's case the returned value is the remainder.</p> <p>c.f. <a href="http://rosettacode.org/wiki/Basic%5Finteger%5Farithmetic#ALGOL%5F68" rel="nofollow">Integer Arithmetic - Algol68</a></p>
1
2009-03-12T21:48:42Z
[ "python", "function", "return-value" ]
python cgi on IIS
61,781
<p>How do you set up IIS so that you can call python scripts from asp pages?</p> <p>Ok, so I found the answer to that question here: <a href="http://support.microsoft.com/kb/276494" rel="nofollow">http://support.microsoft.com/kb/276494</a></p> <p>So on to my next question: How do you call a cgi script from within classic asp (vb) code? Particularly one which is not in the web root directory.</p>
0
2008-09-15T01:41:31Z
61,842
<p>You could also do it <a href="http://www.4guysfromrolla.com/webtech/082201-1.shtml" rel="nofollow">this way</a>.</p>
2
2008-09-15T03:58:29Z
[ "python", "iis", "asp-classic", "vbscript", "cgi" ]
python cgi on IIS
61,781
<p>How do you set up IIS so that you can call python scripts from asp pages?</p> <p>Ok, so I found the answer to that question here: <a href="http://support.microsoft.com/kb/276494" rel="nofollow">http://support.microsoft.com/kb/276494</a></p> <p>So on to my next question: How do you call a cgi script from within classic asp (vb) code? Particularly one which is not in the web root directory.</p>
0
2008-09-15T01:41:31Z
66,440
<p>I don't believe that VBScript as hosted by IIS has any way of executing an external process. If you are using python as an AXscripting engine then you could just use the sys module. If the script you're calling is actually meant to be a cgi script you'll have to mimic all the environment variables that the cgi uses. The alternative is to put the script on the python path, import it and hope that it is modular enough that you can call the pieces you need and bypass the cgi handling code.</p>
1
2008-09-15T20:09:09Z
[ "python", "iis", "asp-classic", "vbscript", "cgi" ]
What's a good way to find relative paths in Google App Engine?
61,894
<p>So I've done the trivial "warmup" apps with GAE. Now I'd like to build something with a more complex directory structure. Something along the lines of:</p> <pre><code>siteroot/ models/ controllers/ controller1/ controller2/ ... templates/ template1/ template2/ ... </code></pre> <p>..etc. The controllers will be Python modules handling requests. They would then need to locate (Django-style) templates in associated folders. Most of the demo apps I've seen resolve template paths like this:</p> <pre><code>path = os.path.join(os.path.dirname(__file__), 'myPage.html') </code></pre> <p>...the __ file __ property resolves to the currently executing script. So, in my above example, if a Python script were running in controllers/controller1/, then the 'myPage.html' would resolve to that same directory -- controllers/controller1/myPage.html -- and I would rather cleanly separate my Python code and templates.</p> <p>The solution I've hacked together feels... hacky:</p> <pre><code>base_paths = os.path.split(os.path.dirname(__file__)) template_dir = os.path.join(base_paths[0], "templates") </code></pre> <p>So, I'm just snipping off the last element of the path for the currently running script and appending the template directory to the new path. The other (non-GAE specific) solutions I've seen for resolving Python paths seem pretty heavyweight (such as splitting paths into lists and manipulating accordingly). Django seems to have an answer for this, but I'd rather stick to the GAE API, vs. creating a full Django app and modifying it for GAE.</p> <p>I'm assuming anything hard-coded would be non-starter, since the apps live on Google's infinite server farm. So what's a better way?</p>
3
2008-09-15T05:21:47Z
62,121
<p>The <code>dirname</code> function returns an absolute path, use relative paths. See what is the current directory when your controllers are executed with <code>os.path.abspath(os.path.curdir)</code> and build a path to the templates relative to that location (without the <code>os.path.abspath</code> part of course).</p> <p>This will only work if the current directory is somewhere inside <em>siteroot</em>, else you could do something like this:</p> <pre><code>template_dir = os.path.join(os.path.dirname(__file__), os.path.pardir, "templates") </code></pre>
1
2008-09-15T10:37:02Z
[ "python", "google-app-engine" ]
What's a good way to find relative paths in Google App Engine?
61,894
<p>So I've done the trivial "warmup" apps with GAE. Now I'd like to build something with a more complex directory structure. Something along the lines of:</p> <pre><code>siteroot/ models/ controllers/ controller1/ controller2/ ... templates/ template1/ template2/ ... </code></pre> <p>..etc. The controllers will be Python modules handling requests. They would then need to locate (Django-style) templates in associated folders. Most of the demo apps I've seen resolve template paths like this:</p> <pre><code>path = os.path.join(os.path.dirname(__file__), 'myPage.html') </code></pre> <p>...the __ file __ property resolves to the currently executing script. So, in my above example, if a Python script were running in controllers/controller1/, then the 'myPage.html' would resolve to that same directory -- controllers/controller1/myPage.html -- and I would rather cleanly separate my Python code and templates.</p> <p>The solution I've hacked together feels... hacky:</p> <pre><code>base_paths = os.path.split(os.path.dirname(__file__)) template_dir = os.path.join(base_paths[0], "templates") </code></pre> <p>So, I'm just snipping off the last element of the path for the currently running script and appending the template directory to the new path. The other (non-GAE specific) solutions I've seen for resolving Python paths seem pretty heavyweight (such as splitting paths into lists and manipulating accordingly). Django seems to have an answer for this, but I'd rather stick to the GAE API, vs. creating a full Django app and modifying it for GAE.</p> <p>I'm assuming anything hard-coded would be non-starter, since the apps live on Google's infinite server farm. So what's a better way?</p>
3
2008-09-15T05:21:47Z
102,572
<p>You can't use relative paths, as Toni suggests, because you have no guarantee that the path from your working directory to your app's directory will remain the same.</p> <p>The correct solution is to either use os.path.split, as you are, or to use something like:</p> <pre><code>path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'myPage.html') </code></pre> <p>My usual approach is to generate a path to the template directory using the above method, and store it as a member of my controller object, and provide a "getTemplatePath" method that takes the provided filename and joins it with the basename.</p>
4
2008-09-19T15:02:56Z
[ "python", "google-app-engine" ]
Comparing runtimes
62,079
<p>I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.</p> <blockquote> <p>1) Is it actually worth taking such things into account?</p> <p>2) Assuming it is worth taking it into account, how do I do this?</p> </blockquote> <p>I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.</p>
2
2008-09-15T10:06:19Z
62,094
<p>If your idea is to compare the languages, I'd say anything outside them is not relevant for comparison purposes. </p> <p>Nonetheless you can use the time command to measure everything and can compare it with the timing within a script.</p> <p>Like this:</p> <pre><code>$ time script.php HI! real 0m3.218s user 0m0.080s sys 0m0.064s </code></pre> <p>It will give you clock time, user time (php interpreter) and sys time (OS time)</p> <p>If you are thinking web, then it gets a lot harder because you would be mixing webserver overhead and that is not always easy to compare if, say, you are using WSGI v/s mod_php. Then you'd have to hook probes into the webserving parts of the chain as well</p>
4
2008-09-15T10:18:05Z
[ "php", "python", "benchmarking" ]
Comparing runtimes
62,079
<p>I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.</p> <blockquote> <p>1) Is it actually worth taking such things into account?</p> <p>2) Assuming it is worth taking it into account, how do I do this?</p> </blockquote> <p>I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.</p>
2
2008-09-15T10:06:19Z
62,097
<ol> <li><p>It's worth taking speed into account if you're optimizing code. You should generally know why you're optimizing code (as in: a specific task in your existing codebase is taking too long, not "I heard PHP is slower than Python"). It's <em>not</em> worth taking speed into account if you don't actually plan on switching languages. Just because one tiny module does something slightly faster doesn't mean rewriting your app in another language is a good idea. There are many other factors to choosing a language besides speed.</p></li> <li><p>You benchmark, of course. Run the two codebases multiple times and compare the timing. You can use the <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?time" rel="nofollow">time</a> command if both scripts are executable from the shell, or use respective benchmarking functionality from each language; the latter case depends heavily on the actual language, naturally.</p></li> </ol>
1
2008-09-15T10:20:04Z
[ "php", "python", "benchmarking" ]
Comparing runtimes
62,079
<p>I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.</p> <blockquote> <p>1) Is it actually worth taking such things into account?</p> <p>2) Assuming it is worth taking it into account, how do I do this?</p> </blockquote> <p>I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.</p>
2
2008-09-15T10:06:19Z
62,099
<p>Well, you can use the "time" command to help:</p> <pre><code>you@yourmachine:~$ time echo "hello world" hello world real 0m0.000s user 0m0.000s sys 0m0.000s you@yourmachine:~$ </code></pre> <p>And this will get around timing outside of the environment.</p> <p>As for whether you need to actually time that extra work... that entirely depends on what you are doing. I assume this is for some kind of web application of some sort, so it depends on how the framework you use actually works... does it cache some kind of compiled (or parsed) version of the script? If so, then startup time will be totally irrelevant (since the first hit will be the only one that startup time exists in).</p> <p>Also, make sure to run your tests in a loop so you can discount the first run (and include the cost on the first run in your report if you want). I have done some tests in Java, and the first run is always slowest due to the JIT doing its job (and the same sort of hit may exist in PHP, Python and any other languages you try).</p>
1
2008-09-15T10:23:55Z
[ "php", "python", "benchmarking" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,093
<p>No. How would Python parse your script if there was a way to disable this?</p>
0
2008-09-15T13:56:32Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,094
<p>No. Indentation-as-grammar is an integral part of the Python language, for better and worse.</p>
33
2008-09-15T13:56:47Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,095
<p>I do not believe so, as Python is a whitespace-delimited language. Perhaps a text editor or IDE with auto-indentation would be of help. What are you currently using?</p>
2
2008-09-15T13:56:55Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,111
<p>No, there isn't. Indentation is syntax for Python. You can:</p> <ol> <li>Use tabnanny.py to check your code</li> <li>Use a syntax-aware editor that highlights such mistakes (vi does that, emacs I bet it does, and then, most IDEs do too)</li> <li>(far-fetched) write a preprocessor of your own to convert braces (or whatever block delimiters you love) into indentation</li> </ol>
3
2008-09-15T13:59:18Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,119
<p>All of the whitespace issues I had when I was starting Python were the result mixing tabs and spaces. Once I configured everything to just use one or the other, I stopped having problems.</p> <p>In my case I configured UltraEdit &amp; vim to use spaces in place of tabs.</p>
5
2008-09-15T13:59:45Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,122
<p>You should disable tab characters in your editor when you're working with Python (always, actually, IMHO, but especially when you're working with Python). Look for an option like "Use spaces for tabs": any decent editor should have one.</p>
2
2008-09-15T14:00:05Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,124
<p>Not really. There are a few ways to modify whitespace rules for a given line of code, but you will still need indent levels to determine scope.</p> <p>You can terminate statements with <code>;</code> and then begin a new statement on the same line. (Which people often do when <a href="http://codegolf.com/" rel="nofollow">golfing.)</a></p> <p>If you want to break up a single line into multiple lines you can finish a line with the <code>\</code> character which means the current line effectively continues from the first non-whitespace character of the next line. This visually <em>appears</em> violate the usual whitespace rules but is legal.</p> <p>My advice: don't use tabs if you are having tab/space confusion. Use spaces, and choose either 2 or 3 spaces as your indent level. </p> <p>A good editor will make it so you don't have to worry about this. (python-mode for <a href="http://www.gnu.org/software/emacs/" rel="nofollow">emacs,</a> for example, you can just use the tab key and it will keep you honest).</p>
1
2008-09-15T14:00:23Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,196
<p>It's possible to write a pre-processor which takes randomly-indented code with pseudo-python keywords like "endif" and "endwhile" and properly indents things. I had to do this when using python as an "ASP-like" language, because the whole notion of "indentation" gets a bit fuzzy in such an environment.</p> <p>Of course, even with such a thing you really ought to indent sanely, at which point the conveter becomes superfluous.</p>
2
2008-09-15T14:06:46Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,216
<p>I agree with justin and others -- pick a good editor and use spaces rather than tabs for indentation and the whitespace thing becomes a non-issue. I only recently started using Python, and while I thought the whitespace issue would be a real annoyance it turns out to not be the case. For the record I'm using emacs though I'm sure there are other editors out there that do an equally fine job.</p> <p>If you're really dead-set against it, you can always pass your scripts through a pre-processor but that's a bad idea on many levels. If you're going to learn a language, embrace the features of that language rather than try to work around them. Otherwise, what's the point of learning a new language?</p>
2
2008-09-15T14:09:10Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,289
<p>Getting your indentation to work correctly is going to be important in any language you use. </p> <p>Even though it won't affect the execution of the program in most other languages, incorrect indentation can be very confusing for anyone trying to read your program, so you need to invest the time in figuring out how to configure your editor to align things correctly.</p> <p>Python is pretty liberal in how it lets you indent. You can pick between tabs and spaces (but you really should use spaces) and can pick how many spaces. The only thing it requires is that you are consistent which ultimately is important no matter what language you use.</p>
1
2008-09-15T14:16:37Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,357
<blockquote> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p> </blockquote> <p>I liked <a href="http://pydev.sourceforge.net/" rel="nofollow">pydev</a> extensions of eclipse for that.</p>
4
2008-09-15T14:22:30Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,403
<p>Tabs and spaces confusion can be fixed by setting your editor to use spaces instead of tabs. </p> <p>To make whitespace completely intuitive, you can use a stronger code editor or an IDE (though you don't need a full-blown IDE if all you need is proper automatic code indenting). </p> <p>A list of editors can be found in the Python wiki, though that one is a bit too exhausting: - <a href="http://wiki.python.org/moin/PythonEditors" rel="nofollow">http://wiki.python.org/moin/PythonEditors</a></p> <p>There's already a question in here which tries to slim that down a bit: </p> <ul> <li><a href="http://stackoverflow.com/questions/60784/poll-which-python-ideeditor-is-the-best">http://stackoverflow.com/questions/60784/poll-which-python-ideeditor-is-the-best</a></li> </ul> <p>Maybe you should add a more specific question on that: "Which Python editor or IDE do you prefer on Windows - and why?"</p>
2
2008-09-15T14:28:27Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,450
<p>I was a bit reluctant to learn Python because of tabbing. However, I almost didn't notice it when I used Vim.</p>
0
2008-09-15T14:34:34Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,819
<p>I find it hard to understand when people flag this as a problem with Python. I took to it immediately and actually find it's one of my favourite 'features' of the language :)</p> <p>In other languages I have two jobs: 1. Fix the braces so the computer can parse my code 2. Fix the indentation so I can parse my code.</p> <p>So in Python I have half as much to worry about ;-)</p> <p>(nb the only time I ever have problem with indendation is when Python code is in a blog and a forum that messes with the white-space but this is happening less and less as the apps get smarter)</p>
2
2008-09-15T15:15:07Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
63,956
<p>If you're looking for a recommendation for a Python IDE, after extensive research, I've been most happy with Wing Software's WingIDE:</p> <p><a href="http://www.wingware.com/products" rel="nofollow">http://www.wingware.com/products</a></p> <p>There is a free trial version, so you have nothing to lose. It supports all the major OSes, and is only about $60 for the full version.</p> <p>I also like SciTE a lot, which is totally free, free, free!</p> <p><a href="http://scintilla.sourceforge.net/SciTEDownload.html" rel="nofollow">http://scintilla.sourceforge.net/SciTEDownload.html</a></p>
1
2008-09-15T15:29:29Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
64,186
<p>Many Python IDEs and generally-capable text/source editors can handle the whitespace for you.</p> <p>However, it is best to just "let go" and enjoy the whitespace rules of Python. With some practice, they won't get into your way at all, and you will find they have many merits, the most important of which are:</p> <ol> <li>Because of the forced whitespace, Python code is simpler to understand. You will find that as you read code written by others, it is easier to grok than code in, say, Perl or PHP.</li> <li>Whitespace saves you quite a few keystrokes of control characters like { and }, which litter code written in C-like languages. Less {s and }s means, among other things, less RSI and wrist pain. This is not a matter to take lightly.</li> </ol>
0
2008-09-15T15:57:56Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
64,356
<p><a href="http://timhatch.com/projects/pybraces/" rel="nofollow">pybraces</a></p> <p>It's unsupported.</p>
3
2008-09-15T16:18:30Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
64,899
<p>In Python, indentation is a semantic element as well as providing visual grouping for readability.</p> <p>Both space and tab can indicate indentation. This is unfortunate, because:</p> <ul> <li><p>The interpretation(s) of a tab varies among editors and IDEs and is often configurable (and often configured).</p></li> <li><p>OTOH, some editors are not configurable but apply their own rules for indentation.</p></li> <li><p>Different sequences of spaces and tabs may be visually indistinguishable.</p></li> <li><p>Cut and pastes can alter whitespace.</p></li> </ul> <p>So, unless you know that a given piece of code will only be modified by yourself with a single tool and an unvarying config, you must avoid tabs for indentation (configure your IDE) and make sure that you are warned if they are introduced (search for tabs in leading whitespace).</p> <p>And you can still expect to be bitten now and then, as long as arbitrary semantics are applied to control characters.</p>
0
2008-09-15T17:25:34Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
65,771
<p>The real answer to your question is that if you are going to use the language you need to learn its syntax. Just as an error in indenting python can generate a compiler error, an error using braces in various other languages can also generate a compiler error.</p> <p>Even worse it can be silently misinterpreted by the compiler to do the wrong thing. This is particularly dangerous when the indenting doesn't match the desired meaning. I.e. in many other languages:</p> <pre><code>If(first condition) if (second condition) do something interesting; else do something different; </code></pre> <p>Will lead to unpleasant surprises.</p> <p>Python forces you to write code that <em>looks</em> like what it does. This is a good thing for other programmers who have to read your code, or for you when you try to read your own code after a month or so.</p>
0
2008-09-15T19:07:07Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
68,052
<p>If you don't want to use an IDE/text editor with automatic indenting, you can use the pindent.py script that comes in the Tools\Scripts directory. It's a preprocessor that can convert code like:</p> <pre><code>def foobar(a, b): if a == b: a = a+1 elif a &lt; b: b = b-1 if b &gt; a: a = a-1 end if else: print 'oops!' end if end def foobar </code></pre> <p>into:</p> <pre><code>def foobar(a, b): if a == b: a = a+1 elif a &lt; b: b = b-1 if b &gt; a: a = a-1 # end if else: print 'oops!' # end if # end def foobar </code></pre> <p>Which is valid python.</p>
1
2008-09-15T23:53:40Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
68,061
<p>Emacs! Seriously, its use of "tab is a <em>command</em>, not a <em>character</em>", is absolutely perfect for python development.</p>
9
2008-09-15T23:56:17Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
68,702
<pre><code>from __future__ import braces </code></pre>
36
2008-09-16T01:55:09Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
69,064
<p>Check the options of your editor or find an editor/IDE that allows you to convert TABs to spaces. I usually set the options of my editor to substitute the TAB character with 4 spaces, and I never run into any problems.</p>
0
2008-09-16T03:03:31Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
73,325
<p>Strange - No one mentioned GEdit (Gnome) or OpenKomodo (Windows, Mac, GNU/Linux...). Both of them are great!</p> <p>OpenKomodo especially deals with tabs and spaces very well. And - it's free. Whee! When I need a lighter weight thingy, I just use GEdit.</p> <p>Download OpenKomodo here - <a href="http://www.openkomodo.com/" rel="nofollow">http://www.openkomodo.com/</a></p>
0
2008-09-16T15:03:47Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
118,216
<p>Nope, there's no way around it, and it's by design:</p> <pre><code>&gt;&gt;&gt; from __future__ import braces File "&lt;stdin&gt;", line 1 SyntaxError: not a chance </code></pre> <p>Most Python programmers simply don't use tabs, but use spaces to indent instead, that way there's no editor-to-editor inconsistency.</p>
0
2008-09-22T23:27:06Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
1,515,244
<p>Yes, there is a way. I hate these "no way" answers, there is no way until you discover one.</p> <p>And in that case, whatever it is worth, there is one.</p> <p>I read once about a guy who designed a way to code so that a simple script could re-indent the code properly. I didn't managed to find any links today, though, but I swear I read it.</p> <p>The main tricks are to <em>always</em> use <code>return</code> at the end of a function, <em>always</em> use <code>pass</code> at the end of an <code>if</code> or at the end of a class definition, and always use <code>continue</code> at the end of a <code>while</code>. Of course, any other <em>no-effect</em> instruction would fit the purpose.</p> <p>Then, a simple <em>awk</em> script can take your code and detect the end of block by reading pass/continue/return instructions, and the start of code with if/def/while/... instructions.</p> <p>Of course, because you'll develop your indenting script, you'll see that you don't have to use continue after a return inside the if, because the return will trigger the indent-back mechanism. The same applies for other situations. Just get use to it.</p> <p>If you are diligent, you'll be able to cut/paste and add/remove <code>if</code> and correct the indentations automagically. And incidentally, pasting code from the web will require you to understand a bit of it so that you can adapt it to that "non-classical" setting.</p>
-1
2009-10-04T00:20:23Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
1,538,995
<p>I'm surprised no one has mentioned IDLE as a good default python editor. Nice syntax colors, handles indents, has intellisense, easy to adjust fonts, and it comes with the default download of python. Heck, I write mostly IronPython, but it's so nice &amp; easy to edit in IDLE and run ipy from a command prompt.</p> <p>Oh, and what is the big deal about whitespace? Most easy to read C or C# is well indented, too, python just enforces a really simple formatting rule.</p>
1
2009-10-08T16:35:33Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
1,780,742
<p>Just use Ruby, it's much better than Python.</p> <p><a href="http://www.ruby-lang.org" rel="nofollow">http://www.ruby-lang.org</a></p>
-3
2009-11-23T01:52:25Z
[ "python" ]
Is there a way around coding in Python without the tab, indent & whitespace criteria?
63,086
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
6
2008-09-15T13:55:14Z
2,695,213
<p>Any decent programming editor will reduce this annoyance to nil. I see Notepad++ has syntax highlighting, it's likely you just need to set your preferences appropriately for auto-indenting and such.</p>
0
2010-04-22T23:24:42Z
[ "python" ]
Which is the most useful Mercurial hook for programming in a loosely connected team?
63,488
<p>I recently discovered the notify extension in Mercurial which allows me quickly send out emails whenever I push changes, but I'm pretty sure I'm still missing out on a lot of functionality which could make my life a lot easier. </p> <ul> <li>notify-extension: <a href="http://www.selenic.com/mercurial/wiki/index.cgi/NotifyExtension" rel="nofollow">http://www.selenic.com/mercurial/wiki/index.cgi/NotifyExtension</a></li> </ul> <p>Which Mercurial hook or combination of interoperating hooks is the most useful for working in a loosely connected team? </p> <p>Please add links to non-standard parts you use and/or add the hook (or a description how to set it up), so others can easily use it. </p>
0
2008-09-15T14:38:58Z
63,606
<p>Take a look at the hgweb stuff. You can set up RSS feeds and see all the revisions, et cetera.</p>
1
2008-09-15T14:52:58Z
[ "python", "mercurial", "hook" ]
Which is the most useful Mercurial hook for programming in a loosely connected team?
63,488
<p>I recently discovered the notify extension in Mercurial which allows me quickly send out emails whenever I push changes, but I'm pretty sure I'm still missing out on a lot of functionality which could make my life a lot easier. </p> <ul> <li>notify-extension: <a href="http://www.selenic.com/mercurial/wiki/index.cgi/NotifyExtension" rel="nofollow">http://www.selenic.com/mercurial/wiki/index.cgi/NotifyExtension</a></li> </ul> <p>Which Mercurial hook or combination of interoperating hooks is the most useful for working in a loosely connected team? </p> <p>Please add links to non-standard parts you use and/or add the hook (or a description how to set it up), so others can easily use it. </p>
0
2008-09-15T14:38:58Z
63,636
<p>I really enjoy what I did with my custom hook. I have it post a message to my campfire account (campfire is a group based app). It worked out really well. Because I had my clients in there and it could show him my progress.</p>
2
2008-09-15T14:56:06Z
[ "python", "mercurial", "hook" ]
Which is the most useful Mercurial hook for programming in a loosely connected team?
63,488
<p>I recently discovered the notify extension in Mercurial which allows me quickly send out emails whenever I push changes, but I'm pretty sure I'm still missing out on a lot of functionality which could make my life a lot easier. </p> <ul> <li>notify-extension: <a href="http://www.selenic.com/mercurial/wiki/index.cgi/NotifyExtension" rel="nofollow">http://www.selenic.com/mercurial/wiki/index.cgi/NotifyExtension</a></li> </ul> <p>Which Mercurial hook or combination of interoperating hooks is the most useful for working in a loosely connected team? </p> <p>Please add links to non-standard parts you use and/or add the hook (or a description how to set it up), so others can easily use it. </p>
0
2008-09-15T14:38:58Z
330,548
<p>I've written a small set of minor hooks which might be interesting: <a href="http://fellowiki.org/hg/support/quecksilber/file/" rel="nofollow">http://fellowiki.org/hg/support/quecksilber/file/</a></p> <p>Anyway, these are the hooks most useful to me ;-)</p>
1
2008-12-01T11:13:07Z
[ "python", "mercurial", "hook" ]
How create threads under Python for Delphi
63,681
<p>I'm hosting Python script with Python for Delphi components inside my Delphi application. I'd like to create background tasks which keep running by script.</p> <p>Is it possible to create threads which keep running even if the script execution ends (but not the host process, which keeps going on). I've noticed that the program gets stuck if the executing script ends and there is thread running. However if I'll wait until the thread is finished everything goes fine.</p> <p>I'm trying to use "threading" standard module for threads.</p>
1
2008-09-15T15:00:45Z
63,767
<p>Threads by definition are part of the same process. If you want them to keep running, they need to be forked off into a new process; see os.fork() and friends.</p> <p>You'll probably want the new process to end (via exit() or the like) immediately after spawning the script.</p>
0
2008-09-15T15:10:03Z
[ "python", "delphi" ]
How create threads under Python for Delphi
63,681
<p>I'm hosting Python script with Python for Delphi components inside my Delphi application. I'd like to create background tasks which keep running by script.</p> <p>Is it possible to create threads which keep running even if the script execution ends (but not the host process, which keeps going on). I've noticed that the program gets stuck if the executing script ends and there is thread running. However if I'll wait until the thread is finished everything goes fine.</p> <p>I'm trying to use "threading" standard module for threads.</p>
1
2008-09-15T15:00:45Z
63,794
<p>If a process dies all it's threads die with it, so a solution might be a separate process.</p> <p>See if creating a xmlrpc server might help you, that is a simple solution for interprocess communication.</p>
0
2008-09-15T15:12:27Z
[ "python", "delphi" ]
How create threads under Python for Delphi
63,681
<p>I'm hosting Python script with Python for Delphi components inside my Delphi application. I'd like to create background tasks which keep running by script.</p> <p>Is it possible to create threads which keep running even if the script execution ends (but not the host process, which keeps going on). I've noticed that the program gets stuck if the executing script ends and there is thread running. However if I'll wait until the thread is finished everything goes fine.</p> <p>I'm trying to use "threading" standard module for threads.</p>
1
2008-09-15T15:00:45Z
65,757
<p>Python has its own threading module that comes standard, if it helps. You can create thread objects using the threading module.</p> <p><a href="http://docs.python.org/lib/module-threading.html" rel="nofollow">threading Documentation</a></p> <p><a href="http://docs.python.org/lib/module-thread.html" rel="nofollow">thread Documentation</a></p> <p>The thread module offers low level threading and synchronization using simple Lock objects.</p> <p>Again, not sure if this helps since you're using Python under a Delphi environment.</p>
2
2008-09-15T19:05:12Z
[ "python", "delphi" ]
Classes in Python
64,141
<p>In Python is there any way to make a class, then make a second version of that class with identical dat,a but which can be changed, then reverted to be the same as the data in the original class? </p> <p>So I would make a class with the numbers 1 to 5 as the data in it, then make a second class with the same names for sections (or very similar). Mess around with the numbers in the second class then with one function then reset them to be the same as in the first class. </p> <p>The only alternative I've found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable.</p>
1
2008-09-15T15:51:02Z
64,163
<p>A class is a template, it allows you to create a blueprint, you can then have multiple instances of a class each with different numbers, like so.</p> <pre><code>class dog(object): def __init__(self, height, width, lenght): self.height = height self.width = width self.length = length def revert(self): self.height = 1 self.width = 2 self.length = 3 dog1 = dog(5, 6, 7) dog2 = dog(2, 3, 4) dog1.revert() </code></pre>
5
2008-09-15T15:54:52Z
[ "python", "class" ]
Classes in Python
64,141
<p>In Python is there any way to make a class, then make a second version of that class with identical dat,a but which can be changed, then reverted to be the same as the data in the original class? </p> <p>So I would make a class with the numbers 1 to 5 as the data in it, then make a second class with the same names for sections (or very similar). Mess around with the numbers in the second class then with one function then reset them to be the same as in the first class. </p> <p>The only alternative I've found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable.</p>
1
2008-09-15T15:51:02Z
64,195
<p>Classes don't have values. Objects do. Is what you want basically a class that can reset an instance (object) to a set of default values? </p> <p>How about just providing a reset method, that resets the properties of your object to whatever is the default?</p> <p>I think you should simplify your question, or tell us what you really want to do. It's not at all clear.</p>
1
2008-09-15T15:59:11Z
[ "python", "class" ]
Classes in Python
64,141
<p>In Python is there any way to make a class, then make a second version of that class with identical dat,a but which can be changed, then reverted to be the same as the data in the original class? </p> <p>So I would make a class with the numbers 1 to 5 as the data in it, then make a second class with the same names for sections (or very similar). Mess around with the numbers in the second class then with one function then reset them to be the same as in the first class. </p> <p>The only alternative I've found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable.</p>
1
2008-09-15T15:51:02Z
64,206
<p>I think you are confused. You should re-check the meaning of "class" and "instance".</p> <p>I think you are trying to first declare a Instance of a certain Class, and then declare a instance of other Class, use the data from the first one, and then find a way to convert the data in the second instance and use it on the first instance...</p> <p>I recommend that you use operator overloading to assign the data.</p>
1
2008-09-15T16:00:31Z
[ "python", "class" ]
Classes in Python
64,141
<p>In Python is there any way to make a class, then make a second version of that class with identical dat,a but which can be changed, then reverted to be the same as the data in the original class? </p> <p>So I would make a class with the numbers 1 to 5 as the data in it, then make a second class with the same names for sections (or very similar). Mess around with the numbers in the second class then with one function then reset them to be the same as in the first class. </p> <p>The only alternative I've found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable.</p>
1
2008-09-15T15:51:02Z
64,216
<pre><code>class ABC(self): numbers = [0,1,2,3] class DEF(ABC): def __init__(self): self.new_numbers = super(ABC,self).numbers def setnums(self, numbers): self.new_numbers = numbers def getnums(self): return self.new_numbers def reset(self): __init__() </code></pre>
1
2008-09-15T16:01:20Z
[ "python", "class" ]
Classes in Python
64,141
<p>In Python is there any way to make a class, then make a second version of that class with identical dat,a but which can be changed, then reverted to be the same as the data in the original class? </p> <p>So I would make a class with the numbers 1 to 5 as the data in it, then make a second class with the same names for sections (or very similar). Mess around with the numbers in the second class then with one function then reset them to be the same as in the first class. </p> <p>The only alternative I've found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable.</p>
1
2008-09-15T15:51:02Z
64,399
<p>Just FYI, here's an alternate implementation... Probably violates about 15 million pythonic rules, but I publish it per information/observation:</p> <pre><code>class Resettable(object): base_dict = {} def reset(self): self.__dict__ = self.__class__.base_dict def __init__(self): self.__dict__ = self.__class__.base_dict.copy() class SomeClass(Resettable): base_dict = { 'number_one': 1, 'number_two': 2, 'number_three': 3, 'number_four': 4, 'number_five': 5, } def __init__(self): Resettable.__init__(self) p = SomeClass() p.number_one = 100 print p.number_one p.reset() print p.number_one </code></pre>
1
2008-09-15T16:24:30Z
[ "python", "class" ]
Classes in Python
64,141
<p>In Python is there any way to make a class, then make a second version of that class with identical dat,a but which can be changed, then reverted to be the same as the data in the original class? </p> <p>So I would make a class with the numbers 1 to 5 as the data in it, then make a second class with the same names for sections (or very similar). Mess around with the numbers in the second class then with one function then reset them to be the same as in the first class. </p> <p>The only alternative I've found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable.</p>
1
2008-09-15T15:51:02Z
82,969
<p>Here's another answer kind of like pobk's; it uses the instance's dict to do the work of saving/resetting variables, but doesn't require you to specify the names of them in your code. You can call save() at any time to save the state of the instance and reset() to reset to that state.</p> <pre><code>class MyReset: def __init__(self, x, y): self.x = x self.y = y self.save() def save(self): self.saved = self.__dict__.copy() def reset(self): self.__dict__ = self.saved.copy() a = MyReset(20, 30) a.x = 50 print a.x a.reset() print a.x </code></pre> <p>Why do you want to do this? It might not be the best/only way.</p>
1
2008-09-17T13:09:44Z
[ "python", "class" ]
Nice Python wrapper for Yahoo's Geoplanet web service?
64,185
<p>Has anybody created a nice wrapper around Yahoo's geo webservice "GeoPlanet" yet?</p>
2
2008-09-15T15:57:48Z
66,924
<p>After a brief amount of Googling, I found nothing that looks like a wrapper for this API, but I'm not quite sure if a wrapper is what is necessary for GeoPlanet. </p> <p>According to Yahoo's <a href="http://developer.yahoo.com/geo/guide/api_docs.html#api_overview" rel="nofollow">documentation</a> for GeoPlanet, requests are made in the form of an HTTP GET messages which can very easily be made using Python's <a href="http://docs.python.org/lib/module-httplib.html" rel="nofollow">httplib module</a>, and <a href="http://developer.yahoo.com/geo/guide/response_formats.html" rel="nofollow">responses</a> can take one of several forms including XML and JSON. Python can very easily parse these formats. In fact, Yahoo! itself even offers libraries for parsing both <a href="http://developer.yahoo.com/python/python-xml.html" rel="nofollow">XML</a> and <a href="http://developer.yahoo.com/python/python-json.html" rel="nofollow">JSON</a> with Python. </p> <p>I know it sounds like a lot of libraries, but all the hard work has already been done for the programmer. It would just take a little "gluing together" and you would have yourself a nice interface to Yahoo! GeoPlanet using the power of Python.</p>
2
2008-09-15T21:01:02Z
[ "python", "gis", "yahoo" ]
When to create a new app (with startapp) in Django?
64,237
<p>I've googled around for this, but I still have trouble relating to what Django defines as "apps". </p> <p>Should I create a new app for each piece of functionality in a site, even though it uses models from the main project? </p> <p>Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality together with the "main project" or other apps?</p>
48
2008-09-15T16:03:22Z
64,308
<p>I tend to create new applications for each logically separate set of models. e.g.:</p> <ul> <li>User Profiles</li> <li>Forum Posts</li> <li>Blog posts</li> </ul>
7
2008-09-15T16:12:39Z
[ "python", "django" ]
When to create a new app (with startapp) in Django?
64,237
<p>I've googled around for this, but I still have trouble relating to what Django defines as "apps". </p> <p>Should I create a new app for each piece of functionality in a site, even though it uses models from the main project? </p> <p>Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality together with the "main project" or other apps?</p>
48
2008-09-15T16:03:22Z
64,464
<p>I prefer to think of Django applications as reusable modules or components than as "applications". </p> <p>This helps me encapsulate and decouple certain features from one another, improving re-usability should I decide to share a particular "app" with the community at large, and maintainability.</p> <p>My general approach is to bucket up specific features or feature sets into "apps" as though I were going to release them publicly. The hard part here is figuring out how big each bucket is. </p> <p>A good trick I use is to imagine how my apps would be used if they were released publicly. This often encourages me to shrink the buckets and more clearly define its "purpose".</p>
11
2008-09-15T16:32:07Z
[ "python", "django" ]
When to create a new app (with startapp) in Django?
64,237
<p>I've googled around for this, but I still have trouble relating to what Django defines as "apps". </p> <p>Should I create a new app for each piece of functionality in a site, even though it uses models from the main project? </p> <p>Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality together with the "main project" or other apps?</p>
48
2008-09-15T16:03:22Z
64,492
<p>James Bennett has a wonderful <a href="http://www.b-list.org/weblog/2008/mar/15/slides/" rel="nofollow">set of slides</a> on how to organize reusable apps in Django.</p>
25
2008-09-15T16:35:16Z
[ "python", "django" ]
When to create a new app (with startapp) in Django?
64,237
<p>I've googled around for this, but I still have trouble relating to what Django defines as "apps". </p> <p>Should I create a new app for each piece of functionality in a site, even though it uses models from the main project? </p> <p>Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality together with the "main project" or other apps?</p>
48
2008-09-15T16:03:22Z
67,769
<p>An 'app' could be many different things, it all really comes down to taste. For example, let's say you are building a blog. Your app could be the entire blog, or you could have an 'admin' app, a 'site' app for all of the public views, an 'rss' app, a 'services' app so developers can interface with the blog in their own ways, etc.</p> <p>I personally would make the blog itself the app, and break out the functionality within it. The blog could then be reused rather easily in other websites.</p> <p>The nice thing about Django is that it will recognize any models.py file within any level of your directory tree as a file containing Django models. So breaking your functionality out into smaller 'sub apps' within an 'app' itself won't make anything more difficult.</p>
0
2008-09-15T22:56:37Z
[ "python", "django" ]
When to create a new app (with startapp) in Django?
64,237
<p>I've googled around for this, but I still have trouble relating to what Django defines as "apps". </p> <p>Should I create a new app for each piece of functionality in a site, even though it uses models from the main project? </p> <p>Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality together with the "main project" or other apps?</p>
48
2008-09-15T16:03:22Z
68,086
<p>The rule I follow is it should be a new app if I want to reuse the functionality in a different project.</p> <p>If it needs deep understanding of the models in your project, it's probably more cohesive to stick it with the models.</p>
1
2008-09-16T00:01:11Z
[ "python", "django" ]
When to create a new app (with startapp) in Django?
64,237
<p>I've googled around for this, but I still have trouble relating to what Django defines as "apps". </p> <p>Should I create a new app for each piece of functionality in a site, even though it uses models from the main project? </p> <p>Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality together with the "main project" or other apps?</p>
48
2008-09-15T16:03:22Z
8,034,555
<p>Here is the updated presentation on 6 September 2008.</p> <p><a href="http://www.youtube.com/watch?v=A-S0tqpPga4">http://www.youtube.com/watch?v=A-S0tqpPga4</a></p> <p><a href="http://media.b-list.org/presentations/2008/djangocon/reusable_apps.pdf">http://media.b-list.org/presentations/2008/djangocon/reusable_apps.pdf</a></p> <blockquote> <h2>Taken from the slide</h2> <p>Should this be its own application?</p> <ul> <li>Is it completely unrelated to the app’s focus?</li> <li>Is it orthogonal to whatever else I’m doing?</li> <li>Will I need similar functionality on other sites?</li> </ul> <p>If any of them is "Yes"? Then best to break it into a separate application.</p> </blockquote>
7
2011-11-07T09:15:00Z
[ "python", "django" ]
How can I access App Engine through a Corporate proxy?
64,362
<p>I have corporate proxy that supports https but not HTTP CONNECT (even after authentication). It just gives 403 Forbidden in response anything but HTTP or HTTPS URLS. It uses HTTP authenication, not NTLM. It is well documented the urllib2 does not work with https thru a proxy. App Engine trys to connect to a https URL using urllib2 to update the app.</p> <p>On *nix, urllib2 expects proxies to set using env variables.</p> <pre><code>export http_proxy="http://mycorporateproxy:8080" export https_proxy="https://mycorporateproxy:8080" </code></pre> <p>This is sited as a work around: <a href="http://code.activestate.com/recipes/456195/" rel="nofollow">http://code.activestate.com/recipes/456195/</a>. Also see <a href="http://code.google.com/p/googleappengine/issues/detail?id=126" rel="nofollow">http://code.google.com/p/googleappengine/issues/detail?id=126</a>. None of these fixes have worked for me. They seem to rely on the proxy server supporting HTTP CONNECT. Does anyone have any other work arounds? I sure I am not the only one behind a restrictive corporate proxy.</p>
1
2008-09-15T16:18:59Z
84,465
<p>Do you mean it uses http basic-auth before allowing proxying, and does it then allow 'connect'.</p> <p>Then you should be able to tunnel over it using http-tunnel or proxytunnel</p>
1
2008-09-17T15:26:22Z
[ "python", "google-app-engine" ]
Best Python supported server/client protocol?
64,426
<p>I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.</p>
9
2008-09-15T16:27:47Z
64,471
<p><a href="http://pyro.sf.net">Pyro</a> (Python Remote Objects) is fairly clever if all your server/clients are going to be in Python. I use <a href="http://www.xmpp.org">XMPP</a> alot though since I'm communicating with hosts that are not always Python. XMPP lends itself to being extended fairly easily too.</p> <p>There is an excellent XMPP library for python called <a href="http://pyxmpp.jajcus.net">PyXMPP</a> which is reasonably up to date and has no dependancy on Twisted.</p>
5
2008-09-15T16:33:05Z
[ "python", "client" ]
Best Python supported server/client protocol?
64,426
<p>I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.</p>
9
2008-09-15T16:27:47Z
64,487
<p>I'd use http and start with understanding what the Python <a href="http://docs.python.org/lib/asyncore-example.html" rel="nofollow">library</a> offers. </p> <p>Then I'd move onto the more industrial strength <a href="http://wiki.python.org/moin/Twisted-Examples" rel="nofollow">Twisted</a> library.</p>
1
2008-09-15T16:34:45Z
[ "python", "client" ]
Best Python supported server/client protocol?
64,426
<p>I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.</p>
9
2008-09-15T16:27:47Z
64,489
<p><a href="http://www.ietf.org/rfc/rfc2616.txt" rel="nofollow">HTTP</a> seems to suit your requirements and is very well supported in Python. </p> <p><a href="http://twistedmatrix.com/" rel="nofollow">Twisted</a> is good for serious asynchronous network programming in Python, but it has a steep learning curve, so it might be worth using something simpler unless you know your system will need to handle a lot of concurrency.</p> <p>To start, I would suggest using <a href="http://www.python.org/doc/lib/module-urllib2.html" rel="nofollow"><code>urllib</code></a> for the client and a <a href="http://code.google.com/p/modwsgi/" rel="nofollow">WSGI service behind Apache</a> for the server. Apache can be set up to deal with HTTPS fairly simply.</p>
3
2008-09-15T16:34:53Z
[ "python", "client" ]
Best Python supported server/client protocol?
64,426
<p>I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.</p>
9
2008-09-15T16:27:47Z
64,572
<p>In the RPC field, Json-RPC will bring a big performance improvement over xml-rpc: <a href="http://json-rpc.org/wiki/python-json-rpc" rel="nofollow">http://json-rpc.org/wiki/python-json-rpc</a></p>
-1
2008-09-15T16:45:13Z
[ "python", "client" ]
Best Python supported server/client protocol?
64,426
<p>I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.</p>
9
2008-09-15T16:27:47Z
64,690
<p>XMLRPC is very simple to get started with, and at my previous job, we used it extensively for intra-node communication in a distributed system. As long as you keep track of the fact that the None value can't be easily transferred, it's dead easy to work with, and included in Python's standard library. </p> <p>Run it over https and add a username/password parameter to all calls, and you'll have simple security in place. Not sure about how easy it is to verify server certificate in Python, though.</p> <p>However, if you are transferring large amounts of data, the coding into XML might become a bottleneck, so using a <a href="http://sv.wikipedia.org/wiki/REST" rel="nofollow">REST</a>-inspired architecture over https may be as good as xmlrpclib.</p>
0
2008-09-15T16:58:29Z
[ "python", "client" ]
Best Python supported server/client protocol?
64,426
<p>I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.</p>
9
2008-09-15T16:27:47Z
76,560
<p>If you are looking to do file transfers, XMLRPC is likely a bad choice. It will require that you encode all of your data as XML (and load it into memory).</p> <p>"Data requests" and "file transfers" sounds a lot like plain old HTTP to me, but your statement of the problem doesn't make your requirements clear. What kind of information needs to be encoded in the request? Would a URL like "http://yourserver.example.com/service/request?color=yellow&amp;flavor=banana" be good enough?</p> <p>There are lots of HTTP clients and servers in Python, none of which are especially great, but all of which I'm sure will get the job done for basic file transfers. You can do security the "normal" web way, which is to use HTTPS and passwords, which will probably be sufficient.</p> <p>If you want two-way communication then HTTP falls down, and a protocol like Twisted's <a href="http://twistedmatrix.com/projects/core/documentation/howto/pb-intro.html" rel="nofollow">perspective broker (PB)</a> or <a href="http://twistedmatrix.com/documents/8.1.0/api/twisted.protocols.amp.html" rel="nofollow">asynchronous messaging protocol (AMP)</a> might suit you better. These protocols are certainly well-supported by Twisted.</p>
9
2008-09-16T20:23:37Z
[ "python", "client" ]
Best Python supported server/client protocol?
64,426
<p>I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.</p>
9
2008-09-15T16:27:47Z
256,826
<p>I suggest you look at 1. XMLRPC 2. JSONRPC 3. SOAP 4. REST/ATOM XMLRPC is a valid choice. Don't worry it is too old. That is not a problem. It is so simple that little needed changing since original specification. The pro is that in every programming langauge I know there is a library for a client to be written in. Certainly for python. I made it work with mod_python and had no problem at all. The big problem with it is its verbosity. For simple values there is a lot of XML overhead. You can gzip it of cause, but then you loose some debugging ability with the tools like Fiddler.</p> <p>My personal preference is JSONRPC. It has all of the XMLRPC advantages and it is very compact. Further, Javascript clients can "eval" it so no parsing is necessary. Most of them are built for version 1.0 of the standard. I have seen diverse attempts to improve on it, called 1.1 1.2 and 2.0 but they are not built one on top of another and, to my knowledge, are not widely supported yet. 2.0 looks the best, but I would still stick with 1.0 for now (October 2008)</p> <p>Third candidate would be REST/ATOM. REST is a principle, and ATOM is how you convey bulk of data when it needs to for POST, PUT requests and GET responses. For a very nice implementation of it, look at GData, Google's API. Real real nice.</p> <p>SOAP is old, and lots lots of libraries / langauges support it. IT is heeavy and complicated, but if your primary clients are .NET or Java, it might be worth the bother. Visual Studio would import your WSDL file and create a wrapper and to C# programmer it would look like local assembly indeed.</p> <p>The nice thing about all this, is that if you architect your solution right, existing libraries for Python would allow you support more then one with almost no overhead. XMLRPC and JSONRPC are especially good match.</p> <p>Regarding authentication. XMLRPC and JSONRPC don't bother defining one. It is independent thing from the serialization. So you can implement Basic Authentication, Digest Authentication or your own with any of those. I have seen couple of examples of client side Digest Authentication for python, but am yet to see the server based one. If you use Apache, you might not need one, using mod_auth_digest Apache module instead. This depens on the nature of your application</p> <p>Transport security. It is obvously SSL (HTTPS). I can't currently remember how XMLRPC deals with, but with JSONRPC implementation that I have it is trivial - you merely change http to https in your URLs to JSONRPC and it shall be going over SSL enabled transport.</p>
4
2008-11-02T12:10:07Z
[ "python", "client" ]
Best Python supported server/client protocol?
64,426
<p>I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.</p>
9
2008-09-15T16:27:47Z
256,833
<p>There is no need to use HTTP (indeed, HTTP is not good for RPC in general in some respects), and no need to use a standards-based protocol if you're talking about a python client talking to a python server.</p> <p>Use a Python-specific RPC library such as Pyro, or what Twisted provides (Twisted.spread).</p>
1
2008-11-02T12:17:54Z
[ "python", "client" ]
Best Python supported server/client protocol?
64,426
<p>I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.</p>
9
2008-09-15T16:27:47Z
257,415
<p>SSH can be a good choice for file transfer and remote control, especially if you are concerned with secure login. Most Linux and Solaris servers will already run an SSH service for administration, so if your Python program use ssh then you don't need to open up any additional ports or services on remote machines. </p> <p><a href="http://www.openssh.com/" rel="nofollow">OpenSSH</a> is the standard and portable SSH client and server, and can be used via subprocesses from Python. If you want more flexibility Twisted includes <a href="http://twistedmatrix.com/trac/wiki/TwistedConch" rel="nofollow">Twisted Conch</a> which is a SSH client and server implementation which provides flexible programmable control of an SSH stack, on both Linux and Windows. I use both in production.</p>
1
2008-11-02T21:34:54Z
[ "python", "client" ]
Best Python supported server/client protocol?
64,426
<p>I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.</p>
9
2008-09-15T16:27:47Z
280,853
<p><a href="http://incubator.apache.org/thrift/" rel="nofollow">Facebook's thrift</a> project may be a good answer. It uses a light-weight protocol to pass object around and allows you to use any language you wish. It may fall-down on security though as I believe there is none.</p>
0
2008-11-11T13:21:44Z
[ "python", "client" ]
Best Python supported server/client protocol?
64,426
<p>I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.</p>
9
2008-09-15T16:27:47Z
292,659
<p><a href="http://code.google.com/p/protobuf/">ProtocolBuffers</a> was released by Google as a way of serializing data in a very compact efficient way. They have support for C++, Java and Python. I haven't used it yet, but looking at the source, there seem to be RPC clients and servers for each language. </p> <p>I personally have used XML-RPC on several projects, and it always did exactly what I was hoping for. I was usually going between C++, Java and Python. I use libxmlrpc in Python often because it's easy to memorize and type interactively, but it is actually much slower than the alternative <a href="http://sourceforge.net/projects/py-xmlrpc/">pyxmlrpc</a>.</p> <p>PyAMF is mostly for RPC with Flash clients, but it's a compact RPC format worth looking at too.</p> <p>When you have Python on both ends, I don't believe anything beats <a href="http://pyro.sourceforge.net/">Pyro</a> (Python Remote Objects.) Pyro even has a "name server" that lets services announce their availability to a network. Clients use the name server to find the services it needs no matter where they're active at a particular moment. This gives you free redundancy, and the ability to move services from one machine to another without any downtime.</p> <p>For security, I'd tunnel over SSH, or use TLS or SSL at the connection level. Of course, all these options are essentially the same, they just have various difficulties of setup.</p>
7
2008-11-15T15:16:25Z
[ "python", "client" ]
Sending mail from Python using SMTP
64,505
<p>I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?</p> <pre><code>from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "John Doe &lt;[email protected]&gt;" to_addr = "[email protected]" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() </code></pre>
70
2008-09-15T16:36:35Z
64,554
<p>The main gotcha I see is that you're not handling any errors: .login() and .sendmail() both have documented exceptions that they can throw, and it seems like .connect() must have some way to indicate that it was unable to connect - probably an exception thrown by the underlying socket code.</p>
6
2008-09-15T16:43:36Z
[ "python", "smtp" ]
Sending mail from Python using SMTP
64,505
<p>I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?</p> <pre><code>from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "John Doe &lt;[email protected]&gt;" to_addr = "[email protected]" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() </code></pre>
70
2008-09-15T16:36:35Z
64,580
<p>You should make sure you format the date in the correct format - <a href="http://www.faqs.org/rfcs/rfc2822.html" rel="nofollow">RFC2822</a>.</p>
3
2008-09-15T16:46:00Z
[ "python", "smtp" ]
Sending mail from Python using SMTP
64,505
<p>I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?</p> <pre><code>from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "John Doe &lt;[email protected]&gt;" to_addr = "[email protected]" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() </code></pre>
70
2008-09-15T16:36:35Z
64,673
<p>Make sure you don't have any firewalls blocking SMTP. The first time I tried to send an email, it was blocked both by Windows Firewall and McAfee - took forever to find them both.</p>
5
2008-09-15T16:55:57Z
[ "python", "smtp" ]