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
listlengths
1
5
How to find out if a Python object is a string?
1,303,243
<p>How can I check if a Python object is a string (either regular or Unicode)?</p>
195
2009-08-19T23:50:58Z
37,808,689
<p>I found this ans more pythonic:</p> <pre><code>if type(aObject) is str: #do your stuff here pass </code></pre> <p>since type objects are singleton, <strong>is</strong> can be used to do the compare</p>
1
2016-06-14T09:53:58Z
[ "python", "string", "types", "compatibility" ]
How to find out if a Python object is a string?
1,303,243
<p>How can I check if a Python object is a string (either regular or Unicode)?</p>
195
2009-08-19T23:50:58Z
38,124,526
<p>In order to check if your variable is something you could go like:</p> <pre><code>s='Hello World' if isinstance(s,str): #do something here, </code></pre> <p>The output of isistance will give you a boolean True or False value so you can adjust accordingly. You can check the expected acronym of your value by initially using: type(s) This will return you type 'str' so you can use it in the isistance function.</p>
1
2016-06-30T13:26:15Z
[ "python", "string", "types", "compatibility" ]
How to find out if a Python object is a string?
1,303,243
<p>How can I check if a Python object is a string (either regular or Unicode)?</p>
195
2009-08-19T23:50:58Z
38,636,757
<p>If one wants to stay away from explicit type-checking (and there <em>are</em> good reasons to stay away from it), probably the safest part of the string protocol to check is:</p> <pre><code>str(maybe_string) == maybe_string </code></pre> <p>It won't iterate through an iterable or iterator, it won't call a list-of-strings a string and it correctly detects a <a href="https://pypi.python.org/pypi/stringlike" rel="nofollow">stringlike</a> as a string.</p> <p>Of course there are drawbacks. For example, <code>str(maybe_string)</code> may be a heavy calculation. As so often, the answer is <em>it depends</em>.</p>
1
2016-07-28T12:44:46Z
[ "python", "string", "types", "compatibility" ]
FFT for Spectrograms in Python
1,303,307
<p>How would I go about using Python to read the frequency peaks from a WAV PCM file and then be able to generate an image of it, for spectogram analysis?</p> <p>I'm trying to make a program that allows you to read any audio file, converting it to WAV PCM, and then finding the peaks and frequency cutoffs.</p>
24
2009-08-20T00:14:03Z
1,303,325
<p><a href="http://docs.python.org/library/wave.html">Python's wave library</a> will let you import the audio. After that, you can <a href="http://docs.scipy.org/doc/numpy/reference/routines.fft.html">use numpy to take an FFT</a> of the audio.</p> <p>Then, <a href="http://matplotlib.sourceforge.net/index.html">matplotlib</a> makes very nice charts and graphs - absolutely comparable to MATLAB.</p> <p>It's old as dirt, but <a href="http://macdevcenter.com/pub/a/python/2001/01/31/numerically.html">this article</a> would probably get you started on almost exactly the problem you're describing (article in Python of course).</p>
23
2009-08-20T00:19:31Z
[ "python", "image", "graphics", "audio", "fft" ]
FFT for Spectrograms in Python
1,303,307
<p>How would I go about using Python to read the frequency peaks from a WAV PCM file and then be able to generate an image of it, for spectogram analysis?</p> <p>I'm trying to make a program that allows you to read any audio file, converting it to WAV PCM, and then finding the peaks and frequency cutoffs.</p>
24
2009-08-20T00:14:03Z
1,368,688
<p>Loading WAV files is easy using <a href="http://cournape.github.com/audiolab/">audiolab</a>:</p> <pre><code>from audiolab import wavread signal, fs, enc = wavread('test.wav') </code></pre> <p>or for reading any general audio format and converting to WAV:</p> <pre><code>from audiolab import Sndfile sound_file = Sndfile('test.w64', 'r') signal = wave_file.read_frames(wave_file.nframes) </code></pre> <p>The spectrogram is built into PyLab:</p> <pre><code>from pylab import * specgram(signal) </code></pre> <p>Specifically, it's part of <a href="http://matplotlib.sourceforge.net/">matplotlib</a>. <a href="http://matplotlib.sourceforge.net/examples/pylab_examples/specgram_demo.html">Here's a better example.</a></p>
13
2009-09-02T16:15:24Z
[ "python", "image", "graphics", "audio", "fft" ]
FFT for Spectrograms in Python
1,303,307
<p>How would I go about using Python to read the frequency peaks from a WAV PCM file and then be able to generate an image of it, for spectogram analysis?</p> <p>I'm trying to make a program that allows you to read any audio file, converting it to WAV PCM, and then finding the peaks and frequency cutoffs.</p>
24
2009-08-20T00:14:03Z
8,996,824
<pre><code>from pylab import * specgram(signal) </code></pre> <p>is the easiest. Also quite handy in this context:</p> <pre><code>subplot </code></pre> <p>But be warned: Matplotlib is very slow but it creates beautiful images. You should not use it for demanding animation, even less when you are dealing with 3D</p>
3
2012-01-25T01:28:40Z
[ "python", "image", "graphics", "audio", "fft" ]
FFT for Spectrograms in Python
1,303,307
<p>How would I go about using Python to read the frequency peaks from a WAV PCM file and then be able to generate an image of it, for spectogram analysis?</p> <p>I'm trying to make a program that allows you to read any audio file, converting it to WAV PCM, and then finding the peaks and frequency cutoffs.</p>
24
2009-08-20T00:14:03Z
9,714,655
<p>If you need to convert from PCM format to integers, you'll want to use struct.unpack.</p>
1
2012-03-15T05:54:00Z
[ "python", "image", "graphics", "audio", "fft" ]
Getting a map() to return a list in Python 3.x
1,303,347
<p>I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:</p> <p><strong>A:</strong> Python 2.6:</p> <pre><code>&gt;&gt;&gt; map(chr, [66, 53, 0, 94]) ['B', '5', '\x00', '^'] </code></pre> <p>However, on Python 3.1, the above returns a map object.</p> <p><strong>B:</strong> Python 3.1:</p> <pre><code>&gt;&gt;&gt; map(chr, [66, 53, 0, 94]) &lt;map object at 0x00AF5570&gt; </code></pre> <p>How do I retrieve the mapped list (as in <strong>A</strong> above) on Python 3.x? </p> <p>Alternatively, is there a better way of doing this? My initial list object has around 45 items and id like to convert them to hex.</p>
155
2009-08-20T00:27:26Z
1,303,353
<p>Why aren't you doing this:</p> <pre><code>[chr(x) for x in [66,53,0,94]] </code></pre> <p>It's called a list comprehension. You can find plenty of information on Google, but <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">here's the link to the Python (2.6) documentation on list comprehensions</a>. You might be more interested in <a href="http://docs.python.org/3.1/tutorial/datastructures.html#list-comprehensions">the Python 3 documenation</a>, though.</p>
50
2009-08-20T00:28:19Z
[ "python", "list", "python-3.x", "map-function" ]
Getting a map() to return a list in Python 3.x
1,303,347
<p>I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:</p> <p><strong>A:</strong> Python 2.6:</p> <pre><code>&gt;&gt;&gt; map(chr, [66, 53, 0, 94]) ['B', '5', '\x00', '^'] </code></pre> <p>However, on Python 3.1, the above returns a map object.</p> <p><strong>B:</strong> Python 3.1:</p> <pre><code>&gt;&gt;&gt; map(chr, [66, 53, 0, 94]) &lt;map object at 0x00AF5570&gt; </code></pre> <p>How do I retrieve the mapped list (as in <strong>A</strong> above) on Python 3.x? </p> <p>Alternatively, is there a better way of doing this? My initial list object has around 45 items and id like to convert them to hex.</p>
155
2009-08-20T00:27:26Z
1,303,354
<p>Do this:</p> <pre><code>list(map(chr,[66,53,0,94])) </code></pre> <p>In Python 3+, many processes that iterate over iterables return iterators themselves. In most cases, this ends up saving memory, and should make things go faster. </p> <p>If all you're going to do is iterate over this list eventually, there's no need to even convert it to a list, because you can still iterate over the <code>map</code> object like so:</p> <pre><code># Prints "ABCD" for ch in map(chr,[65,66,67,68]): print(ch) </code></pre>
256
2009-08-20T00:28:40Z
[ "python", "list", "python-3.x", "map-function" ]
Getting a map() to return a list in Python 3.x
1,303,347
<p>I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:</p> <p><strong>A:</strong> Python 2.6:</p> <pre><code>&gt;&gt;&gt; map(chr, [66, 53, 0, 94]) ['B', '5', '\x00', '^'] </code></pre> <p>However, on Python 3.1, the above returns a map object.</p> <p><strong>B:</strong> Python 3.1:</p> <pre><code>&gt;&gt;&gt; map(chr, [66, 53, 0, 94]) &lt;map object at 0x00AF5570&gt; </code></pre> <p>How do I retrieve the mapped list (as in <strong>A</strong> above) on Python 3.x? </p> <p>Alternatively, is there a better way of doing this? My initial list object has around 45 items and id like to convert them to hex.</p>
155
2009-08-20T00:27:26Z
1,303,355
<p>I'm not familiar with Python 3.1, but will this work?</p> <pre><code>[chr(x) for x in [66, 53, 0, 94]] </code></pre>
9
2009-08-20T00:28:44Z
[ "python", "list", "python-3.x", "map-function" ]
Getting a map() to return a list in Python 3.x
1,303,347
<p>I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:</p> <p><strong>A:</strong> Python 2.6:</p> <pre><code>&gt;&gt;&gt; map(chr, [66, 53, 0, 94]) ['B', '5', '\x00', '^'] </code></pre> <p>However, on Python 3.1, the above returns a map object.</p> <p><strong>B:</strong> Python 3.1:</p> <pre><code>&gt;&gt;&gt; map(chr, [66, 53, 0, 94]) &lt;map object at 0x00AF5570&gt; </code></pre> <p>How do I retrieve the mapped list (as in <strong>A</strong> above) on Python 3.x? </p> <p>Alternatively, is there a better way of doing this? My initial list object has around 45 items and id like to convert them to hex.</p>
155
2009-08-20T00:27:26Z
24,507,069
<p>List-returning map function has the advantage of saving typing, especially during interactive sessions. You can define <code>lmap</code> function (on the analogy of python2's <code>imap</code>) that returns list:</p> <pre><code>lmap = lambda func, *iterable: list(map(func, *iterable) </code></pre> <p>Then calling <code>lmap</code> instead of <code>map</code> will do the job: <code>lmap(str, x)</code> is shorter by 5 characters (30% in this case) than <code>list(map(str, x))</code> and is certainly shorter than <code>[str(v) for v in x]</code>. You may create similar functions for <code>filter</code> too.</p> <p>There was a comment to the original question:</p> <blockquote> <p>I would suggest a rename to Getting map() to return a list in Python 3.* as it applies to all Python3 versions. Is there a way to do this? – meawoppl Jan 24 at 17:58</p> </blockquote> <p>It <em>is</em> possible to do that, but it is a very bad idea. Just for fun, here's how you may (<strong>but should not</strong>) do it:</p> <pre><code>__global_map = map #keep reference to the original map lmap = lambda func, *iterable: list(__global_map(func, *iterable)) # using "map" here will cause infinite recursion map = lmap x = [1, 2, 3] map(str, x) #test map = __global_map #restore the original map and don't do that again map(str, x) #iterator </code></pre>
13
2014-07-01T09:41:21Z
[ "python", "list", "python-3.x", "map-function" ]
Getting a map() to return a list in Python 3.x
1,303,347
<p>I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:</p> <p><strong>A:</strong> Python 2.6:</p> <pre><code>&gt;&gt;&gt; map(chr, [66, 53, 0, 94]) ['B', '5', '\x00', '^'] </code></pre> <p>However, on Python 3.1, the above returns a map object.</p> <p><strong>B:</strong> Python 3.1:</p> <pre><code>&gt;&gt;&gt; map(chr, [66, 53, 0, 94]) &lt;map object at 0x00AF5570&gt; </code></pre> <p>How do I retrieve the mapped list (as in <strong>A</strong> above) on Python 3.x? </p> <p>Alternatively, is there a better way of doing this? My initial list object has around 45 items and id like to convert them to hex.</p>
155
2009-08-20T00:27:26Z
38,702,484
<p>New and neat in Python 3.5:</p> <pre><code>[*map(chr, [66, 53, 0, 94])] </code></pre> <p>Thanks to <a href="https://docs.python.org/3/whatsnew/3.5.html#whatsnew-pep-448" rel="nofollow">Additional Unpacking Generalizations</a></p>
3
2016-08-01T15:18:41Z
[ "python", "list", "python-3.x", "map-function" ]
python shutil.copytree - ignore permissions
1,303,413
<p>Python's <code>shutil.copytree</code> is not very flexible; what is the simplest way to add support for ignoring permissions while copying in <code>copytree</code> (without having to re-write its implementation)?</p> <p>Otherwise, <code>copytree</code> fails like this:</p> <pre><code>(…)”[Errno 45] Operation not supported: ‘/path/foo/bar’” </code></pre>
4
2009-08-20T00:51:17Z
1,303,434
<p>You have <code>shutil.py</code> in your standard Python distribution (on Ubuntu, mine is under <code>/usr/lib/python2.6</code> for instance; Windows might be <code>C:\Python26\lib</code>?). The copytree function is only 38 lines long (34 if you don't count comments), and the end of the docstring explicitly states:</p> <blockquote> <p><code>XXX Consider this example code rather than the ultimate tool.</code></p> </blockquote> <p>So the simplest way really would be to change/add a couple lines to copytree, or find another library, to be honest.</p>
3
2009-08-20T00:58:06Z
[ "python", "file", "shutil" ]
python shutil.copytree - ignore permissions
1,303,413
<p>Python's <code>shutil.copytree</code> is not very flexible; what is the simplest way to add support for ignoring permissions while copying in <code>copytree</code> (without having to re-write its implementation)?</p> <p>Otherwise, <code>copytree</code> fails like this:</p> <pre><code>(…)”[Errno 45] Operation not supported: ‘/path/foo/bar’” </code></pre>
4
2009-08-20T00:51:17Z
17,022,146
<p>Not thread-safe (or advisable in general) but OK for a throwaway script:</p> <pre> import shutil _orig_copystat = shutil.copystat shutil.copystat = lambda x, y: x shutil.copytree(src, dst) shutil.copystat = _orig_copystat </pre>
1
2013-06-10T10:50:47Z
[ "python", "file", "shutil" ]
Threaded Django task doesn't automatically handle transactions or db connections?
1,303,654
<p>I've got Django set up to run some recurring tasks in their own threads, and I noticed that they were always leaving behind unfinished database connection processes (pgsql "Idle In Transaction").</p> <p>I looked through the Postgres logs and found that the transactions weren't being completed (no ROLLBACK). I tried using the various transaction decorators on my functions, no luck.</p> <p>I switched to manual transaction management and did the rollback manually, that worked, but still left the processes as "Idle".</p> <p>So then I called connection.close(), and all is well.</p> <p>But I'm left wondering, why doesn't Django's typical transaction and connection management work for these threaded tasks that are being spawned from the main Django thread?</p>
50
2009-08-20T02:26:48Z
1,346,401
<p>After weeks of testing and reading the Django source code, I've found the answer to my own question:</p> <p><strong>Transactions</strong></p> <p>Django's default autocommit behavior still holds true for my threaded function. However, it states in the Django docs:</p> <blockquote> <p>As soon as you perform an action that needs to write to the database, Django produces the INSERT/UPDATE/DELETE statements and then does the COMMIT. There’s no implicit ROLLBACK.</p> </blockquote> <p>That last sentence is very literal. It DOES NOT issue a ROLLBACK command unless something in Django has set the dirty flag. Since my function was only doing SELECT statements it never set the dirty flag and didn't trigger a COMMIT.</p> <p>This goes against the fact that PostgreSQL thinks the transaction requires a ROLLBACK because Django issued a SET command for the timezone. In reviewing the logs, I threw myself off because I kept seeing these ROLLBACK statements and assumed Django's transaction management was the source. Turns out it's not, and that's OK.</p> <p><strong>Connections</strong></p> <p>The connection management is where things do get tricky. It turns out Django uses <code>signals.request_finished.connect(close_connection)</code> to close the database connection it normally uses. Since nothing normally happens in Django that doesn't involve a request, you take this behavior for granted.</p> <p>In my case, though, there was no request because the job was scheduled. No request means no signal. No signal means the database connection was never closed.</p> <p>Going back to transactions, it turns out that simply issuing a call to <code>connection.close()</code> in the absence of any changes to the transaction management issues the ROLLBACK statement in the PostgreSQL log that I'd been looking for.</p> <p><strong>Solution</strong></p> <p>The solution is to allow the normal Django transaction management to proceed as normal and to simply close the connection one of three ways:</p> <ol> <li>Write a decorator that closes the connection and wrap the necessary functions in it.</li> <li>Hook into the existing request signals to have Django close the connection.</li> <li>Close the connection manually at the end of the function.</li> </ol> <p>Any of those three will (and do) work.</p> <p>This has driven me crazy for weeks. I hope this helps someone else in the future!</p>
85
2009-08-28T11:22:05Z
[ "python", "database", "django", "multithreading", "transactions" ]
Unable to install python berkeleydb access on osx
1,303,659
<p>I installed python 2.6 on my mac (which ships with 2.5, and I am going crazy in working with 2.6) Everything has been installed on <code>/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/</code>. Now I want to install the python BerkeleyDB module, but it goes syntax error during the build:</p> <pre><code>creating build/temp.macosx-10.3-fat-2.6/extsrc gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 -DPYBSDDB_STANDALONE=1 -I~/include -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c extsrc/_bsddb.c -o build/temp.macosx-10.3-fat-2.6/extsrc/_bsddb.o extsrc/_bsddb.c:232: error: syntax error before 'DB_ENV' extsrc/_bsddb.c:232: warning: no semicolon at end of struct or union extsrc/_bsddb.c:239: error: syntax error before '}' token extsrc/_bsddb.c:239: warning: data definition has no type or storage class extsrc/_bsddb.c:245: error: syntax error before 'DBEnvObject' extsrc/_bsddb.c:245: warning: no semicolon at end of struct or union extsrc/_bsddb.c:258: error: syntax error before '}' token extsrc/_bsddb.c:258: warning: data definition has no type or storage class &lt;and so on&gt; extsrc/_bsddb.c:5915: error: 'DB_OLD_VERSION' undeclared (first use in this function) extsrc/_bsddb.c:5916: error: 'DB_RUNRECOVERY' undeclared (first use in this function) extsrc/_bsddb.c:5917: error: 'DB_VERIFY_BAD' undeclared (first use in this function) lipo: can't figure out the architecture type of: /var/folders/Ye/YeXcn-oIE7ybm-TS4yB8c++++TQ/-Tmp-//cclJF2Xy.out </code></pre> <p>Google does not help.</p>
1
2009-08-20T02:28:02Z
1,303,687
<p>It may save you a lot of time to reinstall python using fink or macports, then get the berkley package from either.</p>
0
2009-08-20T02:45:30Z
[ "python", "osx" ]
Unable to install python berkeleydb access on osx
1,303,659
<p>I installed python 2.6 on my mac (which ships with 2.5, and I am going crazy in working with 2.6) Everything has been installed on <code>/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/</code>. Now I want to install the python BerkeleyDB module, but it goes syntax error during the build:</p> <pre><code>creating build/temp.macosx-10.3-fat-2.6/extsrc gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 -DPYBSDDB_STANDALONE=1 -I~/include -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c extsrc/_bsddb.c -o build/temp.macosx-10.3-fat-2.6/extsrc/_bsddb.o extsrc/_bsddb.c:232: error: syntax error before 'DB_ENV' extsrc/_bsddb.c:232: warning: no semicolon at end of struct or union extsrc/_bsddb.c:239: error: syntax error before '}' token extsrc/_bsddb.c:239: warning: data definition has no type or storage class extsrc/_bsddb.c:245: error: syntax error before 'DBEnvObject' extsrc/_bsddb.c:245: warning: no semicolon at end of struct or union extsrc/_bsddb.c:258: error: syntax error before '}' token extsrc/_bsddb.c:258: warning: data definition has no type or storage class &lt;and so on&gt; extsrc/_bsddb.c:5915: error: 'DB_OLD_VERSION' undeclared (first use in this function) extsrc/_bsddb.c:5916: error: 'DB_RUNRECOVERY' undeclared (first use in this function) extsrc/_bsddb.c:5917: error: 'DB_VERIFY_BAD' undeclared (first use in this function) lipo: can't figure out the architecture type of: /var/folders/Ye/YeXcn-oIE7ybm-TS4yB8c++++TQ/-Tmp-//cclJF2Xy.out </code></pre> <p>Google does not help.</p>
1
2009-08-20T02:28:02Z
1,304,700
<p>The standard Python 2.6 installer for OS X from <a href="http://www.python.org/download/releases/2.6.2/" rel="nofollow">python.org</a> includes bsddb. Why build your own? </p>
2
2009-08-20T08:15:42Z
[ "python", "osx" ]
Unable to install python berkeleydb access on osx
1,303,659
<p>I installed python 2.6 on my mac (which ships with 2.5, and I am going crazy in working with 2.6) Everything has been installed on <code>/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/</code>. Now I want to install the python BerkeleyDB module, but it goes syntax error during the build:</p> <pre><code>creating build/temp.macosx-10.3-fat-2.6/extsrc gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 -DPYBSDDB_STANDALONE=1 -I~/include -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c extsrc/_bsddb.c -o build/temp.macosx-10.3-fat-2.6/extsrc/_bsddb.o extsrc/_bsddb.c:232: error: syntax error before 'DB_ENV' extsrc/_bsddb.c:232: warning: no semicolon at end of struct or union extsrc/_bsddb.c:239: error: syntax error before '}' token extsrc/_bsddb.c:239: warning: data definition has no type or storage class extsrc/_bsddb.c:245: error: syntax error before 'DBEnvObject' extsrc/_bsddb.c:245: warning: no semicolon at end of struct or union extsrc/_bsddb.c:258: error: syntax error before '}' token extsrc/_bsddb.c:258: warning: data definition has no type or storage class &lt;and so on&gt; extsrc/_bsddb.c:5915: error: 'DB_OLD_VERSION' undeclared (first use in this function) extsrc/_bsddb.c:5916: error: 'DB_RUNRECOVERY' undeclared (first use in this function) extsrc/_bsddb.c:5917: error: 'DB_VERIFY_BAD' undeclared (first use in this function) lipo: can't figure out the architecture type of: /var/folders/Ye/YeXcn-oIE7ybm-TS4yB8c++++TQ/-Tmp-//cclJF2Xy.out </code></pre> <p>Google does not help.</p>
1
2009-08-20T02:28:02Z
1,767,639
<p>Try:</p> <p>easy_install bsddb3</p>
0
2009-11-20T00:44:20Z
[ "python", "osx" ]
Unable to install python berkeleydb access on osx
1,303,659
<p>I installed python 2.6 on my mac (which ships with 2.5, and I am going crazy in working with 2.6) Everything has been installed on <code>/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/</code>. Now I want to install the python BerkeleyDB module, but it goes syntax error during the build:</p> <pre><code>creating build/temp.macosx-10.3-fat-2.6/extsrc gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 -DPYBSDDB_STANDALONE=1 -I~/include -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c extsrc/_bsddb.c -o build/temp.macosx-10.3-fat-2.6/extsrc/_bsddb.o extsrc/_bsddb.c:232: error: syntax error before 'DB_ENV' extsrc/_bsddb.c:232: warning: no semicolon at end of struct or union extsrc/_bsddb.c:239: error: syntax error before '}' token extsrc/_bsddb.c:239: warning: data definition has no type or storage class extsrc/_bsddb.c:245: error: syntax error before 'DBEnvObject' extsrc/_bsddb.c:245: warning: no semicolon at end of struct or union extsrc/_bsddb.c:258: error: syntax error before '}' token extsrc/_bsddb.c:258: warning: data definition has no type or storage class &lt;and so on&gt; extsrc/_bsddb.c:5915: error: 'DB_OLD_VERSION' undeclared (first use in this function) extsrc/_bsddb.c:5916: error: 'DB_RUNRECOVERY' undeclared (first use in this function) extsrc/_bsddb.c:5917: error: 'DB_VERIFY_BAD' undeclared (first use in this function) lipo: can't figure out the architecture type of: /var/folders/Ye/YeXcn-oIE7ybm-TS4yB8c++++TQ/-Tmp-//cclJF2Xy.out </code></pre> <p>Google does not help.</p>
1
2009-08-20T02:28:02Z
1,898,019
<p>Here's what I did for python2.5 easy_install didn't work for me</p> <pre><code># get berkeley db sudo port install db44 # download and untar bsddb3-4.8.1 and cd to the directory sudo python setup.py --berkeley-db-incdir=/opt/local/include/db44 --berkeley-db-libdir=/opt/local/lib/db44 build # test program test.py ran but don't know what it did python test.py # install sudo python setup.py --berkeley-db-incdir=/opt/local/include/db44 --berkeley-db-libdir=/opt/local/lib/db44 install # import as needed </code></pre>
0
2009-12-13T22:25:16Z
[ "python", "osx" ]
Unable to install python berkeleydb access on osx
1,303,659
<p>I installed python 2.6 on my mac (which ships with 2.5, and I am going crazy in working with 2.6) Everything has been installed on <code>/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/</code>. Now I want to install the python BerkeleyDB module, but it goes syntax error during the build:</p> <pre><code>creating build/temp.macosx-10.3-fat-2.6/extsrc gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 -DPYBSDDB_STANDALONE=1 -I~/include -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c extsrc/_bsddb.c -o build/temp.macosx-10.3-fat-2.6/extsrc/_bsddb.o extsrc/_bsddb.c:232: error: syntax error before 'DB_ENV' extsrc/_bsddb.c:232: warning: no semicolon at end of struct or union extsrc/_bsddb.c:239: error: syntax error before '}' token extsrc/_bsddb.c:239: warning: data definition has no type or storage class extsrc/_bsddb.c:245: error: syntax error before 'DBEnvObject' extsrc/_bsddb.c:245: warning: no semicolon at end of struct or union extsrc/_bsddb.c:258: error: syntax error before '}' token extsrc/_bsddb.c:258: warning: data definition has no type or storage class &lt;and so on&gt; extsrc/_bsddb.c:5915: error: 'DB_OLD_VERSION' undeclared (first use in this function) extsrc/_bsddb.c:5916: error: 'DB_RUNRECOVERY' undeclared (first use in this function) extsrc/_bsddb.c:5917: error: 'DB_VERIFY_BAD' undeclared (first use in this function) lipo: can't figure out the architecture type of: /var/folders/Ye/YeXcn-oIE7ybm-TS4yB8c++++TQ/-Tmp-//cclJF2Xy.out </code></pre> <p>Google does not help.</p>
1
2009-08-20T02:28:02Z
6,570,711
<p>I had a similar problem installing <code>lxml</code>. Try this for berkeleydb:</p> <pre><code>sudo env ARCHFLAGS="-arch i386 -arch x86_64" easy_install bsddb3 </code></pre>
0
2011-07-04T11:13:40Z
[ "python", "osx" ]
Unable to install python berkeleydb access on osx
1,303,659
<p>I installed python 2.6 on my mac (which ships with 2.5, and I am going crazy in working with 2.6) Everything has been installed on <code>/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/</code>. Now I want to install the python BerkeleyDB module, but it goes syntax error during the build:</p> <pre><code>creating build/temp.macosx-10.3-fat-2.6/extsrc gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 -DPYBSDDB_STANDALONE=1 -I~/include -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c extsrc/_bsddb.c -o build/temp.macosx-10.3-fat-2.6/extsrc/_bsddb.o extsrc/_bsddb.c:232: error: syntax error before 'DB_ENV' extsrc/_bsddb.c:232: warning: no semicolon at end of struct or union extsrc/_bsddb.c:239: error: syntax error before '}' token extsrc/_bsddb.c:239: warning: data definition has no type or storage class extsrc/_bsddb.c:245: error: syntax error before 'DBEnvObject' extsrc/_bsddb.c:245: warning: no semicolon at end of struct or union extsrc/_bsddb.c:258: error: syntax error before '}' token extsrc/_bsddb.c:258: warning: data definition has no type or storage class &lt;and so on&gt; extsrc/_bsddb.c:5915: error: 'DB_OLD_VERSION' undeclared (first use in this function) extsrc/_bsddb.c:5916: error: 'DB_RUNRECOVERY' undeclared (first use in this function) extsrc/_bsddb.c:5917: error: 'DB_VERIFY_BAD' undeclared (first use in this function) lipo: can't figure out the architecture type of: /var/folders/Ye/YeXcn-oIE7ybm-TS4yB8c++++TQ/-Tmp-//cclJF2Xy.out </code></pre> <p>Google does not help.</p>
1
2009-08-20T02:28:02Z
27,678,763
<p>For Mavericks/Yosemite (can use newer versions like db53 too):</p> <pre><code>sudo port install db51 sudo ln -sf /opt/local/include/db51/ /opt/local/lib/db51/include sudo ln -sf /opt/local/lib/db51/ /opt/local/lib/db51/lib sudo BERKELEYDB_DIR=/opt/local/lib/db51 ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future easy_install bsddb3 </code></pre>
0
2014-12-28T17:21:13Z
[ "python", "osx" ]
setting option in config file using SafeConfigParser
1,303,697
<p>I'm trying to set an option (xdebug.profiler_enable) in my php.ini file using python's ConfigParser object. here is the code: section in php.ini file im trying to modify</p> <pre><code>[xdebug] ;XDEBUG SETTINGS ;turn on the profiler? xdebug.profiler_enable=0 xdebug.profiler_append=1 xdebug.profiler_enable_trigger=0 xdebug.trace_output_name="%R" xdebug.profiler_output_dir="/home/made_up_user/www/cachegrind/" </code></pre> <p>Python </p> <pre><code>import sys import ConfigParser if __name__ == '__main__': phpIniLocation = "/home/made_up_user/Desktop/phpinicopy.ini"; phpIni = ConfigParser.RawConfigParser(); phpIni.read(phpIniLocation); xdebugSetting = phpIni.getboolean("xdebug", "xdebug.profiler_enable"); if xdebugSetting: phpIni.set("xdebug", "xdebug.profiler_enable", "0"); else: phpIni.set("xdebug", "xdebug.profiler_enable", "1"); </code></pre> <p>Environment: Ubuntu 9.04,python 2.6 Everything SEEMS to be working fine. The xdebugSetting variable returns the option's boolean value correctly, I can parse through the section and retrieve each of the options correct values, and the set method doesn't throw any exceptions, but when i check the file, the options have not been changed. I have used RawConfigParser, ConfigParser, and SafeConfigParser all with the same result. The script runs with roots permissions. Is there something I'm missing? How do I get the set method to work?</p>
1
2009-08-20T02:48:11Z
1,303,724
<pre><code>phpIni.write(open(phpIniLocation, 'w')) </code></pre> <p><a href="http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser.write" rel="nofollow">docs</a>.</p>
2
2009-08-20T02:59:42Z
[ "python", "linux", "file-io", "ubuntu" ]
Python string interpolation using dictionary and strings
1,304,025
<p>Given:</p> <pre><code>dict = {"path": "/var/blah"} curr = "1.1" prev = "1.0" </code></pre> <p>What's the best/shortest way to interpolate the string to generate the following:</p> <blockquote> <p>path: /var/blah curr: 1.1 prev: 1.0</p> </blockquote> <p>I know this works:</p> <pre><code>str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": prev} </code></pre> <p>But I was hoping there is a shorter way, such as:</p> <pre><code>str = "path: %(path)s curr: %s prev: %s" % (dict, curr, prev) </code></pre> <p>My apologies if this seems like an overly pedantic question.</p>
17
2009-08-20T04:54:16Z
1,304,050
<p>Maybe:</p> <pre><code>path = dict['path'] str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % locals() </code></pre> <p>I mean it works:</p> <pre><code>&gt;&gt;&gt; dict = {"path": "/var/blah"} &gt;&gt;&gt; curr = "1.1" &gt;&gt;&gt; prev = "1.0" &gt;&gt;&gt; path = dict['path'] &gt;&gt;&gt; str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % locals() &gt;&gt;&gt; str 'path: /var/blah curr: 1.1 prev: 1.0' </code></pre> <p>I just don't know if you consider that shorter.</p>
10
2009-08-20T05:03:33Z
[ "python", "string", "interpolation" ]
Python string interpolation using dictionary and strings
1,304,025
<p>Given:</p> <pre><code>dict = {"path": "/var/blah"} curr = "1.1" prev = "1.0" </code></pre> <p>What's the best/shortest way to interpolate the string to generate the following:</p> <blockquote> <p>path: /var/blah curr: 1.1 prev: 1.0</p> </blockquote> <p>I know this works:</p> <pre><code>str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": prev} </code></pre> <p>But I was hoping there is a shorter way, such as:</p> <pre><code>str = "path: %(path)s curr: %s prev: %s" % (dict, curr, prev) </code></pre> <p>My apologies if this seems like an overly pedantic question.</p>
17
2009-08-20T04:54:16Z
1,304,088
<p>Why not:</p> <pre><code>mystr = "path: %s curr: %s prev: %s" % (mydict[path], curr, prev) </code></pre> <p>BTW, I've changed a couple names you were using that trample upon builtin names -- don't do that, it's never needed and once in a while will waste a lot of your time tracking down a misbehavior it causes (where something's using the builtin name assuming it means the builtin but you have hidden it with the name of our own variable).</p>
10
2009-08-20T05:16:38Z
[ "python", "string", "interpolation" ]
Python string interpolation using dictionary and strings
1,304,025
<p>Given:</p> <pre><code>dict = {"path": "/var/blah"} curr = "1.1" prev = "1.0" </code></pre> <p>What's the best/shortest way to interpolate the string to generate the following:</p> <blockquote> <p>path: /var/blah curr: 1.1 prev: 1.0</p> </blockquote> <p>I know this works:</p> <pre><code>str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": prev} </code></pre> <p>But I was hoping there is a shorter way, such as:</p> <pre><code>str = "path: %(path)s curr: %s prev: %s" % (dict, curr, prev) </code></pre> <p>My apologies if this seems like an overly pedantic question.</p>
17
2009-08-20T04:54:16Z
1,304,098
<p>You can try this:</p> <pre><code>data = {"path": "/var/blah", "curr": "1.1", "prev": "1.0"} s = "path: %(path)s curr: %(curr)s prev: %(prev)s" % data </code></pre>
38
2009-08-20T05:20:28Z
[ "python", "string", "interpolation" ]
Python string interpolation using dictionary and strings
1,304,025
<p>Given:</p> <pre><code>dict = {"path": "/var/blah"} curr = "1.1" prev = "1.0" </code></pre> <p>What's the best/shortest way to interpolate the string to generate the following:</p> <blockquote> <p>path: /var/blah curr: 1.1 prev: 1.0</p> </blockquote> <p>I know this works:</p> <pre><code>str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": prev} </code></pre> <p>But I was hoping there is a shorter way, such as:</p> <pre><code>str = "path: %(path)s curr: %s prev: %s" % (dict, curr, prev) </code></pre> <p>My apologies if this seems like an overly pedantic question.</p>
17
2009-08-20T04:54:16Z
1,304,483
<p>And of course you could use the newer (from 2.6) <a href="http://docs.python.org/library/string.html#format-string-syntax"><strong>.format</strong></a> string method:</p> <pre><code>&gt;&gt;&gt; mydict = {"path": "/var/blah"} &gt;&gt;&gt; curr = "1.1" &gt;&gt;&gt; prev = "1.0" &gt;&gt;&gt; &gt;&gt;&gt; s = "path: {0} curr: {1} prev: {2}".format(mydict['path'], curr, prev) &gt;&gt;&gt; s 'path: /var/blah curr: 1.1 prev: 1.0' </code></pre> <p>Or, if all elements were in the dictionary, you could do this:</p> <pre><code>&gt;&gt;&gt; mydict = {"path": "/var/blah", "curr": 1.1, "prev": 1.0} &gt;&gt;&gt; "path: {path} curr: {curr} prev: {prev}".format(**mydict) 'path: /var/blah curr: 1.1 prev: 1.0' &gt;&gt;&gt; </code></pre> <p>From the <a href="http://docs.python.org/library/stdtypes.html#str.format">str.format()</a> documentation:</p> <blockquote> <p>This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in <a href="http://docs.python.org/library/stdtypes.html?highlight=format#string-formatting">String Formatting Operations</a> in new code.</p> </blockquote>
17
2009-08-20T07:17:00Z
[ "python", "string", "interpolation" ]
Python string interpolation using dictionary and strings
1,304,025
<p>Given:</p> <pre><code>dict = {"path": "/var/blah"} curr = "1.1" prev = "1.0" </code></pre> <p>What's the best/shortest way to interpolate the string to generate the following:</p> <blockquote> <p>path: /var/blah curr: 1.1 prev: 1.0</p> </blockquote> <p>I know this works:</p> <pre><code>str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": prev} </code></pre> <p>But I was hoping there is a shorter way, such as:</p> <pre><code>str = "path: %(path)s curr: %s prev: %s" % (dict, curr, prev) </code></pre> <p>My apologies if this seems like an overly pedantic question.</p>
17
2009-08-20T04:54:16Z
16,095,156
<p>You can do the following if you place your data inside a dictionary:</p> <pre><code>data = {"path": "/var/blah","curr": "1.1","prev": "1.0"} "{0}: {path}, {1}: {curr}, {2}: {prev}".format(*data, **data) </code></pre>
1
2013-04-19T00:12:17Z
[ "python", "string", "interpolation" ]
Python string interpolation using dictionary and strings
1,304,025
<p>Given:</p> <pre><code>dict = {"path": "/var/blah"} curr = "1.1" prev = "1.0" </code></pre> <p>What's the best/shortest way to interpolate the string to generate the following:</p> <blockquote> <p>path: /var/blah curr: 1.1 prev: 1.0</p> </blockquote> <p>I know this works:</p> <pre><code>str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": prev} </code></pre> <p>But I was hoping there is a shorter way, such as:</p> <pre><code>str = "path: %(path)s curr: %s prev: %s" % (dict, curr, prev) </code></pre> <p>My apologies if this seems like an overly pedantic question.</p>
17
2009-08-20T04:54:16Z
34,095,216
<p>You can also (soon) use <a href="https://www.python.org/dev/peps/pep-0498/" rel="nofollow">f-strings</a> in Python 3.6, which is probably the shortest way to format a string:</p> <pre><code>print f'path: {path} curr: {curr} prev: {prev}' </code></pre> <p>And even put all your data inside a dict:</p> <pre><code>d = {"path": path, "curr": curr, "prev": prev} print f'path: {d["path"]} curr: {d["curr"]} prev: {d["prev"]}' </code></pre>
1
2015-12-04T18:37:34Z
[ "python", "string", "interpolation" ]
Python string interpolation using dictionary and strings
1,304,025
<p>Given:</p> <pre><code>dict = {"path": "/var/blah"} curr = "1.1" prev = "1.0" </code></pre> <p>What's the best/shortest way to interpolate the string to generate the following:</p> <blockquote> <p>path: /var/blah curr: 1.1 prev: 1.0</p> </blockquote> <p>I know this works:</p> <pre><code>str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": prev} </code></pre> <p>But I was hoping there is a shorter way, such as:</p> <pre><code>str = "path: %(path)s curr: %s prev: %s" % (dict, curr, prev) </code></pre> <p>My apologies if this seems like an overly pedantic question.</p>
17
2009-08-20T04:54:16Z
37,547,526
<p>If you don't want to add the unchanging variables to your dictionary each time, you can reference both the variables and the dictionary keys using format:</p> <p><code>str = "path {path} curr: {curr} prev: {prev}".format(curr=curr, prev=prev, **dict)</code></p> <p>It might be bad form logically, but it makes things more modular expecting curr and prev to be mostly static and the dictionary to update.</p>
1
2016-05-31T13:44:50Z
[ "python", "string", "interpolation" ]
Sage CRM web services example in Python
1,304,106
<p>I am trying to write a Python consumer for Sage CRM using their Web Services interface. I am using SOAPpy as Python SOAP library (not married to it, was easy to install on Ubuntu so went with it). </p> <p>Managed to fetch the WSDL using the Proxy and executed the logon method exposed by Sage CRM. </p> <pre><code> from SOAPpy import * proxy = WSDL.Proxy('http://192.168.0.3/MATE/eware.dll/webservice/webservice.wsdl') </code></pre> It returns a session object which sort of looks like <pre> SOAPpy.Types.structType result at 151924492: {'sessionid': '170911104429792'} </pre> <p>Now I am trying to use Sage CRM's queryrecord method to query the data, and that returns </p> <pre> Fault SOAP-ENV:Server: No active usersession detected </pre> <p>Reading the documentation reveals that I have to send back to the session id that recd. when I logged in back with each requests.</p> <p>According to the Sage documentation I have to send it back as such</p> <pre><code> SID = binding.logon("admin", ""); binding.SessionHeaderValue = new SessionHeader(); binding.SessionHeaderValue.sessionId = SID.sessionid; </code> </pre> <p>Any ideas how to do append this to the headers using SOAPpy?</p> <p>Any pointers will be greatly appreciated.</p>
3
2009-08-20T05:23:27Z
1,305,179
<p>First, just to comment on SOAPpy vs. other soap libraries... SOAPpy traditionally has been the easy-to-use library that didn't support complex data structures. So if it works for your case then you are better off. For more complex data structures in the WSDL you'd need to move ZSI.</p> <p>Anyway, the documentation link for the project on SourceForge seems to be broken, so I'll just cut+paste the header documentation here with some minor formatting changes:</p> <h2>Using Headers</h2> <p>SOAPpy has a Header class to hold data for the header of a SOAP message. Each Header instance has methods to set/get the MustUnderstand attribute, and methods to set/get the Actor attribute.</p> <p>SOAPpy also has a SOAPContext class so that each server method can be implemented in such a way that it gets the context of the connecting client. This includes both common SOAP information and connection information (see below for an example).</p> <h2>Client Examples</h2> <pre><code>import SOAPpy test = 42 server = SOAPpy.SOAPProxy("http://localhost:8888") server = server._sa ("urn:soapinterop") hd = SOAPpy.Header() hd.InteropTestHeader ='This should fault, as you don\'t understand the header.' hd._setMustUnderstand ('InteropTestHeader', 0) hd._setActor ('InteropTestHeader','http://schemas.xmlsoap.org/soap/actor/next') server = server._hd (hd) print server.echoInteger (test) </code></pre> <p>This should succeed (provided the server has defined echoInteger), as it builds a valid header into this client with MustUnderstand set to 0 and then sends the SOAP with this header.</p> <pre><code>import SOAPpy test = 42 server = SOAPpy.SOAPProxy("http://localhost:8888") server = server._sa ("urn:soapinterop") #Header hd = SOAPpy.Header() hd.InteropTestHeader = 'This should fault,as you don\'t understand the header.' hd._setMustUnderstand ('InteropTestHeader', 1) hd._setActor ('InteropTestHeader','http://schemas.xmlsoap.org/soap/actor/next') server = server._hd (hd) print server.echoInteger (test) </code></pre> <p>This should fail (even if the server has defined 'echoInteger'), as it builds a valid header into this client, but sets MustUnderstand to 1 for a message that the server presumably won't understand before sending. </p>
0
2009-08-20T10:12:32Z
[ "python", "soap", "crm", "sage-crm" ]
Sage CRM web services example in Python
1,304,106
<p>I am trying to write a Python consumer for Sage CRM using their Web Services interface. I am using SOAPpy as Python SOAP library (not married to it, was easy to install on Ubuntu so went with it). </p> <p>Managed to fetch the WSDL using the Proxy and executed the logon method exposed by Sage CRM. </p> <pre><code> from SOAPpy import * proxy = WSDL.Proxy('http://192.168.0.3/MATE/eware.dll/webservice/webservice.wsdl') </code></pre> It returns a session object which sort of looks like <pre> SOAPpy.Types.structType result at 151924492: {'sessionid': '170911104429792'} </pre> <p>Now I am trying to use Sage CRM's queryrecord method to query the data, and that returns </p> <pre> Fault SOAP-ENV:Server: No active usersession detected </pre> <p>Reading the documentation reveals that I have to send back to the session id that recd. when I logged in back with each requests.</p> <p>According to the Sage documentation I have to send it back as such</p> <pre><code> SID = binding.logon("admin", ""); binding.SessionHeaderValue = new SessionHeader(); binding.SessionHeaderValue.sessionId = SID.sessionid; </code> </pre> <p>Any ideas how to do append this to the headers using SOAPpy?</p> <p>Any pointers will be greatly appreciated.</p>
3
2009-08-20T05:23:27Z
34,109,040
<p>Am just figuring this out too. I have the core of this done though, so this ought to speed things up for anyone else who needs this! I am assuming other Sage subsystems work the same way (but I don't yet know), so I tried to account for that possibility.</p> <p>First, you need this module I wrote called pySage.py. It defines a class for running a process which you'll need to subclass for your custom use.</p> <pre><code>#---------------------------- # # pySage.py # # Author: BuvinJ # Created: December, 2015 # # This module defines the SageProcess class. # This class handles connecting and disconnecting # to Sage web services, and provides an object # through which the web services can be accessed. # #---------------------------- # Download SOAPpy from: https://pypi.python.org/pypi/SOAPpy from SOAPpy import WSDL, Types as soapTypes from enum import Enum SageSubsystem = Enum( 'SageSubsystem', 'CRM' ) # Define your sub system connection parameters here. CRM_WSDL_FILE_URL = "http://CRMservername/CRMinstallname/eWare.dll/webservice/webservice.wsdl" CRM_USER = "admin" CRM_PASSWORD = "" CRM_NAMESPACE = "http://tempuri.org/type" #---------------------------- # SageProcess Class # To use this class: # # 1) Create a SageProcess subclass and define the method # body(). # 2) Instanitate an instance of the subclass, passing a # SageSubsystem enumeration, e.g. SageSubsystem.CRM. # 3) Invoke the run() method of the process instance. # This will in turn invoke body() to execute your # custom actions. # # To access the sage web services, use the "sage" member of # a SageProcess instance. For help using Sage web service # objects see: # https://community.sagecrm.com/developerhelp/default.htm # # You may also invoke the sageHelp() method of a SageProcess # instance to view the top level web service object members. # Or, recordHelp( sageRecord ) to view the members of the # various record objects returned by the web services. # #---------------------------- class SageProcess(): # Construction &amp; service connection methods #---------------------------- def __init__( self, subsystem, verbose=False ): """ @param subsystem: The Sage subsystem on which to run the process. Ex. SageSubsystem.CRM @param verbose: If True, details of the SOAP exchange are displayed. """ self.subsystem = subsystem self.verbose = verbose if self.subsystem == SageSubsystem.CRM : self.wsdl = CRM_WSDL_FILE_URL self.namespace = CRM_NAMESPACE self.username = CRM_USER self.password = CRM_PASSWORD else : self.abort( "Unknown subsystem specified!" ) self.sessionId = None self.connect() def connect( self ) : try : self.sage = WSDL.Proxy( self.wsdl, namespace=self.namespace ) except : self.abort( "WSDL failure. This is may be caused by access settings. File url: " + CRM_WSDL_FILE_URL ) if self.verbose : "Connected to web service." self.soapProxy = self.sage.soapproxy if self.verbose : self.sageDebug() # Core process methods #---------------------------- def run( self ) : if not self.logOn( self.username, self.password ) : self.abort( "Log On failed!" ) else : if self.verbose : print "Logged On. Session Id: " + str( self.sessionId ) self.appendSessionHeader() self.body() if self.logOff() : if self.verbose : print "Logged Off." def logOn( self, username, password ) : try : self.sessionId = self.sage.logon( username, password ).sessionid except Exception as e: self.abortOnException( "Log On failure.\n(You may need to enable forced logins.)", e ) return (self.sessionId is not None) def appendSessionHeader( self ) : self.soapProxy = self.soapProxy._sa( "urn:sessionid" ) soapHeader = soapTypes.headerType() soapHeader.SessionHeader = soapTypes.structType( None, "SessionHeader" ) soapHeader.SessionHeader.sessionId = soapTypes.stringType( self.sessionId ) self.soapProxy = self.soapProxy._hd( soapHeader ) self.sage.soapproxy = self.soapProxy def body( self ) : """ You should override this method when you subclass SageProcess. It will be called after logging on, and will be followed by logging off. Use self.sage to access the system from within this method. """ def logOff( self ) : success = False try : success = self.sage.logoff( self.sessionId ) except Exception as e: self.abortOnException( "Log off failure.", e ) return success # Helper methods #---------------------------- # Immediately exit the program with an indication of success def quit( self, msg=None ) : if msg is not None: print msg import os os._exit( 0 ) # Immediately exit the program with an error def abort( self, msg=None, errorCode=1 ) : if msg is not None: print msg print "Process terminated..." import os os._exit( errorCode ) # Immediately exit the program with an Exception error def abortOnException( self, e, msg=None, errorCode=1 ) : if msg is not None: print msg print "" print e print "" self.abort( None, errorCode ) def sageDebug( self, enable=True ) : if enable : self.soapProxy.config.debug = 1 else : self.soapProxy.config.debug = 0 def sageHelp( self ) : print "\nSage web service methods:\n" self.sage.show_methods() def recordHelp( self, record, typeDescr=None ) : if record is None : return print "" description = "record object members:\n" if typeDescr is not None : description = typeDescr + " " + description print description print dir( record ) print "" </code></pre> <p>Then, add a client for this class. Here's an example I created called fetch_company_data_example.py:</p> <pre><code>#---------------------------- # # fetch_company_data_example.py # #---------------------------- from pySage import SageProcess, SageSubsystem def main() : # Get process parameters from the command line import sys try : companyId = sys.argv[1] except : abort( "Usage: " + sys.argv[0] + " companyId [-v] [--verbose]" ) verbose = False try : if ( sys.argv[2] == "-v" or sys.argv[2] == "--verbose" ) : verbose = True except : pass # Create &amp; run the custom Sage process process = FetchCompanyDataProcess( companyId, verbose ) process.run() class FetchCompanyDataProcess( SageProcess ): def __init__( self, companyId, verbose ): SageProcess.__init__( self, SageSubsystem.CRM, verbose ) self.companyId = companyId def body( self ): # Fetch the company record (exiting if no data is returned) companyRecord = self.getCompanyRecord() if companyRecord is None: self.quit( "\nNo records found.\n" ) # Uncomment for development help... #if self.verbose : self.recordHelp( companyRecord, "Company" ) #if self.verbose : self.recordHelp( companyRecord.address.records, "Address" ) # Print some of the company info print "" print "Company Id: " + self.companyId print "Name: " + companyRecord.name print "Location: " + self.getCompanyLocation( companyRecord ) print "" def getCompanyRecord( self ) : try : queryentity = self.sage.queryentity( self.companyId, "company" ) except Exception as e: self.abortOnException( "Get Company Record failure.", e ) try : return queryentity.records except : return None def getCompanyLocation( self, companyRecord ) : try : return (companyRecord.address.records.city + ", " + companyRecord.address.records.state) except : return "" # Entry point if __name__ == '__main__' : main() </code></pre>
0
2015-12-05T18:08:24Z
[ "python", "soap", "crm", "sage-crm" ]
Python egg: where is it installed?
1,304,122
<p>I'm trying to install py-appscript on the mac using 'sudo easy_install appscript'. The command runs and I get a message saying "Installed /Library/Python/..../appscript=0.20.0-py2.5-maxosx-10.5-i386.egg".</p> <p>However, when I run a tool that required this (osaglue) I get an error that py-appscript isn't installed. My guess is that it's installed in some location that's not in my path, or that I need to do something more to install it.</p> <p>Any ideas?</p> <p>The exact text I see when running easy_install is:</p> <blockquote> <p>Processing appscript-0.20.0-py2.5-macosx-10.5-i386.egg appscript 0.20.0 is already the active version in easy-install.pth</p> <p>Installed /Library/Python/2.5/site-packages/appscript-0.20.0-py2.5-macosx-10.5-i386.egg Processing dependencies for appscript==0.20.0 Finished processing dependencies for appscript==0.20.0</p> </blockquote> <p>and the error when trying to run osaglue is:</p> <blockquote> <p>Sorry, py-appscript 0.18.1 or later is required to use osaglue. Please see the following page for more information:</p> <pre><code>http://appscript.sourceforge.net/py-appscript/install.html </code></pre> <p>Please install py-appscript and run this command again.</p> </blockquote>
3
2009-08-20T05:29:42Z
1,304,172
<p>What does <code>which python</code> return?</p> <p>Update: Ok, so go into /usr/bin and do a <code>ls -l | grep python</code>. Does <code>/usr/bin/python</code> link to the OSX installation?</p> <p>If it does not, I had the same problem a while back. <code>easy_install</code> is installing the egg for the python package that came with OSX, but you're using a different version to execute code when you call python. I believe my solution was to reinstall setuptools and tell it to place the eggs in the location for the python distro that I wanted to use.</p>
0
2009-08-20T05:45:52Z
[ "python", "osx" ]
Python egg: where is it installed?
1,304,122
<p>I'm trying to install py-appscript on the mac using 'sudo easy_install appscript'. The command runs and I get a message saying "Installed /Library/Python/..../appscript=0.20.0-py2.5-maxosx-10.5-i386.egg".</p> <p>However, when I run a tool that required this (osaglue) I get an error that py-appscript isn't installed. My guess is that it's installed in some location that's not in my path, or that I need to do something more to install it.</p> <p>Any ideas?</p> <p>The exact text I see when running easy_install is:</p> <blockquote> <p>Processing appscript-0.20.0-py2.5-macosx-10.5-i386.egg appscript 0.20.0 is already the active version in easy-install.pth</p> <p>Installed /Library/Python/2.5/site-packages/appscript-0.20.0-py2.5-macosx-10.5-i386.egg Processing dependencies for appscript==0.20.0 Finished processing dependencies for appscript==0.20.0</p> </blockquote> <p>and the error when trying to run osaglue is:</p> <blockquote> <p>Sorry, py-appscript 0.18.1 or later is required to use osaglue. Please see the following page for more information:</p> <pre><code>http://appscript.sourceforge.net/py-appscript/install.html </code></pre> <p>Please install py-appscript and run this command again.</p> </blockquote>
3
2009-08-20T05:29:42Z
1,304,519
<p>You can found all your avaiable packages in the sys.path. Start the pythonshell and type in this code:</p> <pre><code>import sys print sys.path </code></pre>
2
2009-08-20T07:26:50Z
[ "python", "osx" ]
Python egg: where is it installed?
1,304,122
<p>I'm trying to install py-appscript on the mac using 'sudo easy_install appscript'. The command runs and I get a message saying "Installed /Library/Python/..../appscript=0.20.0-py2.5-maxosx-10.5-i386.egg".</p> <p>However, when I run a tool that required this (osaglue) I get an error that py-appscript isn't installed. My guess is that it's installed in some location that's not in my path, or that I need to do something more to install it.</p> <p>Any ideas?</p> <p>The exact text I see when running easy_install is:</p> <blockquote> <p>Processing appscript-0.20.0-py2.5-macosx-10.5-i386.egg appscript 0.20.0 is already the active version in easy-install.pth</p> <p>Installed /Library/Python/2.5/site-packages/appscript-0.20.0-py2.5-macosx-10.5-i386.egg Processing dependencies for appscript==0.20.0 Finished processing dependencies for appscript==0.20.0</p> </blockquote> <p>and the error when trying to run osaglue is:</p> <blockquote> <p>Sorry, py-appscript 0.18.1 or later is required to use osaglue. Please see the following page for more information:</p> <pre><code>http://appscript.sourceforge.net/py-appscript/install.html </code></pre> <p>Please install py-appscript and run this command again.</p> </blockquote>
3
2009-08-20T05:29:42Z
1,308,781
<p>Do you have more than one version of Python installed on your machine? (Apple install their own copy of Python in /System, with third-party modules at /Library/Python, by default.) If so, chances are, easy_install is installing appscript for one Python, while osaglue is using another.</p> <p>That said, if you're looking to generate glue code for objc-appscript, the simplest approach is to use ASDictionary (<a href="http://appscript.sourceforge.net/tools.html" rel="nofollow">http://appscript.sourceforge.net/tools.html</a>) to generate the glue directly; no need to mess around installing py-appscript and other dependencies.</p>
0
2009-08-20T21:01:29Z
[ "python", "osx" ]
relevent query to how to fetch public key from public key server
1,304,130
<pre><code>import urllib response = urllib.urlopen('http://pool.sks-keyservers.net/') print 'RESPONSE:', response print 'URL :', response.geturl() headers = response.info() print 'DATE :', headers['date'] print 'HEADERS :' print '---------' print headers data = response.read() print 'LENGTH :', len(data) print 'DATA :' print '---------' print data </code></pre> <p>This code enable me to see some webpage information and contents. what actually i had query that how to fetch the public key from any public key server using python function.</p>
2
2009-08-20T05:32:19Z
1,304,618
<p><a href="http://tools.ietf.org/html/draft-shaw-openpgp-hkp-00" rel="nofollow">This spec</a> should help you along, and stop you asking the same question repeatedly :). Basically you need to perform an HTTP GET request to the key server. Most key servers work on TCP port 11371 so you need to ensure that your firewall will let you through.</p> <p>For example, this URL will give you God's public key:</p> <p><a href="http://pool.sks-keyservers.net:11371/pks/lookup?op=get&amp;search=0x1278A1862492D908&amp;options=mr" rel="nofollow">http://pool.sks-keyservers.net:11371/pks/lookup?op=get&amp;search=0x1278A1862492D908&amp;options=mr</a></p> <p>The response is the key.</p> <p>In python:</p> <pre><code>import urllib f = urllib.urlopen('http://pool.sks-keyservers.net:11371/pks/lookup?op=get&amp;search=0x1278A1862492D908&amp;options=mr') data = f.read() print data -----BEGIN PGP PUBLIC KEY BLOCK----- Version: SKS 1.1.0 mQGiBD/dywoRBADkaddBEedMhFHGH3wKORuOIDFufSDERmlm2ktj3ma+GhfwvnuvvpAj+QYl ANh1K86Mm5k0dGOlhZwIr1zB3cIoNqt7TJ62v8w6mc0BA8UWzWJp0i6dHPa/qeeFFC53B8U1 h3FlPrmQGcVeV+hjOPFU7ANDSDm3tduad7NRxAst7QCg/8o++2BaAlTnbMB+Xfo23uEEc6UE AK0vD4EUPLfU5snfow1zUPXQUDalOcUP6RIhbi6yxKRFAIWI+7QgNPZf/Q2CFIRWsXKmW/ly IDSJgs5ruB+Yj8gmBZlrn5KMmW3EcEoHAhOP+ONZAIOb2LsaAjHjHOuefhlIr1T3gng+kLoD 3Yfy2WTugBizeNybAd2nfZyOJhfWA/4xTfg+Hbcb9n+8sEqgiuyQJEID38Q3FDmwSzRfBMbO JFrf8t/VHPjB7ZSdshl9GM86TXYnWjspzAjjQB8fxLgIim2mC0T46aRNdE0l2ozxRmS95nr7 YuHVA73vcI5tRn6qa9yLXew1YeN3YWxRfIW2AZG7bkRcXOIdl7tO9KiVpbQUR29kIDxHb2RA aGVhdmVuLmNvbT6IWAQQEQIAGAUCP93LCggLAwkIBwIBCgIZAQUbAwAAAAAKCRASeKGGJJLZ CAp7AJ9WqGhOnysRt/b7p+EuC86lhs3iBgCdEVwLgEwcc63OVbBxxFF6vyiNuNG5Ag0EP93L ChAIAPZCV7cIfwgXcqK61qlC8wXo+VMROU+28W65Szgg2gGnVqMU6Y9AVfPQB8bLQ6mUrfdM ZIZJ+AyDvWXpF9Sh01D49Vlf3HZSTz09jdvOmeFXklnN/biudE/F/Ha8g8VHMGHOfMlm/xX5 u/2RXscBqtNbno2gpXI61Brwv0YAWCvl9Ij9WE5J280gtJ3kkQc2azNsOA1FHQ98iLMcfFst jvbzySPAQ/ClWxiNjrtVjLhdONM0/XwXV0OjHRhs3jMhLLUq/zzhsSlAGBGNfISnCnLWhsQD GcgHKXrKlQzZlp+r0ApQmwJG0wg9ZqRdQZ+cfL2JSyIZJrqrol7DVekyCzsAAgIH/j7FzAvF jCmq3vXWnDOymAfJgTNyvYB67y0Xu2HXqGlXe92Gkxcf22w4X63TkZqMy7nXRbGc9WI2sr57 oSTJq3+42WHnVQjd9W10TFIgnH2YkuSC3KckMB5hC1yM9wqaIXNhfxXmq3B4V3UuKLyM3nQi SgWb9+kST3FxcGWXRB0Ec/tIJ0cNeFtu5IrYDNkRbcHep/BuwXEARUIpjlUlG7NPIaY4U03I /GSW7/IrG5/H7EsVWQzxRpcC6DcJjxJv2lIATvraXHwNpllOlPHFb9aABHmTOX7QLrG4FXTP ReH6rjf+w5tqJilTMwYdsZIV13U7+NBwVZHFbUdYMmqhOTiITAQYEQIADAUCP93LCgUbDAAA AAAKCRASeKGGJJLZCMqJAKCzS0hv0EY/GYdUKOOf3XiiZpu3qwCg9kFBm/GO+t073SsHkedu HT0F6po= =NhFO -----END PGP PUBLIC KEY BLOCK----- </code></pre>
4
2009-08-20T07:52:51Z
[ "python", "urllib" ]
relevent query to how to fetch public key from public key server
1,304,130
<pre><code>import urllib response = urllib.urlopen('http://pool.sks-keyservers.net/') print 'RESPONSE:', response print 'URL :', response.geturl() headers = response.info() print 'DATE :', headers['date'] print 'HEADERS :' print '---------' print headers data = response.read() print 'LENGTH :', len(data) print 'DATA :' print '---------' print data </code></pre> <p>This code enable me to see some webpage information and contents. what actually i had query that how to fetch the public key from any public key server using python function.</p>
2
2009-08-20T05:32:19Z
8,388,169
<p>Use <a href="http://pypi.python.org/pypi/python-hkp" rel="nofollow">http://pypi.python.org/pypi/python-hkp</a></p> <p>Python HPK client.</p> <p>Usage example:</p> <pre><code>&gt;&gt;&gt; from hkp import KeyServer &gt;&gt;&gt; serv = KeyServer('http://pool.sks-keyservers.net') &gt;&gt;&gt; serv.search('Dmitry Gladkov') [Key 28DFA7EC RSA (Encrypt or Sign), Key 473C57D9 RSA (Encrypt or Sign)] &gt;&gt;&gt; serv.search('Dmitry Gladkov')[0].identities [Identity Dmitry Gladkov (dgl) &lt;dmitry.gladkov@gmail.com&gt;] </code></pre>
1
2011-12-05T16:05:49Z
[ "python", "urllib" ]
Python logging SMTPHandler - handling offline SMTP server
1,304,593
<p>I have setup the logging module for my new python script. I have two handlers, one sending stuff to a file, and one for email alerts. The SMTPHandler is setup to mail anything at the ERROR level or above.</p> <p>Everything works great, unless the SMTP connection fails. If the SMTP server does not respond or authentication fails (it requires SMTP auth), then the whole script dies.</p> <p>I am fairly new to python, so I am trying to figure out how to capture the exception that the SMTPHandler is raising so that any problems sending the log message via email won't bring down my entire script. Since I am also writing errors to a log file, if the SMTP alert fails, I just want to keep going, not halt anything.</p> <p>If I need a "try:" statement, would it go around the logging.handlers.SMTPHandler setup, or around the individual calls to my_logger.error()?</p>
1
2009-08-20T07:45:57Z
1,304,622
<p>You probably need to do both. To figure this out, I suggest to install a local mail server and use that. This way, you can shut it down while your script runs and note down the error message.</p> <p>To keep the code maintainable, you should extends SMTPHandler in such a way that you can handle the exceptions in a single place (instead of wrapping every logger call with try-except).</p>
0
2009-08-20T07:55:43Z
[ "python", "logging", "handler" ]
Python logging SMTPHandler - handling offline SMTP server
1,304,593
<p>I have setup the logging module for my new python script. I have two handlers, one sending stuff to a file, and one for email alerts. The SMTPHandler is setup to mail anything at the ERROR level or above.</p> <p>Everything works great, unless the SMTP connection fails. If the SMTP server does not respond or authentication fails (it requires SMTP auth), then the whole script dies.</p> <p>I am fairly new to python, so I am trying to figure out how to capture the exception that the SMTPHandler is raising so that any problems sending the log message via email won't bring down my entire script. Since I am also writing errors to a log file, if the SMTP alert fails, I just want to keep going, not halt anything.</p> <p>If I need a "try:" statement, would it go around the logging.handlers.SMTPHandler setup, or around the individual calls to my_logger.error()?</p>
1
2009-08-20T07:45:57Z
1,308,024
<p>Exceptions which occur during logging should not stop your script, though they may cause a traceback to be printed to <code>sys.stderr</code>. In order to prevent this printout, do the following:</p> <pre><code>logging.raiseExceptions = 0 </code></pre> <p>This is not the default (because in development you typically want to know about failures) but in production, <code>raiseExceptions</code> should not be set.</p> <p>You should find that the <code>SMTPHandler</code> will attempt a re-connection the next time an ERROR (or higher) is logged.</p> <p><code>logging</code> <em>does</em> pass through <code>SystemExit</code> and <code>KeyboardInterrupt</code> exceptions, but all others should be handled so that they do not cause termination of an application which uses logging. If you find that this is not the case, please post specific details of the exceptions which are getting through and causing your script to terminate, and about your version of Python/operating system. Bear in mind that the script may appear to hang if there is a network timeout which is causing the handler to block (e.g. if a DNS lookup takes a long time, or if the SMTP connection takes a long time).</p>
4
2009-08-20T18:32:40Z
[ "python", "logging", "handler" ]
User-specific model in Django
1,304,608
<p>I have a model containing items, which has many different fields. There is another model which assigns a set of this field to each user using a m2m-relation.</p> <p>I want to achieve, that in the end, every user has access to a defined set of fields of the item model, and he only sees these field in views, he can only edit these field etc. Is there any generic way to set this up?</p>
0
2009-08-20T07:50:34Z
1,304,634
<p>One way to do this would be to break the <code>Item</code> model up into the parts that are individually assignable to a user. If you have fixed user types (admin, customer, team etc.) who can always see the same set of fields, these parts would be whole groups of fields. If it's very dynamic and you want to be able to set up individual fields for each user, each field is a part of its own.</p> <p>That way, you would have a meta-Item which consists solely of an Id that the parts can refer to. This holds together the parts. Then, you would map a user not to the Item but to the parts and reconstruct the item view from the common Id of the parts.</p>
0
2009-08-20T07:58:22Z
[ "python", "django", "django-models" ]
User-specific model in Django
1,304,608
<p>I have a model containing items, which has many different fields. There is another model which assigns a set of this field to each user using a m2m-relation.</p> <p>I want to achieve, that in the end, every user has access to a defined set of fields of the item model, and he only sees these field in views, he can only edit these field etc. Is there any generic way to set this up?</p>
0
2009-08-20T07:50:34Z
1,304,676
<p>A second approach would be to not include the filtering in the model layer. I. e., you leave the mapping on the model layer as it is and retrieve the full set of item fields for each user. Then you pass the items through a filter that implements the rules.</p> <p>Which approach is better for you depends on how you want to filter. If it's fixed types of users, I would probably implement a rules-based post-processor, if it's very dynamic, I would suggest the approach from my <a href="http://stackoverflow.com/questions/1304608/user-specific-model-in-django/1304634#1304634">earlier answer</a>. Another reason to put the filtering rules in the model would be if you want to reuse the model in applications that couldn't reuse your filter engine (for example if you have applications in different languages sharing the same database).</p>
0
2009-08-20T08:09:16Z
[ "python", "django", "django-models" ]
how to install new packages with python 3.1.1?
1,304,638
<p>I've tried to install pip on windows, but it's not working:</p> <p>giving me ImportError: No module named pkg_resources</p> <p>easy_install doesn't have version 3.1 or so, just 2.5, and should be replaced by pim.</p> <p>is there easy way to install it on windows? </p>
1
2009-08-20T07:59:36Z
1,304,651
<p>setuptools doesn't quite work on Python 3.1 yet. Try installing packages with regular distutils, or use binary packages (.exe, .msi) provided by the package author.</p>
0
2009-08-20T08:03:25Z
[ "python" ]
Difference between accessing an instance attribute and a class attribute
1,304,868
<p>I have a Python class</p> <pre><code>class pytest: i = 34 def func(self): return "hello world" </code></pre> <p>When I access <code>pytest.i</code>, I get 34. I can also do this another way:</p> <pre><code>a = pytest() a.i </code></pre> <p>This gives 34 as well.</p> <p>If I try to access the (non-existing) <code>pytest.j</code>, I get</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; pytest.j AttributeError: class pytest has no attribute 'j' </code></pre> <p>while when I try <code>a.j</code>, the error is</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#8&gt;", line 1, in &lt;module&gt; a.j AttributeError: pytest instance has no attribute 'j' </code></pre> <p>So my question is: What exactly happens in the two cases and what is the difference?</p>
2
2009-08-20T08:48:48Z
1,304,923
<p>No, these are two different things.</p> <p>In Python, everything is an object. Classes are objects, functions are objects and instances are objects. Since everything is an object, everything behaves in a similar way. In your case, you create a class instance (== an object with the type "Class") with the name "pytest". That object has two attributes: <code>i</code> and <code>fuc</code>. <code>i</code> is an instance of "Integer" or "Number", <code>fuc</code> is an instance of "Function".</p> <p>When you use "pytest.j", you tell python "look up the object <code>pytest</code> and when you have it, look up <code>i</code>". "pytest" is a class instance but that doesn't matter.</p> <p>When you create an instance of "pytest" (== an object with the type "pytest"), then you have an object which has "defaults". In your case, <code>a</code> is an instance of <code>pytest</code> which means that anything that can't be found in <code>a</code> will be searched in <code>pytest</code>, next.</p> <p>So <code>a.j</code> means: "Look in <code>a</code>. When it's not there, also look in <code>pytest</code>". But <code>j</code> doesn't exist and Python now has to give you a meaningful error message. It could say "class pytest has no attribute 'j'". This would be correct but meaningless: You would have to figure out yourself that you tried to access <code>j</code> via <code>a</code>. It would be confusing. Guido won't have that.</p> <p>Therefore, python uses a different error message. Since it does not always have the name of the instance (<code>a</code>), the designers decided to use the type instead, so you get "pytest instance...".</p>
6
2009-08-20T09:01:01Z
[ "python", "class", "instance" ]
Difference between accessing an instance attribute and a class attribute
1,304,868
<p>I have a Python class</p> <pre><code>class pytest: i = 34 def func(self): return "hello world" </code></pre> <p>When I access <code>pytest.i</code>, I get 34. I can also do this another way:</p> <pre><code>a = pytest() a.i </code></pre> <p>This gives 34 as well.</p> <p>If I try to access the (non-existing) <code>pytest.j</code>, I get</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; pytest.j AttributeError: class pytest has no attribute 'j' </code></pre> <p>while when I try <code>a.j</code>, the error is</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#8&gt;", line 1, in &lt;module&gt; a.j AttributeError: pytest instance has no attribute 'j' </code></pre> <p>So my question is: What exactly happens in the two cases and what is the difference?</p>
2
2009-08-20T08:48:48Z
1,306,560
<p>To summarize, there are two types of variables associated with classes and objects: class variables and instance variables. Class variables are associated with classes, but instance variables are associated with objects. Here's an example:</p> <pre><code>class TestClass: classVar = 0 def __init__(self): self.instanceVar = 0 </code></pre> <p>classVar is a class variable associated with the class TestClass. instanceVar is an instance variable associated with objects of the type TestClass.</p> <pre><code>print(TestClass.classVar) # prints 0 instance1 = TestClass() # creates new instance of TestClass instance2 = TestClass() # creates another new instance of TestClass </code></pre> <p>instance1 and instance2 share classVar because they're both objects of the type TestClass. </p> <pre><code>print(instance1.classVar) # prints 0 TestClass.classVar = 1 print(instance1.classVar) # prints 1 print(instance2.classVar) # prints 1 </code></pre> <p>However, they both have copies of instanceVar because it is an instance variable associated with individual instances, not the class.</p> <pre><code>print(instance1.instanceVar) # prints 0 print(TestClass.instanceVar) # error! instanceVar is not a class variable instance1.instanceVar = 1 print(instance1.instanceVar) # prints 1 print(instance2.instanceVar) # prints 0 </code></pre> <p>As Aaron said, if you try to access an instance variable, Python first checks the instance variables of that object, then the class variables of the object's type. Class variables function as default values for instance variables.</p>
0
2009-08-20T14:25:21Z
[ "python", "class", "instance" ]
Python japanese module is not found
1,305,042
<p>I run following python script.</p> <p><a href="http://www.halb-katze.jp/pygt/src/pygame2exe.py" rel="nofollow">pygame2exe.py</a></p> <pre><code>ImportError: No module named japanese </code></pre> <p>What's wrong?</p> <p>Do not you know solutions? </p>
0
2009-08-20T09:35:11Z
1,305,197
<p>The script makes use of japanese encoding</p> <pre><code># -*- coding: sjis -*- [...] args.append('japanese,encodings'); </code></pre> <p>It's a shame cause it could use UTF-8 that works out of the box. </p> <p>You can't run this script unless you install the japanese module. I can't find any reference of it on the web, and I can read in the code :</p> <pre><code># make standalone, needs at least pygame-1.5.3 and py2exe-0.3.1 # fixed for py2exe-0.6.x by RyoN3 at 03/15/2006 </code></pre> <p>If you haven't installed the last version of pygame and py2exe, I would start by that since they may embed the module you need.</p>
1
2009-08-20T10:17:29Z
[ "python", "pygame" ]
Python japanese module is not found
1,305,042
<p>I run following python script.</p> <p><a href="http://www.halb-katze.jp/pygt/src/pygame2exe.py" rel="nofollow">pygame2exe.py</a></p> <pre><code>ImportError: No module named japanese </code></pre> <p>What's wrong?</p> <p>Do not you know solutions? </p>
0
2009-08-20T09:35:11Z
1,305,707
<p>To add to e-satis' explanation, the "japanese" module is <a href="http://www.python.jp/Zope/download/JapaneseCodecs" rel="nofollow">provided by the Japan PUG</a>, but I don't think you've actually needed it since around Python 2.2. I believe that all the Japanese codecs are included in a standard Python install these days. I certainly don't use this module, and I handle SJIS in my programs just fine.</p> <p>So I think you could just get rid if the forced import, and do fine. That is, delete these lines:</p> <pre><code>args.append('-p') args.append('japanese,encodings') # JapaneseCodecを強制的に含める </code></pre> <p>Since you don't have the "japanese" module on your system, if the program runs OK on your system, then the frozen version should be OK without this module.</p> <p>However, I would recommend using Unicode throughout instead of byte strings, and if you insist on byte strings, I'd at least put them in UTF-8.</p>
0
2009-08-20T12:04:14Z
[ "python", "pygame" ]
Python socket error occured
1,305,050
<p>I wrote this code.</p> <pre><code>import socket host = 'localhost' port = 3794 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) while 1: print 'Type message you want to send...' msg = raw_input() if msg == '': s.close() break s.sendall(msg) </code></pre> <p>and next execute this code.</p> <pre><code>Traceback (most recent call last): File "socket.py", line 11, in ? s.bind((host, port)) File "&lt;string&gt;", line 1, in bind socket.error: (99, 'Cannot assign requested address') </code></pre> <p>What's wrong?</p> <p>Do you know solutions?</p>
4
2009-08-20T09:36:41Z
1,305,381
<p>This means that you already have a socket bound to 3794 port.</p> <p>It may be another application or it means that port didn't got released yet after the previous run of your own script (it happens, if script terminated improperly).</p> <p>Simply try to use another port number - I believe everything will work fine.</p>
8
2009-08-20T10:54:41Z
[ "python", "sockets" ]
Python socket error occured
1,305,050
<p>I wrote this code.</p> <pre><code>import socket host = 'localhost' port = 3794 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) while 1: print 'Type message you want to send...' msg = raw_input() if msg == '': s.close() break s.sendall(msg) </code></pre> <p>and next execute this code.</p> <pre><code>Traceback (most recent call last): File "socket.py", line 11, in ? s.bind((host, port)) File "&lt;string&gt;", line 1, in bind socket.error: (99, 'Cannot assign requested address') </code></pre> <p>What's wrong?</p> <p>Do you know solutions?</p>
4
2009-08-20T09:36:41Z
6,222,123
<p>I had this same problem and it was caused by trying to listen on the wrong host. When I changed it to an IP that was actually associated with the machine the code was running on (localhost), the problem went away.</p>
3
2011-06-03T01:31:19Z
[ "python", "sockets" ]
Python socket error occured
1,305,050
<p>I wrote this code.</p> <pre><code>import socket host = 'localhost' port = 3794 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) while 1: print 'Type message you want to send...' msg = raw_input() if msg == '': s.close() break s.sendall(msg) </code></pre> <p>and next execute this code.</p> <pre><code>Traceback (most recent call last): File "socket.py", line 11, in ? s.bind((host, port)) File "&lt;string&gt;", line 1, in bind socket.error: (99, 'Cannot assign requested address') </code></pre> <p>What's wrong?</p> <p>Do you know solutions?</p>
4
2009-08-20T09:36:41Z
15,639,675
<p>This error comes up mostly due to the the port being already used by another application/service . Choose a port number above the range of registered ports , i.e 49151</p>
0
2013-03-26T14:32:43Z
[ "python", "sockets" ]
Django - Edit data in db
1,305,182
<p>I have a question regarding editing/saving data in database using Django.</p> <p>I have template that show data from database. And after each record i have link that link you to edit page. But now is the question how to edit data in db without using admin panel?</p> <p>I run thought tutorial in djangobook but i didn't see how to achieve this without using the shell</p> <p>Thanks in advice! </p>
0
2009-08-20T10:13:54Z
1,305,199
<p>Have a look at the <a href="http://docs.djangoproject.com/en/dev/topics/forms/" rel="nofollow">"Working with forms" section</a> in the Django documentation.</p>
1
2009-08-20T10:18:06Z
[ "python", "django" ]
Django - Edit data in db
1,305,182
<p>I have a question regarding editing/saving data in database using Django.</p> <p>I have template that show data from database. And after each record i have link that link you to edit page. But now is the question how to edit data in db without using admin panel?</p> <p>I run thought tutorial in djangobook but i didn't see how to achieve this without using the shell</p> <p>Thanks in advice! </p>
0
2009-08-20T10:13:54Z
37,114,696
<p>You can use Django authenticaion system to create users and giving them permissions to modify the data.</p>
0
2016-05-09T11:31:38Z
[ "python", "django" ]
python 3.1 with pydev
1,305,218
<p>I am now moving to eclipse for my python development. I have pydev installed but it is showing grammar support up to python version 3.0. My question is can I use python 3.1 with 3.0 grammar? Has the grammar changed from version 3.0 to 3.1?</p> <p>I am using eclipse 3.4.2 and pydev 1.4.7</p>
5
2009-08-20T10:22:37Z
1,305,253
<p>grammar hasn't changed, some <a href="http://docs.python.org/3.1/whatsnew/3.1.html" rel="nofollow">modules have</a>.</p>
10
2009-08-20T10:31:19Z
[ "python", "eclipse", "python-3.x", "pydev" ]
Python - If statement
1,305,302
<p>I keep getting invalid syntax with the below:</p> <pre><code>if (row[0] == year) and (row[1] == month) and (row[2] == day and (row[3] == hour) and (row[4] == minute): print "hello" else: print "hello2" </code></pre> <p>Any ideas?</p>
-1
2009-08-20T10:42:13Z
1,305,314
<p>A closing paren is missing at <code>row[2] == day</code>.</p>
13
2009-08-20T10:43:52Z
[ "python", "syntax-error" ]
Python - If statement
1,305,302
<p>I keep getting invalid syntax with the below:</p> <pre><code>if (row[0] == year) and (row[1] == month) and (row[2] == day and (row[3] == hour) and (row[4] == minute): print "hello" else: print "hello2" </code></pre> <p>Any ideas?</p>
-1
2009-08-20T10:42:13Z
1,305,323
<p>You're missing a closing parenthesis:</p> <pre><code>if (row[0] == year) and (row[1] == month) and (row[2] == day and (row[3] == hour) and (row[4] == minute): ^^^ </code></pre> <p>Also, beware indentation.</p>
11
2009-08-20T10:44:41Z
[ "python", "syntax-error" ]
Python - If statement
1,305,302
<p>I keep getting invalid syntax with the below:</p> <pre><code>if (row[0] == year) and (row[1] == month) and (row[2] == day and (row[3] == hour) and (row[4] == minute): print "hello" else: print "hello2" </code></pre> <p>Any ideas?</p>
-1
2009-08-20T10:42:13Z
1,305,369
<p>Try:</p> <pre><code>if row[0:5] == [year, month, day, hour, minute]: </code></pre> <p>That fixes your error and makes the whole thing much more readable.</p>
1
2009-08-20T10:52:58Z
[ "python", "syntax-error" ]
Python - If statement
1,305,302
<p>I keep getting invalid syntax with the below:</p> <pre><code>if (row[0] == year) and (row[1] == month) and (row[2] == day and (row[3] == hour) and (row[4] == minute): print "hello" else: print "hello2" </code></pre> <p>Any ideas?</p>
-1
2009-08-20T10:42:13Z
1,305,377
<p>If "row" is a list, you can do this instead (for clarity):</p> <pre><code>if row[:5] == [year, month, day, hour, minute]: </code></pre> <p>..or if row is a tuple:</p> <pre><code>if row[:5] == (year, month, day, hour, minute): </code></pre>
16
2009-08-20T10:53:38Z
[ "python", "syntax-error" ]
Python - If statement
1,305,302
<p>I keep getting invalid syntax with the below:</p> <pre><code>if (row[0] == year) and (row[1] == month) and (row[2] == day and (row[3] == hour) and (row[4] == minute): print "hello" else: print "hello2" </code></pre> <p>Any ideas?</p>
-1
2009-08-20T10:42:13Z
1,305,543
<p>Add a colon after "hour)" along with the aforementioned ")"</p>
0
2009-08-20T11:30:52Z
[ "python", "syntax-error" ]
Python - If statement
1,305,302
<p>I keep getting invalid syntax with the below:</p> <pre><code>if (row[0] == year) and (row[1] == month) and (row[2] == day and (row[3] == hour) and (row[4] == minute): print "hello" else: print "hello2" </code></pre> <p>Any ideas?</p>
-1
2009-08-20T10:42:13Z
1,306,343
<p>You have 5 superfluous left parentheses but only 4 superfluous right parentheses. Consider losing ALL the parentheses!</p>
2
2009-08-20T13:51:16Z
[ "python", "syntax-error" ]
How to delete entries in a dictionary with a given flag in python?
1,305,437
<p>I have a dictionary, lets call it <code>myDict</code>, in Python that contains a set of similar dictionaries which all have the entry "<code>turned_on : True</code>" or "<code>turned_on : False</code>". I want to remove all the entries in <code>myDict</code> that are off, e.g. where "<code>turned_on : False</code>". In Ruby I would do something like this:</p> <pre><code>myDict.delete_if { |id,dict| not dict[:turned_on] } </code></pre> <p>How should I do this in Python?</p>
1
2009-08-20T11:07:59Z
1,305,445
<p>Straight-forward way:</p> <pre><code>def delete_if_not(predicate_key, some_dict): for key, subdict in some_dict.items(): if not subdict.get(predicate_key, True): del some_dict[key] </code></pre> <p>Testing:</p> <pre><code>mydict = { 'test1': { 'turned_on': True, 'other_data': 'foo', }, 'test2': { 'turned_on': False, 'other_data': 'bar', }, } delete_if_not('turned_on', mydict) print mydict </code></pre> <p>The other answers on this page so far create another dict. They don't delete the keys in your actual dict.</p>
5
2009-08-20T11:11:07Z
[ "python", "ruby", "dictionary" ]
How to delete entries in a dictionary with a given flag in python?
1,305,437
<p>I have a dictionary, lets call it <code>myDict</code>, in Python that contains a set of similar dictionaries which all have the entry "<code>turned_on : True</code>" or "<code>turned_on : False</code>". I want to remove all the entries in <code>myDict</code> that are off, e.g. where "<code>turned_on : False</code>". In Ruby I would do something like this:</p> <pre><code>myDict.delete_if { |id,dict| not dict[:turned_on] } </code></pre> <p>How should I do this in Python?</p>
1
2009-08-20T11:07:59Z
1,305,446
<p>It's not clear what you want, but my guess is:</p> <pre><code>myDict = {i: j for i, j in myDict.items() if j['turned_on']} </code></pre> <p>or for older version of python:</p> <pre><code>myDict = dict((i, j) for i, j in myDict.iteritems() if j['turned_on']) </code></pre>
3
2009-08-20T11:11:10Z
[ "python", "ruby", "dictionary" ]
How to delete entries in a dictionary with a given flag in python?
1,305,437
<p>I have a dictionary, lets call it <code>myDict</code>, in Python that contains a set of similar dictionaries which all have the entry "<code>turned_on : True</code>" or "<code>turned_on : False</code>". I want to remove all the entries in <code>myDict</code> that are off, e.g. where "<code>turned_on : False</code>". In Ruby I would do something like this:</p> <pre><code>myDict.delete_if { |id,dict| not dict[:turned_on] } </code></pre> <p>How should I do this in Python?</p>
1
2009-08-20T11:07:59Z
1,305,462
<p>You mean like this?</p> <pre><code>myDict = {"id1" : {"turned_on": True}, "id2" : {"turned_on": False}} result = dict((a, b) for a, b in myDict.items() if b["turned_on"]) </code></pre> <p>output:</p> <pre><code>{'id1': {'turned_on': True}} </code></pre>
7
2009-08-20T11:14:11Z
[ "python", "ruby", "dictionary" ]
How to delete entries in a dictionary with a given flag in python?
1,305,437
<p>I have a dictionary, lets call it <code>myDict</code>, in Python that contains a set of similar dictionaries which all have the entry "<code>turned_on : True</code>" or "<code>turned_on : False</code>". I want to remove all the entries in <code>myDict</code> that are off, e.g. where "<code>turned_on : False</code>". In Ruby I would do something like this:</p> <pre><code>myDict.delete_if { |id,dict| not dict[:turned_on] } </code></pre> <p>How should I do this in Python?</p>
1
2009-08-20T11:07:59Z
1,305,476
<pre><code>d = { 'id1':{'turned_on':True}, 'id2':{'turned_on':False}} dict((i,j) for i, j in d.items() if not j['turned_on']) </code></pre>
1
2009-08-20T11:17:08Z
[ "python", "ruby", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
1,305,547
<pre><code>x = type('new_dict', (object,), d) </code></pre> <p>then add recursion to this and you're done.</p> <p><strong>edit</strong> this is how I'd implement it:</p> <pre><code>&gt;&gt;&gt; d {'a': 1, 'b': {'c': 2}, 'd': ['hi', {'foo': 'bar'}]} &gt;&gt;&gt; def obj_dic(d): top = type('new', (object,), d) seqs = tuple, list, set, frozenset for i, j in d.items(): if isinstance(j, dict): setattr(top, i, obj_dic(j)) elif isinstance(j, seqs): setattr(top, i, type(j)(obj_dic(sj) if isinstance(sj, dict) else sj for sj in j)) else: setattr(top, i, j) return top &gt;&gt;&gt; x = obj_dic(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo 'bar' </code></pre>
47
2009-08-20T11:31:34Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
1,305,548
<p><code>x.__dict__.update(d)</code> should do fine.</p>
7
2009-08-20T11:31:59Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
1,305,561
<p>This should get your started:</p> <pre><code>class dict2obj(object): def __init__(self, d): self.__dict__['d'] = d def __getattr__(self, key): value = self.__dict__['d'][key] if type(value) == type({}): return dict2obj(value) return value d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} x = dict2obj(d) print x.a print x.b.c print x.d[1].foo </code></pre> <p>It doesn't work for lists, yet. You'll have to wrap the lists in a UserList and overload <code>__getitem__</code> to wrap dicts.</p>
6
2009-08-20T11:34:42Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
1,305,643
<pre><code>&gt;&gt;&gt; def dict2obj(d): if isinstance(d, list): d = [dict2obj(x) for x in d] if not isinstance(d, dict): return d class C(object): pass o = C() for k in d: o.__dict__[k] = dict2obj(d[k]) return o &gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} &gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo 'bar' </code></pre>
10
2009-08-20T11:50:56Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
1,305,651
<p>Let me explain a solution I <strong>almost</strong> used some time ago. But first, the reason I did not is illustrated by the fact that the following code:</p> <pre><code>d = {'from': 1} x = dict2obj(d) print x.from </code></pre> <p>gives this error:</p> <pre><code> File "test.py", line 20 print x.from == 1 ^ SyntaxError: invalid syntax </code></pre> <p>Because "from" is a Python keyword there are certain dictionary keys you cannot allow.</p> <p><hr /></p> <p>Now my solution allows access to the dictionary items by using their names directly. But it also allows you to use "dictionary semantics". Here is the code with example usage:</p> <pre><code>class dict2obj(dict): def __init__(self, dict_): super(dict2obj, self).__init__(dict_) for key in self: item = self[key] if isinstance(item, list): for idx, it in enumerate(item): if isinstance(it, dict): item[idx] = dict2obj(it) elif isinstance(item, dict): self[key] = dict2obj(item) def __getattr__(self, key): return self[key] d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} x = dict2obj(d) assert x.a == x['a'] == 1 assert x.b.c == x['b']['c'] == 2 assert x.d[1].foo == x['d'][1]['foo'] == "bar" </code></pre>
2
2009-08-20T11:52:34Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
1,305,663
<p><strong>Update:</strong> In Python 2.6 and onwards, consider whether the <a href="https://docs.python.org/2/library/collections.html#collections.namedtuple"><code>namedtuple</code></a> data structure suits your needs:</p> <pre><code>&gt;&gt;&gt; from collections import namedtuple &gt;&gt;&gt; MyStruct = namedtuple('MyStruct', 'a b d') &gt;&gt;&gt; s = MyStruct(a=1, b={'c': 2}, d=['hi']) &gt;&gt;&gt; s MyStruct(a=1, b={'c': 2}, d=['hi']) &gt;&gt;&gt; s.a 1 &gt;&gt;&gt; s.b {'c': 2} &gt;&gt;&gt; s.c &gt;&gt;&gt; s.d ['hi'] </code></pre> <p>The alternative (original answer contents) is:</p> <pre><code>class Struct: def __init__(self, **entries): self.__dict__.update(entries) </code></pre> <p>Then, you can use:</p> <pre><code>&gt;&gt;&gt; args = {'a': 1, 'b': 2} &gt;&gt;&gt; s = Struct(**args) &gt;&gt;&gt; s &lt;__main__.Struct instance at 0x01D6A738&gt; &gt;&gt;&gt; s.a 1 &gt;&gt;&gt; s.b 2 </code></pre>
495
2009-08-20T11:55:39Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
1,305,682
<pre><code>class obj(object): def __init__(self, d): for a, b in d.items(): if isinstance(b, (list, tuple)): setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b]) else: setattr(self, a, obj(b) if isinstance(b, dict) else b) &gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} &gt;&gt;&gt; x = obj(d) &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo 'bar' </code></pre>
67
2009-08-20T11:58:36Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
1,306,221
<p>Here's another implementation:</p> <pre><code>class DictObj(object): def __init__(self, d): self.__dict__ = d def dict_to_obj(d): if isinstance(d, (list, tuple)): return map(dict_to_obj, d) elif not isinstance(d, dict): return d return DictObj(dict((k, dict_to_obj(v)) for (k,v) in d.iteritems())) </code></pre> <p>[Edit] Missed bit about also handling dicts within lists, not just other dicts. Added fix.</p>
2
2009-08-20T13:33:26Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
1,306,518
<p>Here is another way to implement SilentGhost's original suggestion:</p> <pre><code>def dict2obj(d): if isinstance(d, dict): n = {} for item in d: if isinstance(d[item], dict): n[item] = dict2obj(d[item]) elif isinstance(d[item], (list, tuple)): n[item] = [dict2obj(elem) for elem in d[item]] else: n[item] = d[item] return type('obj_from_dict', (object,), n) else: return d </code></pre>
2
2009-08-20T14:18:43Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
1,334,816
<p>Building off my answer to "<a href="http://stackoverflow.com/questions/1325673/python-how-to-add-property-to-a-class-dynamically/1333275#1333275" title="python-how-to-add-property-to-a-class-dynamically">python: How to add property to a class dynamically?</a>":</p> <pre><code>class data(object): def __init__(self,*args,**argd): self.__dict__.update(dict(*args,**argd)) def makedata(d): d2 = {} for n in d: d2[n] = trydata(d[n]) return data(d2) def trydata(o): if isinstance(o,dict): return makedata(o) elif isinstance(o,list): return [trydata(i) for i in o] else: return o </code></pre> <p>You call <code>makedata</code> on the dictionary you want converted, or maybe <code>trydata</code> depending on what you expect as input, and it spits out a data object.</p> <p>Notes:</p> <ul> <li>You can add elifs to <code>trydata</code> if you need more functionality.</li> <li>Obviously this won't work if you want <code>x.a = {}</code> or similar.</li> <li>If you want a readonly version, use the class data from <a href="http://stackoverflow.com/questions/1325673/python-how-to-add-property-to-a-class-dynamically/1333275#1333275" title="python-how-to-add-property-to-a-class-dynamically">the original answer</a>.</li> </ul>
1
2009-08-26T13:48:07Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
5,771,818
<p>I stumbled upon the case I needed to recursively convert a list of dicts to list of objects, so based on Roberto's snippet here what did the work for me:</p> <pre><code>def dict2obj(d): if isinstance(d, dict): n = {} for item in d: if isinstance(d[item], dict): n[item] = dict2obj(d[item]) elif isinstance(d[item], (list, tuple)): n[item] = [dict2obj(elem) for elem in d[item]] else: n[item] = d[item] return type('obj_from_dict', (object,), n) elif isinstance(d, (list, tuple,)): l = [] for item in d: l.append(dict2obj(item)) return l else: return d </code></pre> <p>Note that any tuple will be converted to its list equivalent, for obvious reasons. </p> <p>Hope this helps someone as much as all your answers did for me, guys.</p>
3
2011-04-24T16:41:54Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
6,573,827
<p>Taking what I feel are the best aspects of the previous examples, here's what I came up with:</p> <pre><code>class Struct: '''The recursive class for building and representing objects with.''' def __init__(self, obj): for k, v in obj.iteritems(): if isinstance(v, dict): setattr(self, k, Struct(v)) else: setattr(self, k, v) def __getitem__(self, val): return self.__dict__[val] def __repr__(self): return '{%s}' % str(', '.join('%s : %s' % (k, repr(v)) for (k, v) in self.__dict__.iteritems())) </code></pre>
27
2011-07-04T16:12:02Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
6,993,694
<pre><code>class Struct(object): """Comment removed""" def __init__(self, data): for name, value in data.iteritems(): setattr(self, name, self._wrap(value)) def _wrap(self, value): if isinstance(value, (tuple, list, set, frozenset)): return type(value)([self._wrap(v) for v in value]) else: return Struct(value) if isinstance(value, dict) else value </code></pre> <p>Can be used with any sequence/dict/value structure of any depth.</p>
17
2011-08-09T08:58:27Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
9,413,295
<p>For anyone who happens to stumble upon this question nowadays. In Python 2.6+ there's a collection helper called <a href="http://docs.python.org/library/collections.html?highlight=collections#namedtuple-factory-function-for-tuples-with-named-fields"><code>namedtuple</code></a>, that can do this for you: </p> <pre><code>from collections import namedtuple d_named = namedtuple('Struct', d.keys())(*d.values()) In [7]: d_named Out[7]: Struct(a=1, b={'c': 2}, d=['hi', {'foo': 'bar'}]) In [8]: d_named.a Out[8]: 1 </code></pre>
33
2012-02-23T12:43:16Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
11,007,429
<p>Old Q&amp;A, but I get something more to talk. Seems no one talk about recursive dict. This is my code:</p> <pre><code>#!/usr/bin/env python class Object( dict ): def __init__( self, data = None ): super( Object, self ).__init__() if data: self.__update( data, {} ) def __update( self, data, did ): dataid = id(data) did[ dataid ] = self for k in data: dkid = id(data[k]) if did.has_key(dkid): self[k] = did[dkid] elif isinstance( data[k], Object ): self[k] = data[k] elif isinstance( data[k], dict ): obj = Object() obj.__update( data[k], did ) self[k] = obj obj = None else: self[k] = data[k] def __getattr__( self, key ): return self.get( key, None ) def __setattr__( self, key, value ): if isinstance(value,dict): self[key] = Object( value ) else: self[key] = value def update( self, *args ): for obj in args: for k in obj: if isinstance(obj[k],dict): self[k] = Object( obj[k] ) else: self[k] = obj[k] return self def merge( self, *args ): for obj in args: for k in obj: if self.has_key(k): if isinstance(self[k],list) and isinstance(obj[k],list): self[k] += obj[k] elif isinstance(self[k],list): self[k].append( obj[k] ) elif isinstance(obj[k],list): self[k] = [self[k]] + obj[k] elif isinstance(self[k],Object) and isinstance(obj[k],Object): self[k].merge( obj[k] ) elif isinstance(self[k],Object) and isinstance(obj[k],dict): self[k].merge( obj[k] ) else: self[k] = [ self[k], obj[k] ] else: if isinstance(obj[k],dict): self[k] = Object( obj[k] ) else: self[k] = obj[k] return self def test01(): class UObject( Object ): pass obj = Object({1:2}) d = {} d.update({ "a": 1, "b": { "c": 2, "d": [ 3, 4, 5 ], "e": [ [6,7], (8,9) ], "self": d, }, 1: 10, "1": 11, "obj": obj, }) x = UObject(d) assert x.a == x["a"] == 1 assert x.b.c == x["b"]["c"] == 2 assert x.b.d[0] == 3 assert x.b.d[1] == 4 assert x.b.e[0][0] == 6 assert x.b.e[1][0] == 8 assert x[1] == 10 assert x["1"] == 11 assert x[1] != x["1"] assert id(x) == id(x.b.self.b.self) == id(x.b.self) assert x.b.self.a == x.b.self.b.self.a == 1 x.x = 12 assert x.x == x["x"] == 12 x.y = {"a":13,"b":[14,15]} assert x.y.a == 13 assert x.y.b[0] == 14 def test02(): x = Object({ "a": { "b": 1, "c": [ 2, 3 ] }, 1: 6, 2: [ 8, 9 ], 3: 11, }) y = Object({ "a": { "b": 4, "c": [ 5 ] }, 1: 7, 2: 10, 3: [ 12 , 13 ], }) z = { 3: 14, 2: 15, "a": { "b": 16, "c": 17, } } x.merge( y, z ) assert 2 in x.a.c assert 3 in x.a.c assert 5 in x.a.c assert 1 in x.a.b assert 4 in x.a.b assert 8 in x[2] assert 9 in x[2] assert 10 in x[2] assert 11 in x[3] assert 12 in x[3] assert 13 in x[3] assert 14 in x[3] assert 15 in x[2] assert 16 in x.a.b assert 17 in x.a.c if __name__ == '__main__': test01() test02() </code></pre>
4
2012-06-13T02:23:07Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
11,091,977
<pre><code>class Struct(dict): def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(name) def __setattr__(self, name, value): self[name] = value def copy(self): return Struct(dict.copy(self)) </code></pre> <p>Usage:</p> <pre><code>points = Struct(x=1, y=2) # Changing points['x'] = 2 points.y = 1 # Accessing points['x'], points.x, points.get('x') # 2 2 2 points['y'], points.y, points.get('y') # 1 1 1 # Accessing inexistent keys/attrs points['z'] # KeyError: z points.z # AttributeError: z # Copying points_copy = points.copy() points.x = 2 points_copy.x # 1 </code></pre>
1
2012-06-18T22:26:05Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
11,961,837
<p>Wanted to upload my version of this little paradigm.</p> <pre><code>class Struct(dict): def __init__(self,data): for key, value in data.items(): if isinstance(value, dict): setattr(self, key, Struct(value)) else: setattr(self, key, type(value).__init__(value)) dict.__init__(self,data) </code></pre> <p>It preserves the attributes for the type that's imported into the class. My only concern would be overwriting methods from within the dictionary your parsing. But otherwise seems solid!</p>
3
2012-08-14T22:38:06Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
12,075,692
<p>I had some problems with <code>__getattr__</code> not being called so I constructed a new style class version:</p> <pre><code>class Struct(object): '''The recursive class for building and representing objects with.''' class NoneStruct(object): def __getattribute__(*args): return Struct.NoneStruct() def __eq__(self, obj): return obj == None def __init__(self, obj): for k, v in obj.iteritems(): if isinstance(v, dict): setattr(self, k, Struct(v)) else: setattr(self, k, v) def __getattribute__(*args): try: return object.__getattribute__(*args) except: return Struct.NoneStruct() def __repr__(self): return '{%s}' % str(', '.join('%s : %s' % (k, repr(v)) for (k, v) in self.__dict__.iteritems())) </code></pre> <p>This version also has the addition of <code>NoneStruct</code> that is returned when an attribute is called that is not set. This allows for None testing to see if an attribute is present. Very usefull when the exact dict input is not known (settings etc.).</p> <pre><code>bla = Struct({'a':{'b':1}}) print(bla.a.b) &gt;&gt; 1 print(bla.a.c == None) &gt;&gt; True </code></pre>
0
2012-08-22T14:44:29Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
14,208,842
<p>My dictionary is of this format:</p> <pre><code>addr_bk = { 'person': [ {'name': 'Andrew', 'id': 123, 'email': 'andrew@mailserver.com', 'phone': [{'type': 2, 'number': '633311122'}, {'type': 0, 'number': '97788665'}] }, {'name': 'Tom', 'id': 456, 'phone': [{'type': 0, 'number': '91122334'}]}, {'name': 'Jack', 'id': 7788, 'email': 'jack@gmail.com'} ] } </code></pre> <p>As can be seen, I have <strong>nested dictionaries</strong> and <strong>list of dicts</strong>. This is because the addr_bk was decoded from protocol buffer data that converted to a python dict using lwpb.codec. There are optional field (e.g. email => where key may be unavailable) and repeated field (e.g. phone => converted to list of dict).</p> <p>I tried all the above proposed solutions. Some doesn't handle the nested dictionaries well. Others cannot print the object details easily.</p> <p>Only the solution, dict2obj(dict) by Dawie Strauss, works best.</p> <p>I have enhanced it a little to handle when the key cannot be found:</p> <pre><code># Work the best, with nested dictionaries &amp; lists! :) # Able to print out all items. class dict2obj_new(dict): def __init__(self, dict_): super(dict2obj_new, self).__init__(dict_) for key in self: item = self[key] if isinstance(item, list): for idx, it in enumerate(item): if isinstance(it, dict): item[idx] = dict2obj_new(it) elif isinstance(item, dict): self[key] = dict2obj_new(item) def __getattr__(self, key): # Enhanced to handle key not found. if self.has_key(key): return self[key] else: return None </code></pre> <p>Then, I tested it with:</p> <pre><code># Testing... ab = dict2obj_new(addr_bk) for person in ab.person: print "Person ID:", person.id print " Name:", person.name # Check if optional field is available before printing. if person.email: print " E-mail address:", person.email # Check if optional field is available before printing. if person.phone: for phone_number in person.phone: if phone_number.type == codec.enums.PhoneType.MOBILE: print " Mobile phone #:", elif phone_number.type == codec.enums.PhoneType.HOME: print " Home phone #:", else: print " Work phone #:", print phone_number.number </code></pre>
0
2013-01-08T05:40:02Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
15,589,291
<p>If you want to access dict keys as an object (or as a dict for difficult keys), do it recursively, and also be able to update the original dict, you could do:</p> <pre><code>class Dictate(object): """Object view of a dict, updating the passed in dict when values are set or deleted. "Dictate" the contents of a dict...: """ def __init__(self, d): # since __setattr__ is overridden, self.__dict = d doesn't work object.__setattr__(self, '_Dictate__dict', d) # Dictionary-like access / updates def __getitem__(self, name): value = self.__dict[name] if isinstance(value, dict): # recursively view sub-dicts as objects value = Dictate(value) return value def __setitem__(self, name, value): self.__dict[name] = value def __delitem__(self, name): del self.__dict[name] # Object-like access / updates def __getattr__(self, name): return self[name] def __setattr__(self, name, value): self[name] = value def __delattr__(self, name): del self[name] def __repr__(self): return "%s(%r)" % (type(self).__name__, self.__dict) def __str__(self): return str(self.__dict) </code></pre> <p>Example usage:</p> <pre><code>d = {'a': 'b', 1: 2} dd = Dictate(d) assert dd.a == 'b' # Access like an object assert dd[1] == 2 # Access like a dict # Updates affect d dd.c = 'd' assert d['c'] == 'd' del dd.a del dd[1] # Inner dicts are mapped dd.e = {} dd.e.f = 'g' assert dd['e'].f == 'g' assert d == {'c': 'd', 'e': {'f': 'g'}} </code></pre>
10
2013-03-23T16:41:48Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
15,882,327
<p>If your dict is coming from <code>json.loads()</code>, you can turn it into an object instead (rather than a dict) in one line:</p> <pre><code>import json from collections import namedtuple json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values())) </code></pre> <p>See also <a href="http://stackoverflow.com/questions/6578986/how-to-convert-json-data-into-a-python-object/15882054#15882054">How to convert JSON data into a Python object</a>.</p>
15
2013-04-08T14:53:46Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
16,372,505
<p>How about this:</p> <pre><code>from functools import partial d2o=partial(type, "d2o", ()) </code></pre> <p>This can then be used like this:</p> <pre><code>&gt;&gt;&gt; o=d2o({"a" : 5, "b" : 3}) &gt;&gt;&gt; print o.a 5 &gt;&gt;&gt; print o.b 3 </code></pre>
1
2013-05-04T08:58:39Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
18,357,162
<pre><code>from mock import Mock d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} my_data = Mock(**d) # We got # my_data.a == 1 </code></pre>
2
2013-08-21T12:15:22Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
19,218,587
<p>I think a dict consists of number, string and dict is enough most time. So I ignore the situation that tuples, lists and other types not appearing in the final dimension of a dict. </p> <p>Considering inheritance, combined with recursion, it solves the print problem conveniently and also provides two ways to query a data,one way to edit a data.</p> <p>See the example below, a dict that describes some information about students:</p> <pre><code>group=["class1","class2","class3","class4",] rank=["rank1","rank2","rank3","rank4","rank5",] data=["name","sex","height","weight","score"] #build a dict based on the lists above student_dic=dict([(g,dict([(r,dict([(d,'') for d in data])) for r in rank ]))for g in group]) #this is the solution class dic2class(dict): def __init__(self, dic): for key,val in dic.items(): self.__dict__[key]=self[key]=dic2class(val) if isinstance(val,dict) else val student_class=dic2class(student_dic) #one way to edit: student_class.class1.rank1['sex']='male' student_class.class1.rank1['name']='Nan Xiang' #two ways to query: print student_class.class1.rank1 print student_class.class1['rank1'] print '-'*50 for rank in student_class.class1: print getattr(student_class.class1,rank) </code></pre> <p>Results:</p> <pre><code>{'score': '', 'sex': 'male', 'name': 'Nan Xiang', 'weight': '', 'height': ''} {'score': '', 'sex': 'male', 'name': 'Nan Xiang', 'weight': '', 'height': ''} -------------------------------------------------- {'score': '', 'sex': '', 'name': '', 'weight': '', 'height': ''} {'score': '', 'sex': '', 'name': '', 'weight': '', 'height': ''} {'score': '', 'sex': 'male', 'name': 'Nan Xiang', 'weight': '', 'height': ''} {'score': '', 'sex': '', 'name': '', 'weight': '', 'height': ''} {'score': '', 'sex': '', 'name': '', 'weight': '', 'height': ''} </code></pre>
2
2013-10-07T06:47:22Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
19,511,263
<p>This is another, alternative, way to convert a list of dictionaries to an object:</p> <pre><code>def dict2object(in_dict): class Struct(object): def __init__(self, in_dict): for key, value in in_dict.items(): if isinstance(value, (list, tuple)): setattr( self, key, [Struct(sub_dict) if isinstance(sub_dict, dict) else sub_dict for sub_dict in value]) else: setattr( self, key, Struct(value) if isinstance(value, dict) else value) return [Struct(sub_dict) for sub_dict in in_dict] \ if isinstance(in_dict, list) else Struct(in_dict) </code></pre>
0
2013-10-22T07:06:47Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
24,852,544
<p>Surprisingly no one has mentioned <a href="https://github.com/dsc/bunch">Bunch</a>. This library is exclusively meant to provide attribute style access to dict objects and does exactly what the OP wants. A demonstration:</p> <pre><code>&gt;&gt;&gt; from bunch import bunchify &gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} &gt;&gt;&gt; x = bunchify(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo 'bar' </code></pre> <p>A Python 3 library is available at <a href="https://github.com/Infinidat/munch">https://github.com/Infinidat/munch</a> - Credit goes to @LordZ</p>
37
2014-07-20T16:30:31Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
26,805,003
<p>This little class never gives me any problem, just extend it and use the copy() method:</p> <pre><code> import simplejson as json class BlindCopy(object): def copy(self, json_str): dic = json.loads(json_str) for k, v in dic.iteritems(): if hasattr(self, k): setattr(self, k, v); </code></pre>
0
2014-11-07T15:51:26Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
31,569,634
<p>I ended up trying BOTH the <a href="https://github.com/bcj/AttrDict" rel="nofollow">AttrDict</a> and the <a href="https://github.com/dsc/bunch" rel="nofollow">Bunch</a> libraries and found them to be way to slow for my uses. After a friend and I looked into it, we found that the main method for writing these libraries results in the library aggressively recursing through a nested object and making copies of the dictionary object throughout. With this in mind, we made two key changes. 1) We made attributes lazy-loaded 2) instead of creating copies of a dictionary object, we create copies of a light-weight proxy object. This is the final implementation. The performance increase of using this code is incredible. When using AttrDict or Bunch, these two libraries alone consumed 1/2 and 1/3 respectively of my request time(what!?). This code reduced that time to almost nothing(somewhere in the range of 0.5ms). This of course depends on your needs, but if you are using this functionality quite a bit in your code, definitely go with something simple like this. </p> <pre><code>class DictProxy(object): def __init__(self, obj): self.obj = obj def __getitem__(self, key): return wrap(self.obj[key]) def __getattr__(self, key): try: return wrap(getattr(self.obj, key)) except AttributeError: try: return self[key] except KeyError: raise AttributeError(key) # you probably also want to proxy important list properties along like # items(), iteritems() and __len__ class ListProxy(object): def __init__(self, obj): self.obj = obj def __getitem__(self, key): return wrap(self.obj[key]) # you probably also want to proxy important list properties along like # __iter__ and __len__ def wrap(value): if isinstance(value, dict): return DictProxy(value) if isinstance(value, (tuple, list)): return ListProxy(value) return value </code></pre> <p>See the original implementation <a href="https://gist.github.com/mmerickel/ff4c6faf867d72c1f19c" rel="nofollow">here</a> by <a href="http://stackoverflow.com/users/704327/michael-merickel">http://stackoverflow.com/users/704327/michael-merickel</a>.</p> <p>The other thing to note, is that this implementation is pretty simple and doesn't implement all of the methods you might need. You'll need to write those as required on the DictProxy or ListProxy objects.</p>
3
2015-07-22T17:06:05Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
32,210,017
<p>Here is a nested-ready version with namedtuple:</p> <pre><code>from collections import namedtuple class Struct(object): def __new__(cls, data): if isinstance(data, dict): return namedtuple( 'Struct', data.iterkeys() )( *(Struct(val) for val in data.values()) ) elif isinstance(data, (tuple, list, set, frozenset)): return type(data)(Struct(_) for _ in data) else: return data </code></pre> <p>=></p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} &gt;&gt;&gt; s = Struct(d) &gt;&gt;&gt; s.d ['hi', Struct(foo='bar')] &gt;&gt;&gt; s.d[0] 'hi' &gt;&gt;&gt; s.d[1].foo 'bar' </code></pre>
0
2015-08-25T17:06:23Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
34,997,118
<p>You can leverage the <strong><code>json</code> module</strong> of the standard library with a <strong>custom object hook</strong>:</p> <pre><code>import json class obj(object): def __init__(self, dict_): self.__dict__.update(dict_) def dict2obj(d): return json.loads(json.dumps(d), object_hook=obj) </code></pre> <p>Example usage:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ['hi', {'foo': 'bar'}]} &gt;&gt;&gt; o = dict2obj(d) &gt;&gt;&gt; o.a 1 &gt;&gt;&gt; o.b.c 2 &gt;&gt;&gt; o.d[0] u'hi' &gt;&gt;&gt; o.d[1].foo u'bar' </code></pre> <p>And it is <strong>not strictly read-only</strong> as it is with <code>namedtuple</code>, i.e. you can change values – not structure:</p> <pre><code>&gt;&gt;&gt; o.b.c = 3 &gt;&gt;&gt; o.b.c 3 </code></pre>
0
2016-01-25T16:11:19Z
[ "python", "object", "dictionary" ]
Convert Python dict to object?
1,305,532
<p>I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} </code></pre> <p>Should be accessible in this way:</p> <pre><code>&gt;&gt;&gt; x = dict2obj(d) &gt;&gt;&gt; x.a 1 &gt;&gt;&gt; x.b.c 2 &gt;&gt;&gt; x.d[1].foo bar </code></pre> <p>I think, this is not possible without recursion, but what would be a nice way to get an objectstyle for dicts?</p> <p>Thank you in advance.</p>
322
2009-08-20T11:28:18Z
37,231,623
<p>What about just assigning your <code>dict</code> to the <code>__dict__</code> of an empty object?</p> <pre><code>class Object: """If your dict is "flat", this is a simple way to create an object from a dict &gt;&gt;&gt; obj = Object() &gt;&gt;&gt; obj.__dict__ = d &gt;&gt;&gt; d.a 1 """ pass </code></pre> <p>Of course this fails on your nested dict example unless you walk the dict recursively:</p> <pre><code># For a nested dict, you need to recursively update __dict__ def dict2obj(d): """Convert a dict to an object &gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} &gt;&gt;&gt; obj = dict2obj(d) &gt;&gt;&gt; obj.b.c 2 &gt;&gt;&gt; obj.d ["hi", {'foo': "bar"}] """ try: d = dict(d) except (TypeError, ValueError): return d obj = Object() for k, v in d.iteritems(): obj.__dict__[k] = dict2obj(v) return obj </code></pre> <p>And your example list element was probably meant to be a <code>Mapping</code>, a list of (key, value) pairs like this:</p> <pre><code>&gt;&gt;&gt; d = {'a': 1, 'b': {'c': 2}, 'd': [("hi", {'foo': "bar"})]} &gt;&gt;&gt; obj = dict2obj(d) &gt;&gt;&gt; obj.d.hi.foo "bar" </code></pre>
0
2016-05-14T20:40:46Z
[ "python", "object", "dictionary" ]
How to do Obj-C Categories in Python?
1,305,632
<p>Obj-C (which I have not used for a long time) has something called <a href="http://macdevelopertips.com/objective-c/objective-c-categories.html">categories</a> to extend classes. Declaring a category with new methods and compiling it into your program, all instances of the class suddenly have the new methods.</p> <p>Python has mixin possibilities, which I use, but mixins must be used from the bottom of the program: the class has to declare it itself.</p> <p>Foreseen category use-case: Say you have a big class hierarchy that describe different ways of interacting with data, declaring polymorphic ways to get at different attributes. Now a category can help the consumer of these describing classes by implementing a convenient interface to access these methods in one place. (A category method could for example, try two different methods and return the first defined (non-None) return value.)</p> <p>Any way to do this in Python?</p> <h1>Illustrative code</h1> <p>I <em>hope</em> this clarifies what I mean. The point is that the Category is like an aggregate interface, that the consumer of AppObj can change in <em>its</em> code.</p> <pre><code>class AppObj (object): """This is the top of a big hierarchy of subclasses that describe different data""" def get_resource_name(self): pass def get_resource_location(self): pass # dreaming up class decorator syntax @category(AppObj) class AppObjCategory (object): """this is a category on AppObj, not a subclass""" def get_resource(self): name = self.get_resource_name() if name: return library.load_resource_name(name) else: return library.load_resource(self.get_resource_location()) </code></pre>
8
2009-08-20T11:48:56Z
1,305,868
<p>Why not just add methods dynamically ?</p> <pre><code>&gt;&gt;&gt; class Foo(object): &gt;&gt;&gt; pass &gt;&gt;&gt; def newmethod(instance): &gt;&gt;&gt; print 'Called:', instance ... &gt;&gt;&gt; Foo.newmethod = newmethod &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; f.newmethod() Called: &lt;__main__.Foo object at 0xb7c54e0c&gt; </code></pre> <p>I know Objective-C and this looks just like categories. The only drawback is that you can't do that to built-in or extension types.</p>
8
2009-08-20T12:31:41Z
[ "python" ]
How to do Obj-C Categories in Python?
1,305,632
<p>Obj-C (which I have not used for a long time) has something called <a href="http://macdevelopertips.com/objective-c/objective-c-categories.html">categories</a> to extend classes. Declaring a category with new methods and compiling it into your program, all instances of the class suddenly have the new methods.</p> <p>Python has mixin possibilities, which I use, but mixins must be used from the bottom of the program: the class has to declare it itself.</p> <p>Foreseen category use-case: Say you have a big class hierarchy that describe different ways of interacting with data, declaring polymorphic ways to get at different attributes. Now a category can help the consumer of these describing classes by implementing a convenient interface to access these methods in one place. (A category method could for example, try two different methods and return the first defined (non-None) return value.)</p> <p>Any way to do this in Python?</p> <h1>Illustrative code</h1> <p>I <em>hope</em> this clarifies what I mean. The point is that the Category is like an aggregate interface, that the consumer of AppObj can change in <em>its</em> code.</p> <pre><code>class AppObj (object): """This is the top of a big hierarchy of subclasses that describe different data""" def get_resource_name(self): pass def get_resource_location(self): pass # dreaming up class decorator syntax @category(AppObj) class AppObjCategory (object): """this is a category on AppObj, not a subclass""" def get_resource(self): name = self.get_resource_name() if name: return library.load_resource_name(name) else: return library.load_resource(self.get_resource_location()) </code></pre>
8
2009-08-20T11:48:56Z
1,306,154
<p>I came up with this implementation of a class decorator. I'm using python2.5 so I haven't actually tested it with decorator syntax (which would be nice), and I'm not sure what it does is really correct. But it looks like this:</p> <p>pycategories.py</p> <pre><code>""" This module implements Obj-C-style categories for classes for Python Copyright 2009 Ulrik Sverdrup &lt;ulrik.sverdrup@gmail.com&gt; License: Public domain """ def Category(toclass, clobber=False): """Return a class decorator that implements the decorated class' methods as a Category on the class @toclass if @clobber is not allowed, AttributeError will be raised when the decorated class already contains the same attribute. """ def decorator(cls): skip = set(("__dict__", "__module__", "__weakref__", "__doc__")) for attr in cls.__dict__: if attr in toclass.__dict__: if attr in skip: continue if not clobber: raise AttributeError("Category cannot override %s" % attr) setattr(toclass, attr, cls.__dict__[attr]) return cls return decorator </code></pre>
2
2009-08-20T13:23:00Z
[ "python" ]
How to do Obj-C Categories in Python?
1,305,632
<p>Obj-C (which I have not used for a long time) has something called <a href="http://macdevelopertips.com/objective-c/objective-c-categories.html">categories</a> to extend classes. Declaring a category with new methods and compiling it into your program, all instances of the class suddenly have the new methods.</p> <p>Python has mixin possibilities, which I use, but mixins must be used from the bottom of the program: the class has to declare it itself.</p> <p>Foreseen category use-case: Say you have a big class hierarchy that describe different ways of interacting with data, declaring polymorphic ways to get at different attributes. Now a category can help the consumer of these describing classes by implementing a convenient interface to access these methods in one place. (A category method could for example, try two different methods and return the first defined (non-None) return value.)</p> <p>Any way to do this in Python?</p> <h1>Illustrative code</h1> <p>I <em>hope</em> this clarifies what I mean. The point is that the Category is like an aggregate interface, that the consumer of AppObj can change in <em>its</em> code.</p> <pre><code>class AppObj (object): """This is the top of a big hierarchy of subclasses that describe different data""" def get_resource_name(self): pass def get_resource_location(self): pass # dreaming up class decorator syntax @category(AppObj) class AppObjCategory (object): """this is a category on AppObj, not a subclass""" def get_resource(self): name = self.get_resource_name() if name: return library.load_resource_name(name) else: return library.load_resource(self.get_resource_location()) </code></pre>
8
2009-08-20T11:48:56Z
13,568,709
<p>Python's <code>setattr</code> function makes this easy.</p> <pre><code># categories.py class category(object): def __init__(self, mainModule, override = True): self.mainModule = mainModule self.override = override def __call__(self, function): if self.override or function.__name__ not in dir(self.mainModule): setattr(self.mainModule, function.__name__, function) </code></pre> <p>&nbsp;</p> <pre><code># categories_test.py import this from categories import category @category(this) def all(): print "all things are this" this.all() &gt;&gt;&gt; all things are this </code></pre>
2
2012-11-26T16:14:37Z
[ "python" ]
CheckedListBox used from Python(pywin32)
1,305,703
<p>Does anyone know how to get the list of items and check/uncheck items in a CheckedListBox from python? I've found <a href="http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html" rel="nofollow">this</a> to help me partly on the way. I think I've found the handle for the CheckedListBox(listed as a SysTreeView32 by WinGuiAuto.py).</p> <p>One usage will for my part be to create an autoinstaller that manages to uncheck all checkboxes that installs bloatware.</p>
0
2009-08-20T12:03:27Z
1,378,449
<p>By using <a href="http://sourceforge.net/projects/pywinauto/" rel="nofollow">pywinauto</a> I've managed to check items in a checkedlistbox by selecting them twice.</p> <pre><code>from pywinauto import application app = application.Application() app.Form1.CheckedListBox1.Select('item1') app.Form1.CheckedListBox1.Select('item1') </code></pre>
1
2009-09-04T10:33:57Z
[ "python", "windows", "message", "pywin32", "checkedlistbox" ]
Hook into and log "everything" in the windows message queue
1,305,847
<p>Has anyone got a working code example of how to connect to the windows message queue(post/sendMessage) and log all messages there? Preferably in Python. I'm interrested in this to easier be able to create test-scripts that emulates user input.</p>
3
2009-08-20T12:26:22Z
1,305,991
<p>Usually this is done with <a href="http://msdn.microsoft.com/en-us/library/ms644990%28VS.85%29.aspx" rel="nofollow">SetWindowsHookEx Function</a>. <br><br> In Python you probably must use 3rd party libraries, like <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">Python for Windows extensions</a>. <a href="http://docs.activestate.com/activepython/2.4/pywin32/PyCWnd%5F%5FHookMessage%5Fmeth.html" rel="nofollow">PyCWnd.HookMessage</a> and <a href="http://docs.activestate.com/activepython/2.4/pywin32/PyCWnd%5F%5FHookAllKeyStrokes%5Fmeth.html" rel="nofollow">PyCWnd.HookAllKeyStrokes</a> might be what you need.</p>
1
2009-08-20T12:50:47Z
[ "python", "windows", "message-queue" ]
Hook into and log "everything" in the windows message queue
1,305,847
<p>Has anyone got a working code example of how to connect to the windows message queue(post/sendMessage) and log all messages there? Preferably in Python. I'm interrested in this to easier be able to create test-scripts that emulates user input.</p>
3
2009-08-20T12:26:22Z
1,844,722
<p>There's actually a package that wraps the SetWindowsHookEx function, called <a href="http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=Main%5FPage" rel="nofollow">pyHook</a>. I've used it before to write a primitive key-logger (as an experiment in monitoring myself to assist with reporting work hours) and it worked fine for that.</p>
2
2009-12-04T03:51:39Z
[ "python", "windows", "message-queue" ]
Hook into and log "everything" in the windows message queue
1,305,847
<p>Has anyone got a working code example of how to connect to the windows message queue(post/sendMessage) and log all messages there? Preferably in Python. I'm interrested in this to easier be able to create test-scripts that emulates user input.</p>
3
2009-08-20T12:26:22Z
1,869,913
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/dd373640%28VS.85%29.aspx" rel="nofollow">SetWinEventHook</a> to catch most system windowing activity. The advantage from traditional hooks is that you can do it from your process, that is, you don't need to write a hooking DLL. Also, when the thread that called SetWinEventHook finishes, Windows releases the handler automatically. Having out of context hooking prevents you from crashing other applications, as a minimal error on an injected DLL will possibly do.</p>
1
2009-12-08T21:18:26Z
[ "python", "windows", "message-queue" ]
Extracting the To: header from an attachment of an email
1,306,026
<p>I am using python to open an email on the server (POP3). Each email has an attachment which is a forwarded email itself. </p> <p>I need to get the "To:" address out of the attachment. </p> <p>I am using python to try and help me learn the language and I'm not that good yet ! </p> <p>The code I have already is this</p> <pre><code>import poplib, email, mimetypes oPop = poplib.POP3( 'xx.xxx.xx.xx' ) oPop.user( 'abc@xxxxx.xxx' ) oPop.pass_( 'xxxxxx' ) (iNumMessages, iTotalSize ) = oPop.stat() for thisNum in range(1, iNumMessages + 1): (server_msg, body, octets) = oPop.retr(thisNum) sMail = "\n".join( body ) oMsg = email.message_from_string( sMail ) # now what ?? </code></pre> <p>I understand that I have the email as an instance of the email class but I'm not sure how to get to the attachment </p> <p>I know that using </p> <pre><code> sData = 'To' if sData in oMsg: print sData + "", oMsg[sData] </code></pre> <p>gets me the 'To:' header from the main message but how do I get that from the attachment ?</p> <p>I've tried </p> <pre><code>for part in oMsg.walk(): oAttach = part.get_payload(1) </code></pre> <p>But I'm not sure what to do with the oAttach object. I tried turning it into a string and then passing it to </p> <pre><code>oMsgAttach = email.message_from_string( oAttach ) </code></pre> <p>But that does nothing. I'm a little overwhelmed by the python docs and need some help. Thanks in advance.</p>
3
2009-08-20T12:56:40Z
1,307,262
<p>Without having an email in my inbox that is representative, it's difficult to work this one through (I've never used poplib). Having said that, some things that might help from my little bit of investigation:</p> <p>First of all, make lots of use of the command line interface to python and the <code>dir()</code> and <code>help()</code> functions: these can tell you lots about what's coming out. You can always insert <code>help(oAttach)</code>, <code>dir(oAttach)</code> and <code>print oAttach</code> in your code to get an idea of what's going on as it loops round. If you're typing it into the command line interface line-by-line, it's even easier in this case.</p> <p>What I <b>think</b> you need to do is to go through each attachment and work out what it is. For a conventional email attachment, it's probably base64 encoded, so something like this might help:</p> <pre><code>#!/usr/bin/python import poplib, email, mimetypes # Do everything you've done in the first code block of your question # ... # ... import base64 for part in oMsg.walk(): # I've removed the '1' from the argument as I think you always get the # the first entry (in my test, it was the third iteration that did it). # However, I could be wrong... oAttach = part.get_payload() # Decode the base64 encoded attachment oContent = b64decode(oAttach) # then maybe...? oMsgAttach = email.message_from_string(oContent) </code></pre> <p>Note that you probably need to check oAttach in each case to check that it looks like a message. When you've got your <code>sMail</code> variable, print it out to the screen. Then you can look for something like <code>Content-Transfer-Encoding: base64</code> in there, which will give you a clue to how the attachment is encoded.</p> <p>As I said, I've not used any of the poplib, email or mimetypes modules, so I'm not sure whether that'll help, but I thought it might point you in the right direction.</p>
1
2009-08-20T16:11:51Z
[ "python", "email", "mime", "pop3" ]