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
list
Safe escape function for terminal output
437,476
<p>I'm looking for the equivalent of a <a href="http://docs.python.org/library/urllib.html#urllib.quote_plus" rel="nofollow">urlencode</a> for terminal output -- I need to make sure that garbage characters I (may) print from an external source don't end up doing funky things to my terminal, so a prepackaged function to escape special character sequences would be ideal.</p> <p>I'm working in Python, but anything I can readily translate works too. TIA!</p>
1
2009-01-12T23:33:46Z
440,891
<p>If logging or printing debugging output, I usually use <code>repr()</code> to get a harmless printable version of an object, including strings. This may or may not be what you wanted; the <code>cat --show-nonprinting</code> method others have used in other answers is better for lots of multi-line output.</p> <pre><code>x = get_weird_data() print repr(x) </code></pre>
1
2009-01-13T21:38:22Z
[ "python", "terminal", "escaping" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
437,591
<p>You can reload a module when it has already been imported by using the <a href="http://docs.python.org/library/functions.html?highlight=reload#reload"><code>reload</code></a> builtin function in Python 2:</p> <pre><code>import foo while True: # Do some things. if is_changed(foo): foo = reload(foo) </code></pre> <p>In Python 3, <code>reload</code> was moved to the <a href="https://docs.python.org/3.2/library/imp.html"><code>imp</code></a> module. In 3.4, <code>imp</code> was deprecated in favor of <a href="https://docs.python.org/3.4/library/importlib.html"><code>importlib</code></a>, and <code>reload</code> was added to the latter. When targeting 3 or later, either reference the appropriate module when calling <code>reload</code> or import it.</p> <p>I think that this is what you want. Web servers like Django's development server use this so that you can see the effects of your code changes without restarting the server process itself.</p> <p>To quote from the docs:</p> <blockquote> <p>Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time. As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero. The names in the module namespace are updated to point to any new or changed objects. Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.</p> </blockquote> <p>As you noted in your question, you'll have to reconstruct <code>Foo</code> objects if the <code>Foo</code> class resides in the <code>foo</code> module.</p>
386
2009-01-13T00:34:40Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
438,845
<p><code>reload(module)</code>, but only if it's completely stand-alone. If anything else has a reference to the module (or any object belonging to the module), then you'll get subtle and curious errors caused by the old code hanging around longer than you expected, and things like <code>isinstance</code> not working across different versions of the same code.</p> <p>If you have one-way dependencies, you must also reload all modules that depend on the the reloaded module to get rid of all the references to the old code. And then reload modules that depend on the reloaded modules, recursively.</p> <p>If you have circular dependencies, which is very common for example when you are dealing with reloading a package, you must unload all the modules in the group in one go. You can't do this with <code>reload()</code> because it will re-import each module before its dependencies have been refreshed, allowing old references to creep into new modules.</p> <p>The only way to do it in this case is to hack <code>sys.modules</code>, which is kind of unsupported. You'd have to go through and delete each <code>sys.modules</code> entry you wanted to be reloaded on next import, and also delete entries whose values are <code>None</code> to deal with an implementation issue to do with caching failed relative imports. It's not terribly nice but as long as you have a fully self-contained set of dependencies that doesn't leave references outside its codebase, it's workable.</p> <p>It's probably best to restart the server. :-)</p>
41
2009-01-13T12:53:25Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
487,718
<p>It can be especially difficult to delete a module if it is not pure Python.</p> <p>Here is some information from: <a href="http://web.archive.org/web/20080926094551/http://mail.python.org/pipermail/python-list/2003-December/241654.html">How do I really delete an imported module?</a></p> <blockquote> <p>You can use sys.getrefcount() to find out the actual number of references.</p> </blockquote> <pre><code>&gt;&gt;&gt; import sys, empty, os &gt;&gt;&gt; sys.getrefcount(sys) 9 &gt;&gt;&gt; sys.getrefcount(os) 6 &gt;&gt;&gt; sys.getrefcount(empty) 3 </code></pre> <blockquote> <p>Numbers greater than 3 indicate that it will be hard to get rid of the module. The homegrown "empty" (containing nothing) module should be garbage collected after</p> </blockquote> <pre><code>&gt;&gt;&gt; del sys.modules["empty"] &gt;&gt;&gt; del empty </code></pre> <blockquote> <p>as the third reference is an artifact of the getrefcount() function.</p> </blockquote>
54
2009-01-28T14:03:47Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
1,547,978
<p>In Python 3.0–3.3 you would use: <a href="http://docs.python.org/3.3/library/imp.html?highlight=imp#imp.reload"><code>imp.reload(module)</code></a></p> <p>The <a href="http://docs.python.org/3.3/glossary.html#term-bdfl">BDFL</a> has <a href="http://mail.python.org/pipermail/edu-sig/2008-February/008421.html">answered</a> this question.</p> <p>However, <a href="https://docs.python.org/dev/library/imp.html"><code>imp</code> was deprecated in 3.4, in favour of <code>importlib</code></a> (thanks <a href="http://stackoverflow.com/users/2068635/stefan">@Stefan!</a>).</p> <p>I <em>think</em>, therefore, you’d now use <a href="https://docs.python.org/dev/library/importlib.html#importlib.reload"><code>importlib.reload(module)</code></a>, although I’m not sure.</p>
166
2009-10-10T13:36:30Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
2,794,845
<p>For those like me who want to unload all modules (when running in the Python interpreter under <a href="http://en.wikipedia.org/wiki/Emacs" rel="nofollow">Emacs</a>):</p> <pre><code> for mod in sys.modules.values(): reload(mod) </code></pre> <p>More information is in <em><a href="http://pyunit.sourceforge.net/notes/reloading.html" rel="nofollow">Reloading Python modules</a></em>.</p>
3
2010-05-08T16:50:12Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
3,194,343
<pre><code>if 'myModule' in sys.modules: del sys.modules["myModule"] </code></pre>
39
2010-07-07T11:44:10Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
13,477,119
<p>The following code allows you Python 2/3 compatibility:</p> <pre><code>try: reload except NameError: # Python 3 from imp import reload </code></pre> <p>The you can use it as <code>reload()</code> in both versions which makes things simpler.</p>
13
2012-11-20T16:01:08Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
26,080,151
<p>The accepted answer doesn't handle the from X import Y case. This code handles it and the standard import case as well:</p> <pre><code>def importOrReload(module_name, *names): import sys if module_name in sys.modules: reload(sys.modules[module_name]) else: __import__(module_name, fromlist=names) for name in names: globals()[name] = getattr(sys.modules[module_name], name) # use instead of: from dfly_parser import parseMessages importOrReload("dfly_parser", "parseMessages") </code></pre> <p>In the reloading case, we reassign the top level names to the values stored in the newly reloaded module, which updates them.</p>
6
2014-09-27T23:30:59Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
28,464,606
<p>Another way could be to import the module in a function. This way when the function completes the module gets garbage collected. </p>
1
2015-02-11T21:13:42Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
31,906,907
<p>For Python 2 use built-in function <a href="https://docs.python.org/2/library/functions.html#reload">reload()</a>:</p> <pre><code>reload(module) </code></pre> <p>For Python 2 and 3.2–3.3 use <a href="https://docs.python.org/3/library/imp.html#imp.reload">reload from module imp</a>:</p> <pre><code>imp.reload(module) </code></pre> <p>But <code>imp</code> <a href="https://docs.python.org/3/library/imp.html">is deprecated</a> since version 3.4 <a href="https://docs.python.org/3/library/importlib.html#importlib.reload">in favor of importlib</a>, so use:</p> <pre><code>importlib.reload(module) </code></pre>
9
2015-08-09T17:28:31Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
34,688,584
<p>Enthought Traits has a module that works fairly well for this. <a href="https://traits.readthedocs.org/en/4.3.0/_modules/traits/util/refresh.html" rel="nofollow">https://traits.readthedocs.org/en/4.3.0/_modules/traits/util/refresh.html</a></p> <p>It will reload any module that has been changed, and update other modules and instanced objects that are using it. It does not work most of the time with <code>__very_private__</code> methods, and can choke on class inheritance, but it saves me crazy amounts of time from having to restart the host application when writing PyQt guis, or stuff that runs inside programs such as Maya or Nuke. It doesn't work maybe 20-30 % of the time, but it's still incredibly helpful.</p> <p>Enthought's package doesn't reload files the moment they change - you have to call it explicitely - but that shouldn't be all that hard to implement if you really need it</p>
0
2016-01-09T01:06:14Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
35,226,553
<p>for me for case of Abaqus it is the way it works. Imagine your file is Class_VerticesEdges.py</p> <pre><code>sys.path.append('D:\...\My Pythons') if 'Class_VerticesEdges' in sys.modules: del sys.modules['Class_VerticesEdges'] print 'old module Class_VerticesEdges deleted' from Class_VerticesEdges import * reload(sys.modules['Class_VerticesEdges']) </code></pre>
1
2016-02-05T14:27:12Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
35,820,421
<p>I had the same problem when using a dynamic module in py2exe app. As py2exe always keep bytecode in zip directory reload was not working.</p> <p>But I found a working solution using import_file module. Now my application is working fine.</p>
0
2016-03-05T21:57:09Z
[ "python", "module", "reload", "python-import" ]
How do I unload (reload) a Python module?
437,589
<p>I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?</p> <pre><code>if foo.py has changed: unimport foo &lt;-- How do I do this? import foo myfoo = foo.Foo() </code></pre>
410
2009-01-13T00:33:36Z
40,139,977
<p>If <code>foo</code> is given an alias then reload the alias as <code>reload(foo)</code> raises an exception.</p> <pre><code>import foo as bar # Do things reload(bar) </code></pre>
0
2016-10-19T19:27:48Z
[ "python", "module", "reload", "python-import" ]
Google App Engine - Importing my own source modules (multiple files)
437,791
<p>I am writing a GAE application and am having some difficulty with the following problem.</p> <p>I've created multiple python files (say a.py and b.py) which are both stored in the same folder. I am able to call code in a.py or b.py by mapping URL's to them (using app.yaml). What I haven't figured out how to do is import the code from one into another. </p> <p>Can anyone help me with the syntax and/or any config that is required here? For instance, I am under the impression that I can include the code from b.py in the file a.py by issuing the following statement in a.py</p> <pre><code>import b </code></pre> <p>I'm not having any success with this approach. Specifically I receive this error:</p> <pre><code>ImportError: No module named b </code></pre> <p>Any suggestions?</p> <p>Thanks, </p> <p>Matt</p>
3
2009-01-13T02:33:57Z
437,845
<p>Have you tried importing as if you were starting at the top level? Like </p> <pre> import modules.b </pre>
8
2009-01-13T03:10:46Z
[ "python", "google-app-engine" ]
Google App Engine - Importing my own source modules (multiple files)
437,791
<p>I am writing a GAE application and am having some difficulty with the following problem.</p> <p>I've created multiple python files (say a.py and b.py) which are both stored in the same folder. I am able to call code in a.py or b.py by mapping URL's to them (using app.yaml). What I haven't figured out how to do is import the code from one into another. </p> <p>Can anyone help me with the syntax and/or any config that is required here? For instance, I am under the impression that I can include the code from b.py in the file a.py by issuing the following statement in a.py</p> <pre><code>import b </code></pre> <p>I'm not having any success with this approach. Specifically I receive this error:</p> <pre><code>ImportError: No module named b </code></pre> <p>Any suggestions?</p> <p>Thanks, </p> <p>Matt</p>
3
2009-01-13T02:33:57Z
437,851
<p>If the files a.py and b.py aren't located, be sure to include the respective paths in <code>sys.path</code>.</p> <pre><code>import sys sys.path.append(r"/parent/of/module/b") </code></pre>
2
2009-01-13T03:17:15Z
[ "python", "google-app-engine" ]
Google App Engine - Importing my own source modules (multiple files)
437,791
<p>I am writing a GAE application and am having some difficulty with the following problem.</p> <p>I've created multiple python files (say a.py and b.py) which are both stored in the same folder. I am able to call code in a.py or b.py by mapping URL's to them (using app.yaml). What I haven't figured out how to do is import the code from one into another. </p> <p>Can anyone help me with the syntax and/or any config that is required here? For instance, I am under the impression that I can include the code from b.py in the file a.py by issuing the following statement in a.py</p> <pre><code>import b </code></pre> <p>I'm not having any success with this approach. Specifically I receive this error:</p> <pre><code>ImportError: No module named b </code></pre> <p>Any suggestions?</p> <p>Thanks, </p> <p>Matt</p>
3
2009-01-13T02:33:57Z
438,551
<p>Note that the usual pattern with GAE is not to have each one independently mapped in app.yaml, but rather to have a single 'handler' script that has all (or all but static and special) URLs mapped to it, and have that script import both a and b and use Handlers they define.</p>
1
2009-01-13T10:33:11Z
[ "python", "google-app-engine" ]
Google App Engine - Importing my own source modules (multiple files)
437,791
<p>I am writing a GAE application and am having some difficulty with the following problem.</p> <p>I've created multiple python files (say a.py and b.py) which are both stored in the same folder. I am able to call code in a.py or b.py by mapping URL's to them (using app.yaml). What I haven't figured out how to do is import the code from one into another. </p> <p>Can anyone help me with the syntax and/or any config that is required here? For instance, I am under the impression that I can include the code from b.py in the file a.py by issuing the following statement in a.py</p> <pre><code>import b </code></pre> <p>I'm not having any success with this approach. Specifically I receive this error:</p> <pre><code>ImportError: No module named b </code></pre> <p>Any suggestions?</p> <p>Thanks, </p> <p>Matt</p>
3
2009-01-13T02:33:57Z
4,543,887
<p>as @toby said, it must be imported as if importing from the top directory, and a file named <strong>init</strong>.py must be placed in the folder.</p>
1
2010-12-28T05:29:56Z
[ "python", "google-app-engine" ]
Help needed--Is class necessary in Python scripting?
438,149
<p>I am creating an interface for Python scripting. Later I will be dong Python scripting also for automated testing. Is it necessary the at i must use class in my code.Now I have created the code with dictionaries,lists,functions,global and local variables.</p> <p>Is class necessary?</p> <p>Help me in this.</p>
0
2009-01-13T06:42:52Z
438,171
<p>No, of course class is not <em>a must</em>. As Python is a scripting language, you can simply code your scripts without defining your own classes. Classes are useful if you implement a more complex program which needs a structured approach and OOP benfits (encapsulation, polimorphism) help you in doing it.</p>
10
2009-01-13T06:58:47Z
[ "python", "class", "scripting" ]
Help needed--Is class necessary in Python scripting?
438,149
<p>I am creating an interface for Python scripting. Later I will be dong Python scripting also for automated testing. Is it necessary the at i must use class in my code.Now I have created the code with dictionaries,lists,functions,global and local variables.</p> <p>Is class necessary?</p> <p>Help me in this.</p>
0
2009-01-13T06:42:52Z
438,239
<p>It's not needed to make it work, but I would argue that it will become messy to maintain if you do not encapsulate certain things in classes. Classes are something that schould help the programmer to organizes his/her code, not just nice to have fluff.</p>
1
2009-01-13T07:46:57Z
[ "python", "class", "scripting" ]
Help needed--Is class necessary in Python scripting?
438,149
<p>I am creating an interface for Python scripting. Later I will be dong Python scripting also for automated testing. Is it necessary the at i must use class in my code.Now I have created the code with dictionaries,lists,functions,global and local variables.</p> <p>Is class necessary?</p> <p>Help me in this.</p>
0
2009-01-13T06:42:52Z
438,753
<p>No you don't need to use classes for scripting.</p> <p>However, when you start using the unit testing framework unittest, that will involve classes so you need to understand at least how to sub-class the TestCase class, eg:</p> <pre><code>import unittest import os class TestLint(unittest.TestCase): def testLintCreatesLog(self): # stuff that does things to create the file lint.log removed... assert os.path.exists('lint.log') # this should be here after lint assert os.path.getsize('lint.log') == 0 # nothing in the log - assume happy if __name__ == '__main__': # When this module is executed from the command-line, run all its tests unittest.main() </code></pre>
1
2009-01-13T12:05:55Z
[ "python", "class", "scripting" ]
Help needed--Is class necessary in Python scripting?
438,149
<p>I am creating an interface for Python scripting. Later I will be dong Python scripting also for automated testing. Is it necessary the at i must use class in my code.Now I have created the code with dictionaries,lists,functions,global and local variables.</p> <p>Is class necessary?</p> <p>Help me in this.</p>
0
2009-01-13T06:42:52Z
1,992,389
<p>not necessary since python is not a purely object oriented language but certain things are better written in classes (encapsulation).it becomes easier to build a large project using classes</p>
0
2010-01-02T18:39:29Z
[ "python", "class", "scripting" ]
Python data structure: SQL, XML, or .py file
438,185
<p>What is the best way to store large amounts of data in python, given one (or two) 500,000 item+ dictionary used for undirected graph searching?</p> <p>I've been considering a few options such as storing the data as XML:</p> <pre><code>&lt;key name="a"&gt; &lt;value data="1" /&gt; &lt;value data="2" /&gt; &lt;/key&gt; &lt;key name="b"&gt; ... </code></pre> <p>or in a python file for direct access:</p> <pre><code>db = {"a": [1, 2], "b": ...} </code></pre> <p>or in a SQL database? I'm thinking this would be the best solution, but would I have to rely more on SQL to do the computation than python itself?</p>
4
2009-01-13T07:10:34Z
438,226
<p>I would consider using one of the many graph libraries available for python (e.g. <a href="http://code.google.com/p/python-graph/" rel="nofollow">python-graph</a>)</p>
2
2009-01-13T07:36:51Z
[ "python", "sql", "xml", "data-structures", "graph" ]
Python data structure: SQL, XML, or .py file
438,185
<p>What is the best way to store large amounts of data in python, given one (or two) 500,000 item+ dictionary used for undirected graph searching?</p> <p>I've been considering a few options such as storing the data as XML:</p> <pre><code>&lt;key name="a"&gt; &lt;value data="1" /&gt; &lt;value data="2" /&gt; &lt;/key&gt; &lt;key name="b"&gt; ... </code></pre> <p>or in a python file for direct access:</p> <pre><code>db = {"a": [1, 2], "b": ...} </code></pre> <p>or in a SQL database? I'm thinking this would be the best solution, but would I have to rely more on SQL to do the computation than python itself?</p>
4
2009-01-13T07:10:34Z
438,233
<p>You need to specify your problem a bit better. I'll make a few assumptions: 1) your data is static and you just want to search it, 2) you have enough memory to store it.</p> <p>If application startup speed is not critical, the data format is up to you, just as long as you can get it into Python memory. Use simple data types (dicts, lists, strings) to store data, not an XML graph, if you want to access it quickly. You might consider writing a lightweight class of your own to express nodes and store links to other nodes in a dict or array.</p> <p>If application startup time is critical, consider loading your data in a Python program and pickling it out to a file; you can then load the pickled data structure (which should be really fast) in the production application.</p> <p>If, on the other hand, your data is too big to fit in memory, or you want to be able to modify it persistently, you could use SQL for storage (either an external server or an SQLite database) or ZODB (a Python object database). </p>
1
2009-01-13T07:41:14Z
[ "python", "sql", "xml", "data-structures", "graph" ]
Python data structure: SQL, XML, or .py file
438,185
<p>What is the best way to store large amounts of data in python, given one (or two) 500,000 item+ dictionary used for undirected graph searching?</p> <p>I've been considering a few options such as storing the data as XML:</p> <pre><code>&lt;key name="a"&gt; &lt;value data="1" /&gt; &lt;value data="2" /&gt; &lt;/key&gt; &lt;key name="b"&gt; ... </code></pre> <p>or in a python file for direct access:</p> <pre><code>db = {"a": [1, 2], "b": ...} </code></pre> <p>or in a SQL database? I'm thinking this would be the best solution, but would I have to rely more on SQL to do the computation than python itself?</p>
4
2009-01-13T07:10:34Z
438,234
<p>If you store your data on an XML file it will be easier to modify (i.e. using notepad ...) but you must take in account that reading and parsing all that amount of data from a XML file is a heavy duty. Using a SQL database (maybe PostGres) will make the choiche some more performant, DMBS are more optimized than direct filesystem reading/parsing. If you store all your data in some Python structure on a separate file, you can than have the advantage of bytecode compilation (.pyc) that doesn't give a boost in computational therms but allows for a faster load (wich is what you want). I would choose the last one.</p>
0
2009-01-13T07:41:16Z
[ "python", "sql", "xml", "data-structures", "graph" ]
Python data structure: SQL, XML, or .py file
438,185
<p>What is the best way to store large amounts of data in python, given one (or two) 500,000 item+ dictionary used for undirected graph searching?</p> <p>I've been considering a few options such as storing the data as XML:</p> <pre><code>&lt;key name="a"&gt; &lt;value data="1" /&gt; &lt;value data="2" /&gt; &lt;/key&gt; &lt;key name="b"&gt; ... </code></pre> <p>or in a python file for direct access:</p> <pre><code>db = {"a": [1, 2], "b": ...} </code></pre> <p>or in a SQL database? I'm thinking this would be the best solution, but would I have to rely more on SQL to do the computation than python itself?</p>
4
2009-01-13T07:10:34Z
438,242
<p>XML is really oriented to tree structures and is very verbose. You can look at RDF for ways to describe a graph in XML but it still has other disadvantages, e.g. the time to read, parse, and instantiate 500k+ objects and the amount of file space used.</p> <p>SQL is really oriented to describing rows in tables. You can store graphs of course, but you'll see a performance penalty here too.</p> <p>I would try python pickling first to see if it meets your needs. It will probably be the most compact and the fastest to read in and instantiate all the objects.</p> <p>Really the only reason to use other formats is if you need something they offer, e.g. transactions in SQL or cross-language processing of XML.</p>
0
2009-01-13T07:47:53Z
[ "python", "sql", "xml", "data-structures", "graph" ]
Python data structure: SQL, XML, or .py file
438,185
<p>What is the best way to store large amounts of data in python, given one (or two) 500,000 item+ dictionary used for undirected graph searching?</p> <p>I've been considering a few options such as storing the data as XML:</p> <pre><code>&lt;key name="a"&gt; &lt;value data="1" /&gt; &lt;value data="2" /&gt; &lt;/key&gt; &lt;key name="b"&gt; ... </code></pre> <p>or in a python file for direct access:</p> <pre><code>db = {"a": [1, 2], "b": ...} </code></pre> <p>or in a SQL database? I'm thinking this would be the best solution, but would I have to rely more on SQL to do the computation than python itself?</p>
4
2009-01-13T07:10:34Z
438,245
<p>The python file approach will surely be the fastest if you have a way to maintain the file.</p>
0
2009-01-13T07:48:24Z
[ "python", "sql", "xml", "data-structures", "graph" ]
Python data structure: SQL, XML, or .py file
438,185
<p>What is the best way to store large amounts of data in python, given one (or two) 500,000 item+ dictionary used for undirected graph searching?</p> <p>I've been considering a few options such as storing the data as XML:</p> <pre><code>&lt;key name="a"&gt; &lt;value data="1" /&gt; &lt;value data="2" /&gt; &lt;/key&gt; &lt;key name="b"&gt; ... </code></pre> <p>or in a python file for direct access:</p> <pre><code>db = {"a": [1, 2], "b": ...} </code></pre> <p>or in a SQL database? I'm thinking this would be the best solution, but would I have to rely more on SQL to do the computation than python itself?</p>
4
2009-01-13T07:10:34Z
438,710
<p>The Python source technique absolutely rules.</p> <p>XML is slow to parse, and relatively hard to read by people. That's why companies like Altova are in business -- XML isn't pleasant to edit.</p> <p>Python source <code>db = {"a": [1, 2], "b": ...}</code> is </p> <ol> <li><p>Fast to parse.</p></li> <li><p>Easy to read by people. </p></li> </ol> <p>If you have programs that read and write giant dictionaries, use <code>pprint</code> for the writing so that you get a nicely formatted output. Something easier to read.</p> <p>If you're worried about portability, consider YAML (or JSON) for serializing the object. They parse quickly also, and are much, much easier to read than XML.</p>
6
2009-01-13T11:37:45Z
[ "python", "sql", "xml", "data-structures", "graph" ]
Is there a pure Python Lucene?
438,315
<p>The ruby folks have <a href="https://github.com/dbalmain/ferret">Ferret</a>. Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.</p>
26
2009-01-13T08:24:28Z
438,394
<p><a href="http://sourceforge.net/project/showfiles.php?group_id=76541&amp;package_id=77267" rel="nofollow">lupy</a> was a lucene port to pure python.<a href="http://divmod.org/trac/wiki/WhitherLupy" rel="nofollow">The lupy people suggest that you use PyLucene</a>. Sorry. Maybe you can use the Java sources in combination with <a href="http://www.jython.org/Project/" rel="nofollow">Jython</a>.</p>
2
2009-01-13T09:07:56Z
[ "python", "full-text-search", "lucene", "ferret" ]
Is there a pure Python Lucene?
438,315
<p>The ruby folks have <a href="https://github.com/dbalmain/ferret">Ferret</a>. Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.</p>
26
2009-01-13T08:24:28Z
438,499
<p>The only one pure-python (not involving even C extension) search solution I know of is <a href="http://nucular.sourceforge.net/">Nucular</a>. It's slow (much slower than PyLucene) and unstable yet.</p> <p>We moved from PyLucene-based home baked search and indexing to <a href="http://lucene.apache.org/solr/">Solr</a> but YMMV.</p>
5
2009-01-13T10:01:09Z
[ "python", "full-text-search", "lucene", "ferret" ]
Is there a pure Python Lucene?
438,315
<p>The ruby folks have <a href="https://github.com/dbalmain/ferret">Ferret</a>. Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.</p>
26
2009-01-13T08:24:28Z
439,381
<p>I recently found <a href="http://swapoff.org/pyndexter" rel="nofollow">pyndexter</a>. It provides abstract interface to various different backend full-text search engines/indexers. And it ships with a default pure-python implementation.</p> <p>These things can be disastrously slow though in Python.</p>
4
2009-01-13T15:31:45Z
[ "python", "full-text-search", "lucene", "ferret" ]
Is there a pure Python Lucene?
438,315
<p>The ruby folks have <a href="https://github.com/dbalmain/ferret">Ferret</a>. Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.</p>
26
2009-01-13T08:24:28Z
439,757
<p>For some applications pure Python is overrated. Take a look at Xapian.</p>
3
2009-01-13T16:46:45Z
[ "python", "full-text-search", "lucene", "ferret" ]
Is there a pure Python Lucene?
438,315
<p>The ruby folks have <a href="https://github.com/dbalmain/ferret">Ferret</a>. Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.</p>
26
2009-01-13T08:24:28Z
521,636
<p>After weeks of searching for this, I found a nice Python solution: <a href="http://static.repoze.org/catalogdocs/" rel="nofollow">repoze.catalog</a>. It's not strictly Python-only because it uses ZODB for storage, but it seems a better dependency to me than something like SOLR.</p>
1
2009-02-06T18:47:09Z
[ "python", "full-text-search", "lucene", "ferret" ]
Is there a pure Python Lucene?
438,315
<p>The ruby folks have <a href="https://github.com/dbalmain/ferret">Ferret</a>. Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.</p>
26
2009-01-13T08:24:28Z
522,812
<p>+1 to the Xapian and Pyndexter answers.</p> <p>Ferret is actually written in C with Ruby bindings on top. A pure Ruby search engine would be even slower than a pure Python one. I would love to see "someone else" write a Cython/Pyrex layer for Python interface to Ferret, but won't do it myself because why bother when there are Python bindings for Xapian.</p>
2
2009-02-07T00:44:56Z
[ "python", "full-text-search", "lucene", "ferret" ]
Is there a pure Python Lucene?
438,315
<p>The ruby folks have <a href="https://github.com/dbalmain/ferret">Ferret</a>. Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.</p>
26
2009-01-13T08:24:28Z
533,603
<p><a href="http://pypi.python.org/pypi/Whoosh/">Whoosh</a> is a new project which is similar to lucene, but is pure python.</p>
28
2009-02-10T18:43:11Z
[ "python", "full-text-search", "lucene", "ferret" ]
Is there a pure Python Lucene?
438,315
<p>The ruby folks have <a href="https://github.com/dbalmain/ferret">Ferret</a>. Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.</p>
26
2009-01-13T08:24:28Z
3,816,536
<p>For non-pure Python, <a href="http://sphinxsearch.com" rel="nofollow">Sphinx Search</a> with Python API works the fastest. From the benchmarks from multiple blogs, Sphinx Search is way faster than Lucene, uses way less memory and it is in C.</p> <p>I am developing a multi-document search engine based on it, using python and <a href="http://web2py.com" rel="nofollow">web2py</a> as framework.</p>
2
2010-09-28T19:56:24Z
[ "python", "full-text-search", "lucene", "ferret" ]
Exception handling of a function in Python
438,401
<p>Suppose I have a function definiton:</p> <pre><code>def test(): print 'hi' </code></pre> <p>I get a TypeError whenever I gives an argument.</p> <p>Now, I want to put the def statement in try. How do I do this?</p>
0
2009-01-13T09:11:11Z
438,409
<pre><code>try: test() except TypeError: print "error" </code></pre>
5
2009-01-13T09:13:25Z
[ "python", "exception-handling" ]
Exception handling of a function in Python
438,401
<p>Suppose I have a function definiton:</p> <pre><code>def test(): print 'hi' </code></pre> <p>I get a TypeError whenever I gives an argument.</p> <p>Now, I want to put the def statement in try. How do I do this?</p>
0
2009-01-13T09:11:11Z
438,421
<pre><code>In [1]: def test(): ...: print 'hi' ...: In [2]: try: ...: test(1) ...: except: ...: print 'exception' ...: exception </code></pre> <p>Here is the relevant section in the <a href="http://docs.python.org/tutorial/errors.html" rel="nofollow">tutorial</a></p> <p>By the way. to fix this error, you should not wrap the function call in a try-except. Instead call it with the right number of arguments!</p>
1
2009-01-13T09:21:27Z
[ "python", "exception-handling" ]
Exception handling of a function in Python
438,401
<p>Suppose I have a function definiton:</p> <pre><code>def test(): print 'hi' </code></pre> <p>I get a TypeError whenever I gives an argument.</p> <p>Now, I want to put the def statement in try. How do I do this?</p>
0
2009-01-13T09:11:11Z
438,575
<p>You said</p> <blockquote> <p>Now, I want to put the def statement in try. How to do this.</p> </blockquote> <p>The <code>def</code> statement is correct, it is not raising any exceptions. So putting it in a <code>try</code> won't do anything.</p> <p>What raises the exception is the actual call to the function. So that should be put in the <code>try</code> instead:</p> <pre><code>try: test() except TypeError: print "error" </code></pre>
1
2009-01-13T10:42:30Z
[ "python", "exception-handling" ]
Exception handling of a function in Python
438,401
<p>Suppose I have a function definiton:</p> <pre><code>def test(): print 'hi' </code></pre> <p>I get a TypeError whenever I gives an argument.</p> <p>Now, I want to put the def statement in try. How do I do this?</p>
0
2009-01-13T09:11:11Z
440,791
<p>This is valid:</p> <pre><code>try: def test(): print 'hi' except: print 'error' test() </code></pre>
0
2009-01-13T21:05:39Z
[ "python", "exception-handling" ]
Exception handling of a function in Python
438,401
<p>Suppose I have a function definiton:</p> <pre><code>def test(): print 'hi' </code></pre> <p>I get a TypeError whenever I gives an argument.</p> <p>Now, I want to put the def statement in try. How do I do this?</p>
0
2009-01-13T09:11:11Z
440,839
<p>If you want to throw the error at call-time, which it sounds like you might want, you could try this aproach:</p> <pre><code>def test(*args): if args: raise print 'hi' </code></pre> <p>This will shift the error from the calling location to the function. It accepts any number of parameters via the <code>*args</code> list. Not that I know why you'd want to do that.</p>
1
2009-01-13T21:20:28Z
[ "python", "exception-handling" ]
Exception handling of a function in Python
438,401
<p>Suppose I have a function definiton:</p> <pre><code>def test(): print 'hi' </code></pre> <p>I get a TypeError whenever I gives an argument.</p> <p>Now, I want to put the def statement in try. How do I do this?</p>
0
2009-01-13T09:11:11Z
440,842
<p>A better way to handle a variable number of arguments in Python is as follows:</p> <pre><code>def foo(*args, **kwargs): # args will hold the positional arguments print args # kwargs will hold the named arguments print kwargs # Now, all of these work foo(1) foo(1,2) foo(1,2,third=3) </code></pre>
1
2009-01-13T21:21:03Z
[ "python", "exception-handling" ]
Is there a way to automatically generate a list of columns that need indexing?
438,559
<p>The beauty of ORM lulled me into a soporific sleep. I've got an existing Django app with a lack of database indexes. Is there a way to automatically generate a list of columns that need indexing?</p> <p>I was thinking maybe some middleware that logs which columns are involved in WHERE clauses? but is there anything built into MySQL that might help?</p>
5
2009-01-13T10:36:01Z
438,571
<p>Yes, there is.</p> <p>If you take a look at the <a href="http://dev.mysql.com/doc/refman/5.1/en/slow-query-log.html" rel="nofollow">slow query log</a>, there's an option <code>--log-queries-not-using-indexes</code></p>
4
2009-01-13T10:40:25Z
[ "python", "mysql", "database", "django", "django-models" ]
Is there a way to automatically generate a list of columns that need indexing?
438,559
<p>The beauty of ORM lulled me into a soporific sleep. I've got an existing Django app with a lack of database indexes. Is there a way to automatically generate a list of columns that need indexing?</p> <p>I was thinking maybe some middleware that logs which columns are involved in WHERE clauses? but is there anything built into MySQL that might help?</p>
5
2009-01-13T10:36:01Z
438,700
<p>No.</p> <p>Adding indexes willy-nilly to all "slow" queries will also slow down inserts, updates and deletes.</p> <p>Indexes are a balancing act between fast queries and fast changes. There is no general or "right" answer. There's certainly nothing that can automate this.</p> <p>You have to measure the improvement across your whole application as you add and change indexes.</p>
4
2009-01-13T11:32:53Z
[ "python", "mysql", "database", "django", "django-models" ]
How to call java objects and functions from CPython?
438,594
<p>I have a python program, which runs on the CPython implementation, and inside it I must call a function defined in a java program. How can I do this?</p> <p>It would be nice to be able to use some java objects too.</p> <p>Jython is not an option. I must run the python part in CPython.</p>
8
2009-01-13T10:49:01Z
438,643
<p>I don't know for Python, byt last time I had to call java from C application (NT service) I had to load jvm.dll. Take a look at JNI documentation.</p> <p>Also, you call always call os.system("java com.myapp.MyClass") if you are not concerned about performance.</p>
1
2009-01-13T11:11:40Z
[ "java", "python", "function", "language-interoperability" ]
How to call java objects and functions from CPython?
438,594
<p>I have a python program, which runs on the CPython implementation, and inside it I must call a function defined in a java program. How can I do this?</p> <p>It would be nice to be able to use some java objects too.</p> <p>Jython is not an option. I must run the python part in CPython.</p>
8
2009-01-13T10:49:01Z
438,658
<p>You'll have to create a python C extension that embeds Java - based on something like <a href="http://www.javaworld.com/javaworld/jw-05-2001/jw-0511-legacy.html" rel="nofollow">http://www.javaworld.com/javaworld/jw-05-2001/jw-0511-legacy.html</a> or else you'll have to start java in a separate subprocess.</p>
1
2009-01-13T11:15:46Z
[ "java", "python", "function", "language-interoperability" ]
How to call java objects and functions from CPython?
438,594
<p>I have a python program, which runs on the CPython implementation, and inside it I must call a function defined in a java program. How can I do this?</p> <p>It would be nice to be able to use some java objects too.</p> <p>Jython is not an option. I must run the python part in CPython.</p>
8
2009-01-13T10:49:01Z
438,693
<p>The easiest thing to do is </p> <ol> <li><p>Write a trivial CLI for your java "function". (There's no such thing, so I'll assume you actually mean a method function of a Java class.) </p> <pre><code>public class ExposeAMethod { public static void main( String args[] ) { TheClassToExpose x = new TheClassToExpose(); x.theFunction(); } } </code></pre></li> <li><p>Compile and build an executable JAR file with this as the entry point. Call it <code>ExposeAMethod.jar</code></p></li> <li><p>Call this from a command created by subprocess.</p> <pre><code>import subprocess p = subprocess.Popen("java -jar ExposeAMethod.jar", shell=True) sts = os.waitpid(p.pid, 0) </code></pre></li> </ol> <p>This is the minimum. And it's really not much. I count 6 lines of java, 3 lines of Python and you're up and running.</p> <p>If you want to pass arguments to this Java class constructor or method function, you'll have to write a few more lines of code. You have two choices.</p> <ul> <li><p>Read the arguments from stdin, write the results on stdout. This is relatively easy and performs really well.</p></li> <li><p>Parse the arguments as command-line options to Java, write the results on stdout. This is slightly harder, but generalizes very nicely. The bonus is that you now have a useful command-line Java program that you can reuse.</p></li> </ul>
7
2009-01-13T11:28:40Z
[ "java", "python", "function", "language-interoperability" ]
How to call java objects and functions from CPython?
438,594
<p>I have a python program, which runs on the CPython implementation, and inside it I must call a function defined in a java program. How can I do this?</p> <p>It would be nice to be able to use some java objects too.</p> <p>Jython is not an option. I must run the python part in CPython.</p>
8
2009-01-13T10:49:01Z
444,447
<p>If you don't want to go the write your own JNI/C route.</p> <p>The other option is to use jpype which for me is always what I use to access Oracle databases becuase installing the oracle c drivers on a PC is a pita. You can do stuff like (from docs):</p> <pre><code> from jpype import * startJVM("d:/tools/j2sdk/jre/bin/client/jvm.dll", "-ea") # or path to your jvm java.lang.System.out.println("hello world") shutdownJVM() </code></pre> <p>It hasn't been updated in a while and there isn't much in the way of documentation but it does work reasonably well.</p> <ul> <li><a href="http://jpype.sourceforge.net/" rel="nofollow">homepage</a></li> <li><a href="http://jpype.sourceforge.net/doc/user-guide/userguide.html#using" rel="nofollow">docs</a></li> </ul>
6
2009-01-14T20:00:08Z
[ "java", "python", "function", "language-interoperability" ]
How to call java objects and functions from CPython?
438,594
<p>I have a python program, which runs on the CPython implementation, and inside it I must call a function defined in a java program. How can I do this?</p> <p>It would be nice to be able to use some java objects too.</p> <p>Jython is not an option. I must run the python part in CPython.</p>
8
2009-01-13T10:49:01Z
3,793,504
<p>Apologies for resurrecting the thread, but I think I have a better answer :-)</p> <p>You could also use <a href="http://py4j.sourceforge.net/index.html">Py4J</a> which has two parts: a library that runs in CPython (or any Python interpreter for that matter) and a library that runs on the Java VM you want to call. </p> <p>There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:</p> <pre><code>&gt;&gt;&gt; from py4j.java_gateway import JavaGateway &gt;&gt;&gt; gateway = JavaGateway() # connect to the JVM &gt;&gt;&gt; java_object = gateway.jvm.mypackage.MyClass() # invoke constructor &gt;&gt;&gt; other_object = java_object.doThat() &gt;&gt;&gt; other_object.doThis(1,'abc') &gt;&gt;&gt; gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method </code></pre> <p>The communication is done through sockets instead of JNI.</p> <p><em>Disclaimer: I am the author of Py4J</em></p>
12
2010-09-25T10:55:08Z
[ "java", "python", "function", "language-interoperability" ]
How to call java objects and functions from CPython?
438,594
<p>I have a python program, which runs on the CPython implementation, and inside it I must call a function defined in a java program. How can I do this?</p> <p>It would be nice to be able to use some java objects too.</p> <p>Jython is not an option. I must run the python part in CPython.</p>
8
2009-01-13T10:49:01Z
24,247,890
<p>Look at our project <a href="https://pypi.python.org/pypi?name=javabridge&amp;%3aaction=display" rel="nofollow">python-javabridge</a>. It's a Python wrapper around the JNI, heavily used by <a href="http://cellprofiler.org" rel="nofollow">CellProfiler</a>. It offers both low-level access to the JNI and a high-level reflection-based access to Java objects.</p>
0
2014-06-16T16:07:00Z
[ "java", "python", "function", "language-interoperability" ]
Help in FileNotFoundException -Python
438,733
<p>This is my code:</p> <pre><code>try: import clr, sys from xml.dom.minidom import parse import datetime sys.path.append("C:\\teest") clr.AddReference("TCdll") from ClassLibrary1 import Class1 cl = Class1() except ( ImportError ) : print "Module may not be existing " </code></pre> <p>My TCdll is in C:\test.I just gave it as C:\teest to know the error.</p> <p>Exception is this:</p> <pre><code> Traceback (most recent call last): File "C:/Python25/13thjan/PSE.py", line 8, in &lt;module&gt; clr.AddReference("TCdll") FileNotFoundException: Unable to find assembly 'TCdll'. at Python.Runtime.CLRModule.AddReference(String name) </code></pre> <p>How to handle this exception ??</p> <p>Help needed immediately</p>
-2
2009-01-13T11:50:25Z
438,771
<p>You need to find out how clr.AddReference maps to a file name.</p> <p>EDIT:</p> <p>I think you're asking how to catch the exception from the AddReference call?</p> <p>Replace:</p> <pre><code>clr.AddReference("TCdll") </code></pre> <p>with:</p> <pre><code>try: clr.AddReference("TCdll") except FileNotFoundException,e: print "Failed to find reference",e sys.exit(1) </code></pre>
4
2009-01-13T12:17:54Z
[ "python", "handler", "filenotfoundexception" ]
How do you create a list like PHP's in Python?
438,813
<p>This is an incredibly simple question (I'm new to Python).</p> <p>I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.</p> <p>As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.</p> <p>Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.</p> <p>Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.</p> <p>I.e., I want to be able to do this:</p> <pre><code>list = [] for row in rows: c = list_of_categories.index(row["id"]) print c list[c] = row["name"] </code></pre>
1
2009-01-13T12:42:33Z
438,824
<p>Use the list constructor, and append your items, like this:</p> <pre><code>l = list () l.append ("foo") l.append (3) print (l) </code></pre> <p>gives me <code>['foo', 3]</code>, which should be what you want. See the <a href="http://docs.python.org/library/functions.html?highlight=list#list" rel="nofollow">documentation on list</a> and the <a href="http://docs.python.org/library/stdtypes.html#typesseq" rel="nofollow">sequence type documentation</a>.</p> <p><strong>EDIT</strong> Updated</p> <p>For inserting, use <code>insert</code>, like this:</p> <pre><code>l = list () l.append ("foo") l.append (3) l.insert (1, "new") print (l) </code></pre> <p>which prints <code>['foo', 'new', 3]</code></p>
2
2009-01-13T12:46:11Z
[ "python", "list" ]
How do you create a list like PHP's in Python?
438,813
<p>This is an incredibly simple question (I'm new to Python).</p> <p>I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.</p> <p>As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.</p> <p>Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.</p> <p>Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.</p> <p>I.e., I want to be able to do this:</p> <pre><code>list = [] for row in rows: c = list_of_categories.index(row["id"]) print c list[c] = row["name"] </code></pre>
1
2009-01-13T12:42:33Z
438,827
<p>You can use this syntax to create a list with <code>n</code> elements:</p> <pre><code>lst = [0] * n </code></pre> <p>But be careful! The list will contain <code>n</code> copies of this object. If this object is mutable and you change one element, then all copies will be changed! In this case you should use:</p> <pre><code>lst = [some_object() for i in xrange(n)] </code></pre> <p>Then you can access these elements:</p> <pre><code>for i in xrange(n): lst[i] += 1 </code></pre> <p>A Python list is comparable to a vector in other languages. It is a resizable array, not a linked list.</p>
1
2009-01-13T12:47:16Z
[ "python", "list" ]
How do you create a list like PHP's in Python?
438,813
<p>This is an incredibly simple question (I'm new to Python).</p> <p>I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.</p> <p>As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.</p> <p>Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.</p> <p>Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.</p> <p>I.e., I want to be able to do this:</p> <pre><code>list = [] for row in rows: c = list_of_categories.index(row["id"]) print c list[c] = row["name"] </code></pre>
1
2009-01-13T12:42:33Z
438,829
<p><a href="http://diveintopython3.ep.io/native-datatypes.html#lists" rel="nofollow">http://diveintopython3.ep.io/native-datatypes.html#lists</a></p> <p>You don't need to create empty lists with a specified length. You just add to them and query about their current length if needed. </p> <p>What you can't do without preparing to catch an exception is to use a non existent index. Which is probably what you are used to in PHP.</p>
2
2009-01-13T12:47:45Z
[ "python", "list" ]
How do you create a list like PHP's in Python?
438,813
<p>This is an incredibly simple question (I'm new to Python).</p> <p>I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.</p> <p>As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.</p> <p>Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.</p> <p>Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.</p> <p>I.e., I want to be able to do this:</p> <pre><code>list = [] for row in rows: c = list_of_categories.index(row["id"]) print c list[c] = row["name"] </code></pre>
1
2009-01-13T12:42:33Z
438,841
<p>If the number of items you want is known in advance, and you want to access them using integer, 0-based, consecutive indices, you might try this:</p> <pre><code>n = 3 array = n * [None] print array array[2] = 11 array[1] = 47 array[0] = 42 print array </code></pre> <p>This prints:</p> <pre><code>[None, None, None] [42, 47, 11] </code></pre>
4
2009-01-13T12:50:56Z
[ "python", "list" ]
How do you create a list like PHP's in Python?
438,813
<p>This is an incredibly simple question (I'm new to Python).</p> <p>I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.</p> <p>As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.</p> <p>Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.</p> <p>Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.</p> <p>I.e., I want to be able to do this:</p> <pre><code>list = [] for row in rows: c = list_of_categories.index(row["id"]) print c list[c] = row["name"] </code></pre>
1
2009-01-13T12:42:33Z
438,854
<p>Depending on how you are going to use the list, it may be that you actually want a dictionary. This will work:</p> <pre><code>d = {} for row in rows: c = list_of_categories.index(row["id"]) print c d[c] = row["name"] </code></pre> <p>... or more compactly:</p> <pre><code>d = dict((list_of_categories.index(row['id']), row['name']) for row in rows) print d </code></pre> <p>PHP arrays are much more like Python dicts than they are like Python lists. For example, they can have strings for keys.</p> <p>And confusingly, Python has an array module, which is described as "efficient arrays of numeric values", which is definitely not what you want.</p>
10
2009-01-13T12:58:42Z
[ "python", "list" ]
How do you create a list like PHP's in Python?
438,813
<p>This is an incredibly simple question (I'm new to Python).</p> <p>I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.</p> <p>As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.</p> <p>Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.</p> <p>Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.</p> <p>I.e., I want to be able to do this:</p> <pre><code>list = [] for row in rows: c = list_of_categories.index(row["id"]) print c list[c] = row["name"] </code></pre>
1
2009-01-13T12:42:33Z
438,858
<p>Sounds like what you need might be a <strong>dictionary</strong> rather than an array if you want to insert into specified indices.</p> <pre><code>dict = {'a': 1, 'b': 2, 'c': 3} dict['a'] </code></pre> <blockquote> <blockquote> <p>1</p> </blockquote> </blockquote>
1
2009-01-13T13:00:51Z
[ "python", "list" ]
How do you create a list like PHP's in Python?
438,813
<p>This is an incredibly simple question (I'm new to Python).</p> <p>I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.</p> <p>As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.</p> <p>Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.</p> <p>Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.</p> <p>I.e., I want to be able to do this:</p> <pre><code>list = [] for row in rows: c = list_of_categories.index(row["id"]) print c list[c] = row["name"] </code></pre>
1
2009-01-13T12:42:33Z
438,874
<p>I agree with ned that you probably need a dictionary for what you're trying to do. But here's a way to get a list of those lists of categories you can do this:</p> <pre><code>lst = [list_of_categories.index(row["id"]) for row in rows] </code></pre>
1
2009-01-13T13:05:58Z
[ "python", "list" ]
How do you create a list like PHP's in Python?
438,813
<p>This is an incredibly simple question (I'm new to Python).</p> <p>I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.</p> <p>As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.</p> <p>Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.</p> <p>Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.</p> <p>I.e., I want to be able to do this:</p> <pre><code>list = [] for row in rows: c = list_of_categories.index(row["id"]) print c list[c] = row["name"] </code></pre>
1
2009-01-13T12:42:33Z
438,940
<p>use a dictionary, because what you're really asking for is a structure you can access by arbitrary keys</p> <pre><code>list = {} for row in rows: c = list_of_categories.index(row["id"]) print c list[c] = row["name"] </code></pre> <p>Then you can iterate through the known contents with:</p> <pre><code>for x in list.values(): print x </code></pre> <p>Or check if something exists in the "list":</p> <pre><code>if 3 in list: print "it's there" </code></pre>
1
2009-01-13T13:30:47Z
[ "python", "list" ]
How do you create a list like PHP's in Python?
438,813
<p>This is an incredibly simple question (I'm new to Python).</p> <p>I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.</p> <p>As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.</p> <p>Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.</p> <p>Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.</p> <p>I.e., I want to be able to do this:</p> <pre><code>list = [] for row in rows: c = list_of_categories.index(row["id"]) print c list[c] = row["name"] </code></pre>
1
2009-01-13T12:42:33Z
438,992
<p>I'm not sure if I understood what you mean or want to do, but it seems that you want a list which is dictonary-like where the index is the key. Even if I think, the usage of a dictonary would be a better choice, here's my answer: Got a problem - make an object:</p> <pre><code>class MyList(UserList.UserList): NO_ITEM = 'noitem' def insertAt(self, item, index): length = len(self) if index &lt; length: self[index] = item elif index == length: self.append(item) else: for i in range(0, index-length): self.append(self.NO_ITEM) self.append(item) </code></pre> <p>Maybe some errors in the python syntax (didn't check), but in principle it should work. Of course the else case works also for the elif, but I thought, it might be a little harder to read this way. </p>
1
2009-01-13T13:46:33Z
[ "python", "list" ]
Is there a label/goto in Python?
438,844
<p>Is there a <code>goto</code> or any equivalent in Python to be able to jump to a specific line of code?</p>
78
2009-01-13T12:53:23Z
438,848
<p>No, Python does not support labels and goto, if that is what you're after. It's a (highly) structured programming language.</p>
61
2009-01-13T12:55:57Z
[ "python", "goto" ]
Is there a label/goto in Python?
438,844
<p>Is there a <code>goto</code> or any equivalent in Python to be able to jump to a specific line of code?</p>
78
2009-01-13T12:53:23Z
438,869
<p>Python offers you the ability to do some of the things you could do with a goto using first class functions. For example:</p> <pre><code>void somefunc(int a) { if (a == 1) goto label1; if (a == 2) goto label2; label1: ... label2: ... } </code></pre> <p>Could be done in python like this:</p> <pre><code>def func1(): ... def func2(): ... funcmap = {1 : func1, 2 : func2} def somefunc(a): funcmap[a]() #Ugly! But it works. </code></pre> <p>Granted, that isn't the best way to substitute for goto. But without knowing exactly what you're trying to do with the goto, it's hard to give specific advice.</p> <p>@<a href="http://stackoverflow.com/questions/438844/is-there-a-label-in-python#438866">ascobol</a>:</p> <p>Your best bet is to either enclose it in a function or use an exception. For the function:</p> <pre><code>def loopfunc(): while 1: while 1: if condition: return </code></pre> <p>For the exception:</p> <pre><code>try: while 1: while 1: raise BreakoutException #Not a real exception, invent your own except BreakoutException: pass </code></pre> <p>Using exceptions to do stuff like this may feel a bit awkward if you come from another programming language. But I would argue that if you dislike using exceptions, Python isn't the language for you. :-)</p>
40
2009-01-13T13:04:56Z
[ "python", "goto" ]
Is there a label/goto in Python?
438,844
<p>Is there a <code>goto</code> or any equivalent in Python to be able to jump to a specific line of code?</p>
78
2009-01-13T12:53:23Z
453,678
<p>To answer the <a href="http://stackoverflow.com/questions/438844/is-there-a-label-in-python#438866"><code>@ascobol</code>'s question</a> using <code>@bobince</code>'s suggestion from the comments:</p> <pre><code>for i in range(5000): for j in range(3000): if should_terminate_the_loop: break else: continue # no break encountered break </code></pre> <p>Though I never saw such a code in practice.</p>
11
2009-01-17T17:42:56Z
[ "python", "goto" ]
Is there a label/goto in Python?
438,844
<p>Is there a <code>goto</code> or any equivalent in Python to be able to jump to a specific line of code?</p>
78
2009-01-13T12:53:23Z
9,880,545
<p>Labels for <code>break</code> and <code>continue</code> were proposed in <a href="http://www.python.org/dev/peps/pep-3136/" rel="nofollow">PEP 3136</a> back in 2007, but it was rejected. The <a href="http://www.python.org/dev/peps/pep-3136/#motivation" rel="nofollow">Motivation</a> section of the proposal illustrates several common (if inelegant) methods for imitating labeled <code>break</code> in Python.</p>
4
2012-03-26T22:03:09Z
[ "python", "goto" ]
Is there a label/goto in Python?
438,844
<p>Is there a <code>goto</code> or any equivalent in Python to be able to jump to a specific line of code?</p>
78
2009-01-13T12:53:23Z
29,305,151
<p>you can use <a href="https://docs.python.org/2/tutorial/errors.html#user-defined-exceptions" rel="nofollow">User-defined Exceptions</a> to emulate <code>goto</code></p> <p>example:</p> <pre><code>class goto1(Exception): pass class goto2(Exception): pass class goto3(Exception): pass def loop(): print 'start' num = input() try: if num&lt;=0: raise goto1 elif num&lt;=2: raise goto2 elif num&lt;=4: raise goto3 elif num&lt;=6: raise goto1 else: print 'end' return 0 except goto1 as e: print 'goto1' loop() except goto2 as e: print 'goto2' loop() except goto3 as e: print 'goto3' loop() </code></pre>
2
2015-03-27T16:07:25Z
[ "python", "goto" ]
Is there a label/goto in Python?
438,844
<p>Is there a <code>goto</code> or any equivalent in Python to be able to jump to a specific line of code?</p>
78
2009-01-13T12:53:23Z
30,050,639
<p>It is technically feasible to add a 'goto' like statement to python with some work. We will use the "dis" and "new" modules, both very useful for scanning and modifying python byte code.</p> <p>The main idea behind the implementation is to first mark a block of code as using "goto" and "label" statements. A special "@goto" decorator will be used for the purpose of marking "goto" functions. Afterwards we scan that code for these two statements and apply the necessary modifications to the underlying byte code. This all happens at source code compile time.</p> <pre><code>import dis, new def goto(fn): """ A function decorator to add the goto command for a function. Specify labels like so: label .foo Goto labels like so: goto .foo Note: you can write a goto statement before the correspnding label statement """ labels = {} gotos = {} globalName = None index = 0 end = len(fn.func_code.co_code) i = 0 # scan through the byte codes to find the labels and gotos while i &lt; end: op = ord(fn.func_code.co_code[i]) i += 1 name = dis.opname[op] if op &gt; dis.HAVE_ARGUMENT: b1 = ord(fn.func_code.co_code[i]) b2 = ord(fn.func_code.co_code[i+1]) num = b2 * 256 + b1 if name == 'LOAD_GLOBAL': globalName = fn.func_code.co_names[num] index = i - 1 i += 2 continue if name == 'LOAD_ATTR': if globalName == 'label': labels[fn.func_code.co_names[num]] = index elif globalName == 'goto': gotos[fn.func_code.co_names[num]] = index name = None i += 2 # no-op the labels ilist = list(fn.func_code.co_code) for label,index in labels.items(): ilist[index:index+7] = [chr(dis.opmap['NOP'])]*7 # change gotos to jumps for label,index in gotos.items(): if label not in labels: raise Exception("Missing label: %s"%label) target = labels[label] + 7 # skip NOPs ilist[index] = chr(dis.opmap['JUMP_ABSOLUTE']) ilist[index + 1] = chr(target &amp; 255) ilist[index + 2] = chr(target &gt;&gt; 8) # create new function from existing function c = fn.func_code newcode = new.code(c.co_argcount, c.co_nlocals, c.co_stacksize, c.co_flags, ''.join(ilist), c.co_consts, c.co_names, c.co_varnames, c.co_filename, c.co_name, c.co_firstlineno, c.co_lnotab) newfn = new.function(newcode,fn.func_globals) return newfn if __name__ == '__main__': @goto def test1(): print 'Hello' goto .the_end print 'world' label .the_end print 'the end' test1() </code></pre> <p>Hope this answers the question.</p>
2
2015-05-05T10:36:10Z
[ "python", "goto" ]
Is there a label/goto in Python?
438,844
<p>Is there a <code>goto</code> or any equivalent in Python to be able to jump to a specific line of code?</p>
78
2009-01-13T12:53:23Z
30,373,076
<p>A working version has been made: <a href="http://entrian.com/goto/">http://entrian.com/goto/</a>.</p> <p>Note: It was offered as an April Fool's joke. (working though)</p> <pre><code># Example 1: Breaking out from a deeply nested loop: from goto import goto, label for i in range(1, 10): for j in range(1, 20): for k in range(1, 30): print i, j, k if k == 3: goto .end label .end print "Finished\n" </code></pre> <p>Needless to say. Yes its funny, but DONT use it.</p>
5
2015-05-21T11:57:10Z
[ "python", "goto" ]
Is there a label/goto in Python?
438,844
<p>Is there a <code>goto</code> or any equivalent in Python to be able to jump to a specific line of code?</p>
78
2009-01-13T12:53:23Z
31,726,538
<p>I wanted the same answer and I didnt want to use <code>goto</code>. So I used the following example (from learnpythonthehardway)</p> <pre><code>def sample(): print "This room is full of gold how much do you want?" choice = raw_input("&gt; ") how_much = int(choice) if "0" in choice or "1" in choice: check(how_much) else: print "Enter a number with 0 or 1" sample() def check(n): if n &lt; 150: print "You are not greedy, you win" exit(0) else: print "You are nuts!" exit(0) </code></pre>
0
2015-07-30T14:28:19Z
[ "python", "goto" ]
Is there a label/goto in Python?
438,844
<p>Is there a <code>goto</code> or any equivalent in Python to be able to jump to a specific line of code?</p>
78
2009-01-13T12:53:23Z
32,683,845
<p>I recently <a href="https://github.com/snoack/python-goto">wrote a function decorator</a> that enables <code>goto</code> in Python, just like that:</p> <pre><code>from goto import with_goto @with_goto def range(start, stop): i = start result = [] label .begin if i == stop: goto .end result.append(i) i += 1 goto .begin label .end return result </code></pre> <p>I'm not sure why one would like to do something like that though. That said, I'm not too serious about it. But I'd like to point out that this kind of meta programming is actual possible in Python, at least in CPython and PyPy, and not only by misusing the debugger API as that <a href="http://entrian.com/goto/">other guy</a> did. You have to mess with the bytecode though.</p>
8
2015-09-20T20:15:04Z
[ "python", "goto" ]
Is there a label/goto in Python?
438,844
<p>Is there a <code>goto</code> or any equivalent in Python to be able to jump to a specific line of code?</p>
78
2009-01-13T12:53:23Z
32,709,934
<p>There is now. <a href="https://github.com/snoack/python-goto" rel="nofollow">goto</a></p> <p>I think this might be useful for what you are looking for.</p>
0
2015-09-22T06:33:52Z
[ "python", "goto" ]
Is there a label/goto in Python?
438,844
<p>Is there a <code>goto</code> or any equivalent in Python to be able to jump to a specific line of code?</p>
78
2009-01-13T12:53:23Z
38,238,711
<p>I was looking for some thing similar to</p> <pre><code>for a in xrange(1,10): A_LOOP for b in xrange(1,5): for c in xrange(1,5): for d in xrange(1,5): # do some stuff if(condition(e)): goto B_LOOP; </code></pre> <p>So my approach was to use a boolean to help breaking out from the nested for loops:</p> <pre><code>for a in xrange(1,10): get_out = False for b in xrange(1,5): if(get_out): break for c in xrange(1,5): if(get_out): break for d in xrange(1,5): # do some stuff if(condition(e)): get_out = True break </code></pre>
0
2016-07-07T06:23:05Z
[ "python", "goto" ]
How do I stop a program when an exception is raised in Python?
438,894
<p>I need to stop my program when an exception is raised in Python. How do I implement this?</p>
16
2009-01-13T13:13:24Z
438,901
<p>As far as I know, if an exception is not caught by your script, it will be interrupted.</p>
4
2009-01-13T13:15:53Z
[ "python", "exception-handling" ]
How do I stop a program when an exception is raised in Python?
438,894
<p>I need to stop my program when an exception is raised in Python. How do I implement this?</p>
16
2009-01-13T13:13:24Z
438,902
<pre><code>import sys try: print("stuff") except: sys.exit(0) </code></pre>
23
2009-01-13T13:16:02Z
[ "python", "exception-handling" ]
How do I stop a program when an exception is raised in Python?
438,894
<p>I need to stop my program when an exception is raised in Python. How do I implement this?</p>
16
2009-01-13T13:13:24Z
439,137
<p>You can stop catching the exception, or - if you need to catch it (to do some custom handling), you can re-raise:</p> <pre> <code> try: doSomeEvilThing() except Exception, e: handleException(e) raise</code></pre> <p>Note that typing <code>raise</code> without passing an exception object causes the original traceback to be preserved. Typically it is much better than <code>raise e</code>.</p> <p>Of course - you can also explicitly call </p> <pre><code> import sys sys.exit(exitCodeYouFindAppropriate) </code></pre> <p>This causes SystemExit exception to be raised, and (unless you catch it somewhere) terminates your application with specified exit code.</p>
17
2009-01-13T14:33:53Z
[ "python", "exception-handling" ]
How do I stop a program when an exception is raised in Python?
438,894
<p>I need to stop my program when an exception is raised in Python. How do I implement this?</p>
16
2009-01-13T13:13:24Z
440,523
<p>If you don't handle an exception, it will propagate up the call stack up to the interpreter, which will then display a traceback and exit. IOW : you don't have to do <em>anything</em> to make your script exit when an exception happens. </p>
6
2009-01-13T19:52:52Z
[ "python", "exception-handling" ]
How do I stop a program when an exception is raised in Python?
438,894
<p>I need to stop my program when an exception is raised in Python. How do I implement this?</p>
16
2009-01-13T13:13:24Z
1,759,654
<pre><code>import sys try: import feedparser except: print "Error: Cannot import feedparser.\n" sys.exit(1) </code></pre> <p>Here we're exiting with a status code of 1. It is usually also helpful to output an error message, write to a log, and clean up.</p>
1
2009-11-18T22:36:25Z
[ "python", "exception-handling" ]
How do I stop a program when an exception is raised in Python?
438,894
<p>I need to stop my program when an exception is raised in Python. How do I implement this?</p>
16
2009-01-13T13:13:24Z
31,013,647
<p>Simply like this:</p> <pre><code>import sys if condition: print "your error message" sys.exit(0) </code></pre>
-3
2015-06-23T21:14:12Z
[ "python", "exception-handling" ]
random Decimal in python
439,115
<p>How do I get a random decimal.Decimal? It appears that the random module only returns floats which are a pita to convert to Decimals.</p>
7
2009-01-13T14:26:49Z
439,169
<p>From the <a href="http://docs.python.org/dev/3.0/library/decimal.html">standard library reference</a> :</p> <p>To create a Decimal from a float, first convert it to a string. This serves as an explicit reminder of the details of the conversion (including representation error).</p> <pre><code>&gt;&gt;&gt; import random, decimal &gt;&gt;&gt; decimal.Decimal(str(random.random())) Decimal('0.467474014342') </code></pre> <p>Is this what you mean? It doesn't seem like a pita to me. You can scale it into whatever range and precision you want.</p>
15
2009-01-13T14:44:36Z
[ "python", "random", "decimal" ]
random Decimal in python
439,115
<p>How do I get a random decimal.Decimal? It appears that the random module only returns floats which are a pita to convert to Decimals.</p>
7
2009-01-13T14:26:49Z
439,223
<p>If you know how many digits you want after and before the comma, you can use:</p> <pre><code>&gt;&gt;&gt; import decimal &gt;&gt;&gt; import random &gt;&gt;&gt; def gen_random_decimal(i,d): ... return decimal.Decimal('%d.%d' % (random.randint(0,i),random.randint(0,d))) ... &gt;&gt;&gt; gen_random_decimal(9999,999999) #4 digits before, 6 after Decimal('4262.786648') &gt;&gt;&gt; gen_random_decimal(9999,999999) Decimal('8623.79391') &gt;&gt;&gt; gen_random_decimal(9999,999999) Decimal('7706.492775') &gt;&gt;&gt; gen_random_decimal(99999999999,999999999999) #11 digits before, 12 after Decimal('35018421976.794013996282') &gt;&gt;&gt; </code></pre>
6
2009-01-13T14:56:32Z
[ "python", "random", "decimal" ]
random Decimal in python
439,115
<p>How do I get a random decimal.Decimal? It appears that the random module only returns floats which are a pita to convert to Decimals.</p>
7
2009-01-13T14:26:49Z
439,282
<p>What's "a random decimal"? Decimals have arbitrary precision, so generating a number with as much randomness as you can hold in a Decimal would take the entire memory of your machine to store.</p> <p>You have to know how many decimal digits of precision you want in your random number, at which point it's easy to just grab an random integer and divide it. For example if you want two digits above the point and two digits in the fraction (see <a href="https://docs.python.org/2/library/random.html#random.randrange" rel="nofollow">randrange here</a>):</p> <pre><code>decimal.Decimal(random.randrange(10000))/100 </code></pre>
18
2009-01-13T15:09:41Z
[ "python", "random", "decimal" ]
random Decimal in python
439,115
<p>How do I get a random decimal.Decimal? It appears that the random module only returns floats which are a pita to convert to Decimals.</p>
7
2009-01-13T14:26:49Z
439,557
<p>The random module has more to offer than "only returning floats", but anyway:</p> <pre><code>from random import random from decimal import Decimal randdecimal = lambda: Decimal("%f" % random.random()) </code></pre> <p>Or did I miss something obvious in your question ?</p>
2
2009-01-13T16:04:14Z
[ "python", "random", "decimal" ]
random Decimal in python
439,115
<p>How do I get a random decimal.Decimal? It appears that the random module only returns floats which are a pita to convert to Decimals.</p>
7
2009-01-13T14:26:49Z
10,483,516
<pre><code>decimal.Decimal(random.random() * MAX_VAL).quantize(decimal.Decimal('.01')) </code></pre>
2
2012-05-07T14:05:04Z
[ "python", "random", "decimal" ]
PIL vs RMagick/ruby-gd
439,641
<p>For my next project I plan to create images with text and graphics. I'm comfortable with ruby, but interested in learning python. I figured this may be a good time because PIL looks like a great library to use. However, I don't know how it compares to what ruby has to offer (e.g. RMagick and ruby-gd). From what I can gather PIL had better documentation (does ruby-gd even have a homepage?) and more features. Just wanted to hear a few opinions to help me decide.</p> <p>Thanks.</p> <p>Vince</p>
4
2009-01-13T16:21:17Z
440,298
<p>PIL is a good library, use it. ImageMagic (what RMagick wraps) is a very heavy library that should be avoided if possible. Its good for doing local processing of images, say, a batch photo editor, but way too processor inefficient for common image manipulation tasks for web.</p> <p><strong>EDIT:</strong> In response to the question, PIL supports drawing vector shapes. It can draw polygons, curves, lines, fills and text. I've used it in a project to produce rounded alpha corners to PNG images on the fly over the web. It essentially has most of the drawing features of GDI+ (in Windows) or GTK (in Gnome on Linux).</p>
7
2009-01-13T19:00:38Z
[ "python", "ruby", "python-imaging-library", "rmagick" ]
PIL vs RMagick/ruby-gd
439,641
<p>For my next project I plan to create images with text and graphics. I'm comfortable with ruby, but interested in learning python. I figured this may be a good time because PIL looks like a great library to use. However, I don't know how it compares to what ruby has to offer (e.g. RMagick and ruby-gd). From what I can gather PIL had better documentation (does ruby-gd even have a homepage?) and more features. Just wanted to hear a few opinions to help me decide.</p> <p>Thanks.</p> <p>Vince</p>
4
2009-01-13T16:21:17Z
440,342
<p>PIL has been around for a long time and is very stable, so it's probably a good candidate for your first Python project. The PIL documentation includes a helpful <a href="http://effbot.org/imagingbook/introduction.htm" rel="nofollow">tutorial</a>, which should get you up to speed quickly.</p>
4
2009-01-13T19:12:00Z
[ "python", "ruby", "python-imaging-library", "rmagick" ]
PIL vs RMagick/ruby-gd
439,641
<p>For my next project I plan to create images with text and graphics. I'm comfortable with ruby, but interested in learning python. I figured this may be a good time because PIL looks like a great library to use. However, I don't know how it compares to what ruby has to offer (e.g. RMagick and ruby-gd). From what I can gather PIL had better documentation (does ruby-gd even have a homepage?) and more features. Just wanted to hear a few opinions to help me decide.</p> <p>Thanks.</p> <p>Vince</p>
4
2009-01-13T16:21:17Z
441,260
<p>ImageMagic is a huge library and will do everything under the sun, but many report memory issues with the RMagick variant and I have personally found it to be an overkill for my needs.</p> <p>As you say ruby-gd is a little thin on the ground when it comes to English documentation.... but GD is a doddle to install on post platforms and there is a little wrapper with some helpful examples called <a href="http://gruby.sourceforge.jp/index.en.html" rel="nofollow">gruby</a> thats worth a look. (If you're after alpha transparency make sure you install the latest GD lib)</p> <p>For overall community blogy help, PIL's the way.</p>
3
2009-01-13T23:12:10Z
[ "python", "ruby", "python-imaging-library", "rmagick" ]
Re-creating threading and concurrency knowledge in increasingly popular languages
440,036
<p>I am primarily a Java developer, and I've been reading a lot of in-depth work on threads and concurrency. Many very smart people (Doug Lea, Brian Goetz, etc) have authored books on these topics and made contributions to new concurrency libraries for Java.</p> <p>As I start to learn more about Python, Ruby, and other languages, I'm wondering: does all of that work have to be re-created for these languages?</p> <p>Will there be, or does there need to be, a "Doug Lea of Python," or a "Brian Goetz of Ruby," who make similarly powerful contributions to the concurrency features of those languages? </p> <p><b>Does all of this concurrency work done in Java have to be re-created for future languages?</b> Or will the work done in Java establish lessons and guidance for future languages?</p>
7
2009-01-13T17:52:42Z
440,086
<p>The basic principles of concurrent programming existed before java and were summarized in those java books you're talking about. The java.util.concurrent library was similarly derived from previous code and research papers on concurrent programming.</p> <p>However, some implementation issues are specific to Java. It has a specified memory model, and the concurrent utilities in Java are tailored to the specifics of that. With some modification those can be ported to other languages/environments with different memory model characteristics.</p> <p>So, you might need a book to teach you the canonical usage of the concurrency tools in other languages but it wouldn't be reinventing the wheel.</p>
11
2009-01-13T18:04:08Z
[ "java", "python", "ruby", "multithreading", "concurrency" ]
Re-creating threading and concurrency knowledge in increasingly popular languages
440,036
<p>I am primarily a Java developer, and I've been reading a lot of in-depth work on threads and concurrency. Many very smart people (Doug Lea, Brian Goetz, etc) have authored books on these topics and made contributions to new concurrency libraries for Java.</p> <p>As I start to learn more about Python, Ruby, and other languages, I'm wondering: does all of that work have to be re-created for these languages?</p> <p>Will there be, or does there need to be, a "Doug Lea of Python," or a "Brian Goetz of Ruby," who make similarly powerful contributions to the concurrency features of those languages? </p> <p><b>Does all of this concurrency work done in Java have to be re-created for future languages?</b> Or will the work done in Java establish lessons and guidance for future languages?</p>
7
2009-01-13T17:52:42Z
442,252
<p>Keep in mind that threads are just one of several possible models for dealing with "concurrency". Python, for example, has one of the most advanced asynchronous (event based) non-threaded models in <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a>. Non-blocking models are quite powerful and are used as alternatives to threads in most of the highest scaling apps out there (eg. nginx, lighttpd). </p> <p>Your assumption that other popular languages need threads may simply be a symptom of a java centric (and hence thread-centric) world view. Take a look at the <a href="http://www.kegel.com/c10k.html" rel="nofollow">C10K</a> page for a slightly dated but highly informative look at several models for how to handle large volumes of concurrent requests.</p>
5
2009-01-14T08:12:45Z
[ "java", "python", "ruby", "multithreading", "concurrency" ]
Re-creating threading and concurrency knowledge in increasingly popular languages
440,036
<p>I am primarily a Java developer, and I've been reading a lot of in-depth work on threads and concurrency. Many very smart people (Doug Lea, Brian Goetz, etc) have authored books on these topics and made contributions to new concurrency libraries for Java.</p> <p>As I start to learn more about Python, Ruby, and other languages, I'm wondering: does all of that work have to be re-created for these languages?</p> <p>Will there be, or does there need to be, a "Doug Lea of Python," or a "Brian Goetz of Ruby," who make similarly powerful contributions to the concurrency features of those languages? </p> <p><b>Does all of this concurrency work done in Java have to be re-created for future languages?</b> Or will the work done in Java establish lessons and guidance for future languages?</p>
7
2009-01-13T17:52:42Z
442,312
<p>This is not flame bait, but IMHO Java has one of the simpler and more restricted models for threading and concurrency available. That's not necessarily a bad thing, but at the level of granularity it offers it means that the perspective it gives you of what concurrency is and how to deal with it is inherently limited if you have a "java centric" view (as someone else put it).</p> <p>If you're serious about concurrency, then it's worth exploring other languages precisely <em>because</em> different models and idioms exist.</p> <p>Some of the hottest areas are lock-free programming (you'll see a lot of it, but often done badly, in C++) and functional programming (which has been around for a while but arguably, is becoming increasingly relevant. A prime example in the case of concurrency is probably Erlang).</p>
1
2009-01-14T08:47:34Z
[ "java", "python", "ruby", "multithreading", "concurrency" ]
Re-creating threading and concurrency knowledge in increasingly popular languages
440,036
<p>I am primarily a Java developer, and I've been reading a lot of in-depth work on threads and concurrency. Many very smart people (Doug Lea, Brian Goetz, etc) have authored books on these topics and made contributions to new concurrency libraries for Java.</p> <p>As I start to learn more about Python, Ruby, and other languages, I'm wondering: does all of that work have to be re-created for these languages?</p> <p>Will there be, or does there need to be, a "Doug Lea of Python," or a "Brian Goetz of Ruby," who make similarly powerful contributions to the concurrency features of those languages? </p> <p><b>Does all of this concurrency work done in Java have to be re-created for future languages?</b> Or will the work done in Java establish lessons and guidance for future languages?</p>
7
2009-01-13T17:52:42Z
463,249
<p>I think the answer is both yes and no. Java arguably has the most well-defined memory model and execution semantics of the most commonly used imperative languages (Java, C++, Python, Ruby, etc). In some sense, other languages either lack this completely or are playing catch-up (if that's even possible given the immaturity of the threading models). </p> <p>C++ is probably the notable exception - it has been treading the same ground for C++0x and has possibly gone beyond the current state of the Java model from my impression.</p> <p>I say no because the communities are not isolated. Many of the guys working on this stuff are involved (at least from a guidance point of view, if not from a direct hand in the specs) in more than one language. So, there is a lot of crosstalk between guys working on JMM and guys working on C++0x specs as they are essentially solving the same problems with many of the same underlying drivers (from the hardware guys at the bottom and the users at the top). And I'm pretty sure there is cross-talk at some level between the JVM / CLR camps as well. </p> <p>As others have mentioned, there are also other models for concurrency: actors in Erlang and Scala, agents/STM in Clojure, FP's rise in F#, Scala, Haskell, the CCR and PLINQ stuff in CLR land, etc. It's an exciting time right now! We can use as many concurrency experts as we can find I think.... :)</p>
3
2009-01-20T21:41:01Z
[ "java", "python", "ruby", "multithreading", "concurrency" ]
Re-creating threading and concurrency knowledge in increasingly popular languages
440,036
<p>I am primarily a Java developer, and I've been reading a lot of in-depth work on threads and concurrency. Many very smart people (Doug Lea, Brian Goetz, etc) have authored books on these topics and made contributions to new concurrency libraries for Java.</p> <p>As I start to learn more about Python, Ruby, and other languages, I'm wondering: does all of that work have to be re-created for these languages?</p> <p>Will there be, or does there need to be, a "Doug Lea of Python," or a "Brian Goetz of Ruby," who make similarly powerful contributions to the concurrency features of those languages? </p> <p><b>Does all of this concurrency work done in Java have to be re-created for future languages?</b> Or will the work done in Java establish lessons and guidance for future languages?</p>
7
2009-01-13T17:52:42Z
2,103,804
<p><a href="http://www.kamaelia.org/Home" rel="nofollow">Kamaelia</a> is a project (which I started, and continue to work on) that has specifically the goal of making concurrency a tool you want to use, rather than a pain to use. In practical terms this means that it is primarily a shared-nothing model with message passing model (based on a world view from Occam &amp; Unix pipes).</p> <p>Underlying that goal is a desire to make concurrency easy to use for the average developer, shielding them from the nastier problems caused by a number of approaches to concurrency. (There's a bunch of presentations on slideshare explaining the why &amp; how there)</p> <p>Additionally it provides a simple software transactional memory model for the situations where you must share data, and uses a deliberately simple API.</p> <p>Kamaelia's primary implementation is in python, with a toy implementation in Ruby &amp; C++. Someone else has ported the underlying approach to E and also to Java. (though the Java person has disappeared) (The toy implementations are sanity checks the ideas can work in other languages, if needing to be recast as local idioms)</p> <p>Perhaps your question shouldn't be "what can these languages learn", but "what can the Java community learn by looking elsewhere?". Many people who learn python are liguistically immigrants from elsewhere and bring their knowledge of other languages with them, and so from where I sit it looks like python already looks out to other languages for inspiration.</p> <p>Picking something concrete, for example, <a href="http://www.kamaelia.org/SpeakAndWrite" rel="nofollow">this speak and write application</a> - which is a tool for teaching a small child to read and write, based around pen input, handwriting recognition, and speech synth - uses several dozen concurrent subsystems, runs at an acceptable speed on a single core machine, would be easily amenable to running on a many-core machine. However, the reason for the number of concurrent subsystems however has nothing to do with "wanting to make the application parallel", but more to do with "How can I make the application easier to write, extend and maintain?". <strong>The fact it ends up embarassingly parallel is a secondary bonus.</strong></p> <p>There's a full tutorial - <a href="http://www.kamaelia.org/PragmaticConcurrency" rel="nofollow">Pragmatic Concurrency</a> - linked from the front page. (Notes, slides, video &amp; code bundle)</p> <p>The model can be improved, and suggestions are welcome - life would be very boring if we all just "stopped" trying to make better tools - but ignoring what already exists seems a little ... parochial. If that seems a little harsh, please look at <a href="http://www.dilbert.com/fast/2010-01-20/" rel="nofollow">today's dilbert</a>.</p> <p>:-)</p>
1
2010-01-20T18:15:45Z
[ "java", "python", "ruby", "multithreading", "concurrency" ]
make a parent function return - super return?
440,063
<p>there is a check I need to perform after each subsequent step in a function, so I wanted to define that step as a function within a function.</p> <pre><code>&gt;&gt;&gt; def gs(a,b): ... def ry(): ... if a==b: ... return a ... ... ry() ... ... a += 1 ... ry() ... ... b*=2 ... ry() ... &gt;&gt;&gt; gs(1,2) # should return 2 &gt;&gt;&gt; gs(1,1) # should return 1 &gt;&gt;&gt; gs(5,3) # should return 6 &gt;&gt;&gt; gs(2,3) # should return 3 </code></pre> <p>so how do I get gs to return 'a' from within ry? I thought of using super but think that's only for classes.</p> <p>Thanks</p> <p>There's been a little confusion... I only want to return a if a==b. if a!=b, then I don't want gs to return anything yet.</p> <p><strong>edit</strong>: I now think <a href="http://muharem.wordpress.com/2006/10/19/python-decorator-mini-study-part-2-of-3/" rel="nofollow">decorators</a> might be the best solution.</p>
1
2009-01-13T17:59:40Z
440,072
<p>Do you mean?</p> <pre><code>def gs(a,b): def ry(): if a==b: return a return ry() </code></pre>
10
2009-01-13T18:02:06Z
[ "python", "class", "function", "return", "parent" ]
make a parent function return - super return?
440,063
<p>there is a check I need to perform after each subsequent step in a function, so I wanted to define that step as a function within a function.</p> <pre><code>&gt;&gt;&gt; def gs(a,b): ... def ry(): ... if a==b: ... return a ... ... ry() ... ... a += 1 ... ry() ... ... b*=2 ... ry() ... &gt;&gt;&gt; gs(1,2) # should return 2 &gt;&gt;&gt; gs(1,1) # should return 1 &gt;&gt;&gt; gs(5,3) # should return 6 &gt;&gt;&gt; gs(2,3) # should return 3 </code></pre> <p>so how do I get gs to return 'a' from within ry? I thought of using super but think that's only for classes.</p> <p>Thanks</p> <p>There's been a little confusion... I only want to return a if a==b. if a!=b, then I don't want gs to return anything yet.</p> <p><strong>edit</strong>: I now think <a href="http://muharem.wordpress.com/2006/10/19/python-decorator-mini-study-part-2-of-3/" rel="nofollow">decorators</a> might be the best solution.</p>
1
2009-01-13T17:59:40Z
440,078
<p>you return ry() explicitly instead of just calling it.</p>
1
2009-01-13T18:02:45Z
[ "python", "class", "function", "return", "parent" ]
make a parent function return - super return?
440,063
<p>there is a check I need to perform after each subsequent step in a function, so I wanted to define that step as a function within a function.</p> <pre><code>&gt;&gt;&gt; def gs(a,b): ... def ry(): ... if a==b: ... return a ... ... ry() ... ... a += 1 ... ry() ... ... b*=2 ... ry() ... &gt;&gt;&gt; gs(1,2) # should return 2 &gt;&gt;&gt; gs(1,1) # should return 1 &gt;&gt;&gt; gs(5,3) # should return 6 &gt;&gt;&gt; gs(2,3) # should return 3 </code></pre> <p>so how do I get gs to return 'a' from within ry? I thought of using super but think that's only for classes.</p> <p>Thanks</p> <p>There's been a little confusion... I only want to return a if a==b. if a!=b, then I don't want gs to return anything yet.</p> <p><strong>edit</strong>: I now think <a href="http://muharem.wordpress.com/2006/10/19/python-decorator-mini-study-part-2-of-3/" rel="nofollow">decorators</a> might be the best solution.</p>
1
2009-01-13T17:59:40Z
440,887
<blockquote> <p>There's been a little confusion... I only want to return a if a==b. if a!=b, then I don't want gs to return anything yet.</p> </blockquote> <p>Check for that then:</p> <pre><code>def gs(a,b): def ry(): if a==b: return a ret = ry() if ret: return ret # do other stuff </code></pre>
3
2009-01-13T21:37:48Z
[ "python", "class", "function", "return", "parent" ]
make a parent function return - super return?
440,063
<p>there is a check I need to perform after each subsequent step in a function, so I wanted to define that step as a function within a function.</p> <pre><code>&gt;&gt;&gt; def gs(a,b): ... def ry(): ... if a==b: ... return a ... ... ry() ... ... a += 1 ... ry() ... ... b*=2 ... ry() ... &gt;&gt;&gt; gs(1,2) # should return 2 &gt;&gt;&gt; gs(1,1) # should return 1 &gt;&gt;&gt; gs(5,3) # should return 6 &gt;&gt;&gt; gs(2,3) # should return 3 </code></pre> <p>so how do I get gs to return 'a' from within ry? I thought of using super but think that's only for classes.</p> <p>Thanks</p> <p>There's been a little confusion... I only want to return a if a==b. if a!=b, then I don't want gs to return anything yet.</p> <p><strong>edit</strong>: I now think <a href="http://muharem.wordpress.com/2006/10/19/python-decorator-mini-study-part-2-of-3/" rel="nofollow">decorators</a> might be the best solution.</p>
1
2009-01-13T17:59:40Z
441,679
<p>As you mention "steps" in a function, it almost seems like you want a generator:</p> <pre><code>def gs(a,b): def ry(): if a==b: yield a # If a != b, ry does not "generate" any output for i in ry(): yield i # Continue doing stuff... yield 'some other value' # Do more stuff. yield 'yet another value' </code></pre> <p>(Generators can now also act as coroutines, since Python 2.5, using the <a href="http://docs.python.org/reference/expressions.html#yield-expressions" rel="nofollow">new yield syntax</a>.)</p>
4
2009-01-14T02:13:17Z
[ "python", "class", "function", "return", "parent" ]
make a parent function return - super return?
440,063
<p>there is a check I need to perform after each subsequent step in a function, so I wanted to define that step as a function within a function.</p> <pre><code>&gt;&gt;&gt; def gs(a,b): ... def ry(): ... if a==b: ... return a ... ... ry() ... ... a += 1 ... ry() ... ... b*=2 ... ry() ... &gt;&gt;&gt; gs(1,2) # should return 2 &gt;&gt;&gt; gs(1,1) # should return 1 &gt;&gt;&gt; gs(5,3) # should return 6 &gt;&gt;&gt; gs(2,3) # should return 3 </code></pre> <p>so how do I get gs to return 'a' from within ry? I thought of using super but think that's only for classes.</p> <p>Thanks</p> <p>There's been a little confusion... I only want to return a if a==b. if a!=b, then I don't want gs to return anything yet.</p> <p><strong>edit</strong>: I now think <a href="http://muharem.wordpress.com/2006/10/19/python-decorator-mini-study-part-2-of-3/" rel="nofollow">decorators</a> might be the best solution.</p>
1
2009-01-13T17:59:40Z
562,695
<p>This should allow you to keep checking the state and return from the outer function if a and b ever end up the same:</p> <pre><code>def gs(a,b): class SameEvent(Exception): pass def ry(): if a==b: raise SameEvent(a) try: # Do stuff here, and call ry whenever you want to return if they are the same. ry() # It will now return 3. a = b = 3 ry() except SameEvent as e: return e.args[0] </code></pre>
2
2009-02-18T20:31:03Z
[ "python", "class", "function", "return", "parent" ]
make a parent function return - super return?
440,063
<p>there is a check I need to perform after each subsequent step in a function, so I wanted to define that step as a function within a function.</p> <pre><code>&gt;&gt;&gt; def gs(a,b): ... def ry(): ... if a==b: ... return a ... ... ry() ... ... a += 1 ... ry() ... ... b*=2 ... ry() ... &gt;&gt;&gt; gs(1,2) # should return 2 &gt;&gt;&gt; gs(1,1) # should return 1 &gt;&gt;&gt; gs(5,3) # should return 6 &gt;&gt;&gt; gs(2,3) # should return 3 </code></pre> <p>so how do I get gs to return 'a' from within ry? I thought of using super but think that's only for classes.</p> <p>Thanks</p> <p>There's been a little confusion... I only want to return a if a==b. if a!=b, then I don't want gs to return anything yet.</p> <p><strong>edit</strong>: I now think <a href="http://muharem.wordpress.com/2006/10/19/python-decorator-mini-study-part-2-of-3/" rel="nofollow">decorators</a> might be the best solution.</p>
1
2009-01-13T17:59:40Z
3,815,180
<p>I had a similar problem, but solved it by simply changing the order of the call. </p> <pre><code>def ry () if a==b gs() </code></pre> <p>in some languages like javascript you can even pass a function as a variable in a function:</p> <pre><code>function gs(a, b, callback) { if (a==b) callback(); } gs(a, b, ry); </code></pre>
1
2010-09-28T16:58:32Z
[ "python", "class", "function", "return", "parent" ]
unicode() vs. str.decode() for a utf8 encoded byte string (python 2.x)
440,320
<p>Is there any reason to prefer <code>unicode(somestring, 'utf8')</code> as opposed to <code>somestring.decode('utf8')</code>?</p> <p>My only thought is that <code>.decode()</code> is a bound method so python may be able to resolve it more efficiently, but correct me if I'm wrong.</p>
28
2009-01-13T19:06:16Z
440,432
<p>It's easy to benchmark it:</p> <pre><code>&gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; ts = Timer("s.decode('utf-8')", "s = 'ééé'") &gt;&gt;&gt; ts.timeit() 8.9185450077056885 &gt;&gt;&gt; tu = Timer("unicode(s, 'utf-8')", "s = 'ééé'") &gt;&gt;&gt; tu.timeit() 2.7656929492950439 &gt;&gt;&gt; </code></pre> <p>Obviously, <code>unicode()</code> is faster.</p> <p>FWIW, I don't know where you get the impression that methods would be faster - it's quite the contrary.</p>
23
2009-01-13T19:32:49Z
[ "python", "unicode", "utf-8" ]
unicode() vs. str.decode() for a utf8 encoded byte string (python 2.x)
440,320
<p>Is there any reason to prefer <code>unicode(somestring, 'utf8')</code> as opposed to <code>somestring.decode('utf8')</code>?</p> <p>My only thought is that <code>.decode()</code> is a bound method so python may be able to resolve it more efficiently, but correct me if I'm wrong.</p>
28
2009-01-13T19:06:16Z
440,461
<p>I'd prefer <code>'something'.decode(...)</code> since the <code>unicode</code> type is no longer there in Python 3.0, while <code>text = b'binarydata'.decode(encoding)</code> is still valid. </p>
22
2009-01-13T19:36:52Z
[ "python", "unicode", "utf-8" ]
Extracting Embedded Images From Outlook Email
440,356
<p>I am using Microsoft's CDO (Collaboration Data Objects) to programatically read mail from an Outlook mailbox and save embedded image attachments. I'm trying to do this from Python using the Win32 extensions, but samples in any language that uses CDO would be helpful.</p> <p>So far, I am here...</p> <p>The following Python code will read the last email in my mailbox, print the names of the attachments, and print the message body:</p> <pre><code>from win32com.client import Dispatch session = Dispatch('MAPI.session') session.Logon('','',0,1,0,0,'exchange.foo.com\nbar'); inbox = session.Inbox message = inbox.Messages.Item(inbox.Messages.Count) for attachment in message.Attachments: print attachment print message.Text session.Logoff() </code></pre> <p>However, the attachment names are things like: "zesjvqeqcb_chart_0". Inside the email source, I see image source links like this: &lt;IMG src="cid:zesjvqeqcb_chart_0"&gt;</p> <p>So.. is it possible to use this CID URL (or anything else) to extract the actual image and save it locally?</p>
4
2009-01-13T19:15:03Z
440,579
<p>Difference in versions of OS/Outlook/CDO is what might be the source of confusion, so here are the steps to get it working on WinXP/Outlook 2007/CDO 1.21:</p> <ul> <li>install <a href="http://www.microsoft.com/downloads/details.aspx?familyid=2714320d-c997-4de1-986f-24f081725d36&amp;displaylang=en" rel="nofollow">CDO 1.21</a></li> <li>install win32com.client</li> <li>goto C:\Python25\Lib\site-packages\win32com\client\ directory run the following:</li> </ul> <pre>python makepy.py</pre> <ul> <li>from the list select "Microsoft CDO 1.21 Library (1.21)", click ok</li> </ul> <pre>C:\Python25\Lib\site-packages\win32com\client>python makepy.py Generating to C:\Python25\lib\site-packages\win32com\gen_py\3FA7DEA7-6438-101B-ACC1-00AA00423326x0x1x33.py Building definitions from type library... Generating... Importing module</pre> <ul> <li>Examining file 3FA7DEA7-6438-101B-ACC1-00AA00423326x0x1x33.py that's just been generated, will give you an idea of what classes, methods, properties and constants are available.</li> </ul> <p>Now that we are done with the boring steps, here is the fun part:</p> <pre><code>import win32com.client from win32com.client import Dispatch session = Dispatch('MAPI.session') session.Logon ('Outlook') # this is profile name inbox = session.Inbox messages = session.Inbox.Messages message = inbox.Messages.GetFirst() if(message): attachments = message.Attachments for i in range(attachments.Count): attachment = attachments.Item(i + 1) # yep, indexes are 1 based filename = "c:\\tmpfile" + str(i) attachment.WriteToFile(FileName=filename) session.Logoff() </code></pre> <p>Same general approach will also work if you have older version of CDO (CDO for win2k)</p>
5
2009-01-13T20:08:27Z
[ "python", "email", "outlook", "cdo" ]