title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
How can I find the full path to a font from its display name on a Mac?
469
<p>I am using the Photoshop's javascript API to find the fonts in a given PSD.</p> <p>Given a font name returned by the API, I want to find the actual physical font file that that font name corresponds to on the disc.</p> <p>This is all happening in a python program running on OSX so I guess I'm looking for one of:</p> <ul> <li>Some Photoshop javascript</li> <li>A Python function</li> <li>An OSX API that I can call from python</li> </ul>
21
2008-08-02T15:11:16Z
497
<p>open up a terminal (Applications-&gt;Utilities-&gt;Terminal) and type this in:</p> <pre><code>locate InsertFontHere<br></code></pre> <p>This will spit out every file that has the name you want.</p> <p>Warning: there may be alot to wade through.</p>
4
2008-08-02T16:56:53Z
[ "python", "osx", "fonts", "photoshop" ]
How can I find the full path to a font from its display name on a Mac?
469
<p>I am using the Photoshop's javascript API to find the fonts in a given PSD.</p> <p>Given a font name returned by the API, I want to find the actual physical font file that that font name corresponds to on the disc.</p> <p>This is all happening in a python program running on OSX so I guess I'm looking for one of:</p> <ul> <li>Some Photoshop javascript</li> <li>A Python function</li> <li>An OSX API that I can call from python</li> </ul>
21
2008-08-02T15:11:16Z
518
<p>I haven't been able to find anything that does this directly. I think you'll have to iterate through the various font folders on the system: <code>/System/Library/Fonts</code>, <code>/Library/Fonts</code>, and there can probably be a user-level directory as well <code>~/Library/Fonts</code>.</p>
2
2008-08-02T17:42:28Z
[ "python", "osx", "fonts", "photoshop" ]
How can I find the full path to a font from its display name on a Mac?
469
<p>I am using the Photoshop's javascript API to find the fonts in a given PSD.</p> <p>Given a font name returned by the API, I want to find the actual physical font file that that font name corresponds to on the disc.</p> <p>This is all happening in a python program running on OSX so I guess I'm looking for one of:</p> <ul> <li>Some Photoshop javascript</li> <li>A Python function</li> <li>An OSX API that I can call from python</li> </ul>
21
2008-08-02T15:11:16Z
3,040
<p>Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef.</p> <p>Cocoa doesn't have any native support, at least as of 10.5, for getting the location of a font.</p>
12
2008-08-06T03:01:23Z
[ "python", "osx", "fonts", "photoshop" ]
How can I find the full path to a font from its display name on a Mac?
469
<p>I am using the Photoshop's javascript API to find the fonts in a given PSD.</p> <p>Given a font name returned by the API, I want to find the actual physical font file that that font name corresponds to on the disc.</p> <p>This is all happening in a python program running on OSX so I guess I'm looking for one of:</p> <ul> <li>Some Photoshop javascript</li> <li>A Python function</li> <li>An OSX API that I can call from python</li> </ul>
21
2008-08-02T15:11:16Z
195,170
<p>There must be a method in Cocoa to get a list of fonts, then you would have to use the PyObjC bindings to call it..</p> <p>Depending on what you need them for, you could probably just use something like the following..</p> <pre><code>import os def get_font_list(): fonts = [] for font_path in ["/Library/Fonts", os.path.expanduser("~/Library/Fonts")]: if os.path.isdir(font_path): fonts.extend( [os.path.join(font_path, cur_font) for cur_font in os.listdir(font_path) ] ) return fonts </code></pre>
1
2008-10-12T07:02:40Z
[ "python", "osx", "fonts", "photoshop" ]
Get a preview JPEG of a PDF on Windows?
502
<p>I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF.</p> <p>On the Mac I am spawning <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/sips.1.html">sips</a>. Is there something similarly simple I can do on Windows?</p>
27
2008-08-02T17:01:58Z
536
<p>You can use ImageMagick's convert utility for this, see some examples in <a href="https://web.archive.org/web/20120413111338/http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html" rel="nofollow">http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html</a> :</p> <blockquote> <pre><code>Convert taxes.pdf taxes.jpg </code></pre> <p>Will convert a two page PDF file into [2] jpeg files: taxes.jpg.0, taxes.jpg.1</p> <p>I can also convert these JPEGS to a thumbnail as follows:</p> <pre><code>convert -size 120x120 taxes.jpg.0 -geometry 120x120 +profile '*' thumbnail.jpg </code></pre> <p>I can even convert the PDF directly to a jpeg thumbnail as follows:</p> <pre><code>convert -size 120x120 taxes.pdf -geometry 120x120 +profile '*' thumbnail.jpg </code></pre> <p>This will result in a thumbnail.jpg.0 and thumbnail.jpg.1 for the two pages.</p> </blockquote>
9
2008-08-02T18:49:07Z
[ "python", "windows", "image", "pdf" ]
Get a preview JPEG of a PDF on Windows?
502
<p>I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF.</p> <p>On the Mac I am spawning <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/sips.1.html">sips</a>. Is there something similarly simple I can do on Windows?</p>
27
2008-08-02T17:01:58Z
7,073
<p>Is the PC likely to have Acrobat installed? I think Acrobat installs a shell extension so previews of the first page of a PDF document appear in Windows Explorer's thumbnail view. You can get thumbnails yourself via the IExtractImage COM API, which you'll need to wrap. <a href="http://www.vbaccelerator.com/home/net/code/libraries/shell_projects/Thumbnail_Extraction/article.asp" rel="nofollow" title="Domain Specific Development with Visual Studio DSL Tools.">VBAccelerator has an example in C#</a> that you could port to Python.</p>
2
2008-08-10T07:10:19Z
[ "python", "windows", "image", "pdf" ]
Get a preview JPEG of a PDF on Windows?
502
<p>I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF.</p> <p>On the Mac I am spawning <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/sips.1.html">sips</a>. Is there something similarly simple I can do on Windows?</p>
27
2008-08-02T17:01:58Z
7,090
<p>ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the <code>ps:alpha</code> delegate in ImageMagick, just adjusted to use JPEG as output):</p> <pre><code>gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \ -dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \ -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72x72 \ -sOutputFile=$OUTPUT -f$INPUT </code></pre> <p>where <code>$OUTPUT</code> and <code>$INPUT</code> are the output and input filenames. Adjust the <code>72x72</code> to whatever resolution you need. (Obviously, strip out the backslashes if you're writing out the whole command as one line.)</p> <p>This is good for two reasons:</p> <ol> <li>You don't need to have ImageMagick installed anymore. Not that I have anything against ImageMagick (I love it to bits), but I believe in simple solutions.</li> <li>ImageMagick does a two-step conversion. First PDF->PPM, then PPM->JPEG. This way, the conversion is one-step.</li> </ol> <p>Other things to consider: with the files I've tested, PNG compresses better than JPEG. If you want to use PNG, change the <code>-sDEVICE=jpeg</code> to <code>-sDEVICE=png16m</code>.</p>
25
2008-08-10T08:08:33Z
[ "python", "windows", "image", "pdf" ]
Continuous Integration System for a Python Codebase
535
<p>I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity.</p> <p>I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?</p>
40
2008-08-02T18:43:54Z
538
<p>One possibility is Hudson. It's written in Java, but there's integration with Python projects:</p> <blockquote> <p><a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html" rel="nofollow">Hudson embraces Python</a></p> </blockquote> <p>I've never tried it myself, however.</p> <p>(<strong>Update</strong>, Sept. 2011: After a trademark dispute Hudson has been renamed to <a href="http://jenkins-ci.org/" rel="nofollow">Jenkins</a>.)</p>
23
2008-08-02T18:56:56Z
[ "python", "continuous-integration", "extreme-programming" ]
Continuous Integration System for a Python Codebase
535
<p>I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity.</p> <p>I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?</p>
40
2008-08-02T18:43:54Z
541
<p>We run <a href="http://buildbot.net/trac">Buildbot - Trac</a> at work, I haven't used it too much since my code base isn't part of the release cycle yet. But we run the tests on different environments (OSX/Linux/Win) and it sends emails --and it's written in python.</p>
20
2008-08-02T19:06:40Z
[ "python", "continuous-integration", "extreme-programming" ]
Continuous Integration System for a Python Codebase
535
<p>I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity.</p> <p>I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?</p>
40
2008-08-02T18:43:54Z
660
<p>Second the Buildbot - Trac integration. You can find more information about the integration on the <a href="http://buildbot.net/trac/wiki/BuildbotAndTrac">Buildbot website</a>. At my previous job, we wrote and used the plugin they mention (tracbb). What the plugin does is rewriting all of the Buildbot urls so you can use Buildbot from within Trac. (http://example.com/tracbb).</p> <p>The really nice thing about Buildbot is that the configuration is written in Python. You can integrate your own Python code directly to the configuration. It's also very easy to write your own BuildSteps to execute specific tasks.</p> <p>We used BuildSteps to get the source from SVN, pull the dependencies, publish test results to WebDAV, etcetera.</p> <p>I wrote an X10 interface so we could send signals with build results. When the build failed, we switched on a red lava lamp. When the build succeeded, a green lava lamp switched on. Good times :-)</p>
14
2008-08-03T12:09:18Z
[ "python", "continuous-integration", "extreme-programming" ]
Continuous Integration System for a Python Codebase
535
<p>I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity.</p> <p>I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?</p>
40
2008-08-02T18:43:54Z
61,746
<p>We use both Buildbot and Hudson for Jython development. Both are useful, but have different strengths and weaknesses.</p> <p>Buildbot's configuration is pure Python and quite simple once you get the hang of it (look at the epydoc-generated API docs for the most current info). Buildbot makes it easier to define non-testing tasks and distribute the testers. However, it really has no concept of individual tests, just textual, HTML, and summary output, so if you want to have multi-level browsable test output and so forth you'll have to build it yourself, or just use Hudson.</p> <p>Hudson has terrific support for drilling down from overall results into test suites and individual tests; it also is great for comparing test output between builds, but the distributed (master/slave) stuff is comparatively more complicated because you need a Java environment on the slaves too; also, Hudson is less tolerant of flaky network links between the master and slaves.</p> <p>So, to get the benefits of both tools, we run a single instance of Hudson, which catches the common test failures, then we do multi-platform regression with Buildbot.</p> <p>Here are our instances:</p> <ul> <li><a href="http://bob.underboss.org:8080/job/jython/lastBuild/testReport/">Jython Hudson</a></li> <li><a href="http://www.acm.uiuc.edu/jython-buildbot/waterfall">Jython buildbot</a></li> </ul>
13
2008-09-15T00:11:21Z
[ "python", "continuous-integration", "extreme-programming" ]
Continuous Integration System for a Python Codebase
535
<p>I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity.</p> <p>I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?</p>
40
2008-08-02T18:43:54Z
74,452
<p>We are using <a href="http://bitten.edgewall.org/" rel="nofollow">Bitten</a> wich is integrated with trac. And it's python based.</p>
4
2008-09-16T16:51:46Z
[ "python", "continuous-integration", "extreme-programming" ]
Continuous Integration System for a Python Codebase
535
<p>I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity.</p> <p>I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?</p>
40
2008-08-02T18:43:54Z
117,712
<p>TeamCity has some Python <a href="http://www.jetbrains.net/confluence/display/TW/Python+Unit+Test+Reporting" rel="nofollow">integration</a>.</p> <p>But TeamCity is:</p> <ul> <li>not open-source</li> <li>is not small, but rather feature rich</li> <li>is free for small-mid teams.</li> </ul>
3
2008-09-22T21:18:15Z
[ "python", "continuous-integration", "extreme-programming" ]
Continuous Integration System for a Python Codebase
535
<p>I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity.</p> <p>I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?</p>
40
2008-08-02T18:43:54Z
9,120,453
<p>I have very good experiences with <a href="http://travis-ci.org/" rel="nofollow">Travis-CI</a> for smaller code bases. The main advantages are:</p> <ul> <li>setup is done in less than half a screen of config file</li> <li>you can do your own installation or just use the free hosted version</li> <li>semi-automatic setup for github repositories</li> <li>no account needed on website; login via github</li> </ul> <p>Some limitations:</p> <ul> <li><p>Python is not supported as a first class language (as of time of writing; but you can use pip and apt-get to install python dependencies; see <a href="http://www.travisswicegood.com/2011/11/11/travis-and-python/" rel="nofollow">this tutorial</a>)</p></li> <li><p>code has to be hosted on github (at least when using the official version)</p></li> </ul>
2
2012-02-02T21:42:23Z
[ "python", "continuous-integration", "extreme-programming" ]
cx_Oracle: How do I iterate over a result set?
594
<p>There are several ways to iterate over a result set. What are the tradeoff of each?</p>
25
2008-08-03T01:15:08Z
595
<p>The canonical way is to use the built-in cursor iterator.</p> <pre><code>curs.execute('select * from people') for row in curs: print row </code></pre> <hr> <p>You can use <code>fetchall()</code> to get all rows at once.</p> <pre><code>for row in curs.fetchall(): print row </code></pre> <p>It can be convenient to use this to create a Python list containing the values returned:</p> <pre><code>curs.execute('select first_name from people') names = [row[0] for row in curs.fetchall()] </code></pre> <p>This can be useful for smaller result sets, but can have bad side effects if the result set is large.</p> <ul> <li><p>You have to wait for the entire result set to be returned to your client process.</p></li> <li><p>You may eat up a lot of memory in your client to hold the built-up list.</p></li> <li><p>It may take a while for Python to construct and deconstruct the list which you are going to immediately discard anyways.</p></li> </ul> <hr> <p>If you know there's a single row being returned in the result set you can call <code>fetchone()</code> to get the single row.</p> <pre><code>curs.execute('select max(x) from t') maxValue = curs.fetchone()[0] </code></pre> <hr> <p>Finally, you can loop over the result set fetching one row at a time. In general, there's no particular advantage in doing this over using the iterator.</p> <pre><code>row = curs.fetchone() while row: print row row = curs.fetchone() </code></pre>
25
2008-08-03T01:17:36Z
[ "python", "sql", "database", "oracle", "cx-oracle" ]
cx_Oracle: How do I iterate over a result set?
594
<p>There are several ways to iterate over a result set. What are the tradeoff of each?</p>
25
2008-08-03T01:15:08Z
25,213
<p>There's also the way <code>psyco-pg</code> seems to do it... From what I gather, it seems to create dictionary-like row-proxies to map key lookup into the memory block returned by the query. In that case, fetching the whole answer and working with a similar proxy-factory over the rows seems like useful idea. Come to think of it though, it feels more like Lua than Python.</p> <p>Also, this should be applicable to all <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">PEP-249 DBAPI2.0</a> interfaces, not just Oracle, or did you mean just <em>fastest</em> using <em>Oracle</em>?</p>
4
2008-08-24T17:28:26Z
[ "python", "sql", "database", "oracle", "cx-oracle" ]
cx_Oracle: How do I iterate over a result set?
594
<p>There are several ways to iterate over a result set. What are the tradeoff of each?</p>
25
2008-08-03T01:15:08Z
125,140
<p>My preferred way is the cursor iterator, but setting first the arraysize property of the cursor. </p> <pre><code>curs.execute('select * from people') curs.arraysize = 256 for row in curs: print row </code></pre> <p>In this example, cx_Oracle will fetch rows from Oracle 256 rows at a time, reducing the number of network round trips that need to be performed</p>
17
2008-09-24T02:51:00Z
[ "python", "sql", "database", "oracle", "cx-oracle" ]
Using 'in' to match an attribute of Python objects in an array
683
<p>I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,</p> <pre><code>foo in iter_attr(array of python objects, attribute name)</code></pre> <p>I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers</p>
28
2008-08-03T13:19:16Z
701
<p>No, you were not dreaming. Python has a pretty excellent list comprehension system that lets you manipulate lists pretty elegantly, and depending on exactly what you want to accomplish, this can be done a couple of ways. In essence, what you're doing is saying "For item in list if criteria.matches", and from that you can just iterate through the results or dump the results into a new list.</p> <p>I'm going to crib an example from <a href="http://diveintopython.net/functional_programming/filtering_lists.html" rel="nofollow">Dive Into Python</a> here, because it's pretty elegant and they're smarter than I am. Here they're getting a list of files in a directory, then filtering the list for all files that match a regular expression criteria.</p> <blockquote> <pre><code> files = os.listdir(path) test = re.compile("test\.py$", re.IGNORECASE) files = [f for f in files if test.search(f)] </code></pre> </blockquote> <p>You could do this without regular expressions, for your example, for anything where your expression at the end returns true for a match. There are other options like using the filter() function, but if I were going to choose, I'd go with this.</p> <p>Eric Sipple</p>
3
2008-08-03T14:30:50Z
[ "python", "arrays", "iteration" ]
Using 'in' to match an attribute of Python objects in an array
683
<p>I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,</p> <pre><code>foo in iter_attr(array of python objects, attribute name)</code></pre> <p>I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers</p>
28
2008-08-03T13:19:16Z
735
<p>I think:</p> <pre><code>#!/bin/python<br>bar in dict(Foo)<br></code></pre> <p>Is what you are thinking of. When trying to see if a certain key exists within a dictionary in python (python's version of a hash table) there are two ways to check. First is the <strong><code>has_key()</code></strong> method attached to the dictionary and second is the example given above. It will return a boolean value.</p> <p>That should answer your question.</p> <p>And now a little off topic to tie this in to the <em>list comprehension</em> answer previously given (for a bit more clarity). <em>List Comprehensions</em> construct a list from a basic <em>for loop</em> with modifiers. As an example (to clarify slightly), a way to use the <code>in dict</code> language construct in a _list comprehension_:</p> <p>Say you have a two dimensional dictionary <strong><code>foo</code></strong> and you only want the second dimension dictionaries which contain the key <strong><code>bar</code></strong>. A relatively straightforward way to do so would be to use a <em>list comprehension</em> with a conditional as follows:</p> <pre><code>#!/bin/python<br>baz = dict([(key, value) for key, value in foo if bar in value])<br></code></pre> <p>Note the <strong><code>if bar in value</code></strong> at the end of the statement<strong>, this is a modifying clause which tells the <em>list comprehension</em> to only keep those key-value pairs which meet the conditional.</strong> In this case <strong><code>baz</code></strong> is a new dictionary which contains only the dictionaries from foo which contain bar (Hopefully I didn't miss anything in that code example... you may have to take a look at the list comprehension documentation found in <a href="http://docs.python.org/tut/node7.html#SECTION007140000000000000000" rel="nofollow">docs.python.org tutorials</a> and at <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">secnetix.de</a>, both sites are good references if you have questions in the future.).</p>
-2
2008-08-03T15:47:22Z
[ "python", "arrays", "iteration" ]
Using 'in' to match an attribute of Python objects in an array
683
<p>I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,</p> <pre><code>foo in iter_attr(array of python objects, attribute name)</code></pre> <p>I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers</p>
28
2008-08-03T13:19:16Z
745
<p>Are you looking to get a list of objects that have a certain attribute? If so, a <a href="http://docs.python.org/tut/node7.html#SECTION007140000000000000000">list comprehension</a> is the right way to do this.</p> <pre><code>result = [obj for obj in listOfObjs if hasattr(obj, 'attributeName')]<br></code></pre>
8
2008-08-03T15:59:19Z
[ "python", "arrays", "iteration" ]
Using 'in' to match an attribute of Python objects in an array
683
<p>I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,</p> <pre><code>foo in iter_attr(array of python objects, attribute name)</code></pre> <p>I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers</p>
28
2008-08-03T13:19:16Z
750
<p>What I was thinking of can be achieved using list comprehensions, but I thought that there was a function that did this in a slightly neater way.</p> <p>i.e. 'bar' is a list of objects, all of which have the attribute 'id'</p> <p>The mythical functional way:</p> <pre><code>foo = 12<br>foo in iter_attr(bar, 'id')</code></pre> <p>The list comprehension way:</p> <pre><code>foo = 12<br>foo in [obj.id for obj in bar]</code></pre> <p>In retrospect the list comprehension way is pretty neat anyway.</p>
2
2008-08-03T16:13:29Z
[ "python", "arrays", "iteration" ]
Using 'in' to match an attribute of Python objects in an array
683
<p>I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,</p> <pre><code>foo in iter_attr(array of python objects, attribute name)</code></pre> <p>I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers</p>
28
2008-08-03T13:19:16Z
31,126
<p>you could always write one yourself:</p> <pre><code>def iterattr(iterator, attributename): for obj in iterator: yield getattr(obj, attributename) </code></pre> <p>will work with anything that iterates, be it a tuple, list, or whatever.</p> <p>I love python, it makes stuff like this very simple and no more of a hassle than neccessary, and in use stuff like this is hugely elegant.</p>
6
2008-08-27T20:13:49Z
[ "python", "arrays", "iteration" ]
Using 'in' to match an attribute of Python objects in an array
683
<p>I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,</p> <pre><code>foo in iter_attr(array of python objects, attribute name)</code></pre> <p>I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers</p>
28
2008-08-03T13:19:16Z
31,188
<p>If you plan on searching anything of remotely decent size, your best bet is going to be to use a dictionary or a set. Otherwise, you basically have to iterate through every element of the iterator until you get to the one you want.</p> <p>If this isn't necessarily performance sensitive code, then the list comprehension way should work. But note that it is fairly inefficient because it goes over every element of the iterator and then goes BACK over it again until it finds what it wants.</p> <p>Remember, python has one of the most efficient hashing algorithms around. Use it to your advantage.</p>
2
2008-08-27T20:30:22Z
[ "python", "arrays", "iteration" ]
Using 'in' to match an attribute of Python objects in an array
683
<p>I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,</p> <pre><code>foo in iter_attr(array of python objects, attribute name)</code></pre> <p>I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers</p>
28
2008-08-03T13:19:16Z
57,833
<p>Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before <code>in</code> could start its search.</p> <p>The temporary list can be avoiding by using a generator expression:</p> <pre><code>foo = 12 foo in (obj.id for obj in bar) </code></pre> <p>Now, as long as <code>obj.id == 12</code> near the start of <code>bar</code>, the search will be fast, even if <code>bar</code> is infinitely long.</p> <p>As @Matt suggested, it's a good idea to use <code>hasattr</code> if any of the objects in <code>bar</code> can be missing an <code>id</code> attribute:</p> <pre><code>foo = 12 foo in (obj.id for obj in bar if hasattr(obj, 'id')) </code></pre>
29
2008-09-11T22:42:14Z
[ "python", "arrays", "iteration" ]
Using 'in' to match an attribute of Python objects in an array
683
<p>I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,</p> <pre><code>foo in iter_attr(array of python objects, attribute name)</code></pre> <p>I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers</p>
28
2008-08-03T13:19:16Z
4,905,822
<p>The function you are thinking of is probably <code>operator.attrgettter</code>. For example, to get a list that contains the value of each object's "id" attribute:</p> <pre><code>import operator ids = map(operator.attrgetter("id"), bar)</code></pre> <p>If you want to check whether the list contains an object with an id == 12, then a neat and efficient (i.e. doesn't iterate the whole list unnecessarily) way to do it is:</p> <pre><code>any(obj.id == 12 for obj in bar)</code></pre> <p>If you want to use 'in' with attrgetter, while still retaining lazy iteration of the list:</p> <p><pre><code>import operator,itertools foo = 12 foo in itertools.imap(operator.attrgetter("id"), bar) </pre></code></p>
3
2011-02-05T08:10:41Z
[ "python", "arrays", "iteration" ]
Class views in Django
742
<p><a href="http://www.djangoproject.com/">Django</a> view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach.</p> <p>For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc...</p> <p>One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? </p>
30
2008-08-03T15:55:28Z
764
<p>Sounds to me like you're trying to combine things that shouldn't be combined. If you need to do different processing in your view depending on if it's a User or Group object you're trying to look at then you should use two different view functions.</p> <p>On the other hand there can be common idioms you'd want to extract out of your object_detail type views... perhaps you could use a decorator or just helper functions?</p> <p>-Dan</p>
0
2008-08-03T17:40:25Z
[ "python", "django", "views", "oop" ]
Class views in Django
742
<p><a href="http://www.djangoproject.com/">Django</a> view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach.</p> <p>For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc...</p> <p>One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? </p>
30
2008-08-03T15:55:28Z
4,572
<p>If you're simply displaying data from models, why not use the <a href="https://docs.djangoproject.com/en/1.2/ref/generic-views/" rel="nofollow">Django Generic Views</a>? They're designed to let you easy show data from a model without having to write your own view and stuff about mapping URL paramaters to views, fetching data, handling edge cases, rendering output, etc.</p>
7
2008-08-07T10:44:23Z
[ "python", "django", "views", "oop" ]
Class views in Django
742
<p><a href="http://www.djangoproject.com/">Django</a> view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach.</p> <p>For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc...</p> <p>One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? </p>
30
2008-08-03T15:55:28Z
8,320
<p>Unless you want to do something a little complex, using the generic views are the way to go. They are far more powerful than their name implies, and if you are just displaying model data generic views will do the job.</p>
1
2008-08-11T22:59:42Z
[ "python", "django", "views", "oop" ]
Class views in Django
742
<p><a href="http://www.djangoproject.com/">Django</a> view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach.</p> <p>For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc...</p> <p>One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? </p>
30
2008-08-03T15:55:28Z
27,780
<p>If you want to share common functionality between pages I suggest you look at custom tags. They're quite <a href="https://docs.djangoproject.com/en/1.1/howto/custom-template-tags/" rel="nofollow">easy to create</a>, and are very powerful.</p> <p>Also, <a href="https://code.djangoproject.com/wiki/ExtendingTemplates" rel="nofollow">templates can extend from other templates</a>. This allows you to have a base template to set up the layout of the page and to share this between other templates which fill in the blanks. You can nest templates to any depth; allowing you to specify the layout on separate groups of related pages in one place.</p>
0
2008-08-26T11:30:50Z
[ "python", "django", "views", "oop" ]
Class views in Django
742
<p><a href="http://www.djangoproject.com/">Django</a> view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach.</p> <p>For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc...</p> <p>One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? </p>
30
2008-08-03T15:55:28Z
27,792
<p>You can always create a class, override the <em><code>__call__</code></em> function and then point the URL file to an instance of the class. You can take a look at the <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/formtools/wizard.py" rel="nofollow">FormWizard</a> class to see how this is done.</p>
2
2008-08-26T11:38:36Z
[ "python", "django", "views", "oop" ]
Class views in Django
742
<p><a href="http://www.djangoproject.com/">Django</a> view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach.</p> <p>For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc...</p> <p>One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? </p>
30
2008-08-03T15:55:28Z
33,957
<p>I've created and used my own generic view classes, defining <strong><code>__call__</code></strong> so an instance of the class is callable. I really like it; while Django's generic views allow some customization through keyword arguments, OO generic views (if their behavior is split into a number of separate methods) can have much more fine-grained customization via subclassing, which lets me repeat myself a lot less. (I get tired of rewriting the same create/update view logic anytime I need to tweak something Django's generic views don't quite allow).</p> <p>I've posted some code at <a href="http://www.djangosnippets.org/snippets/1009/">djangosnippets.org</a>.</p> <p>The only real downside I see is the proliferation of internal method calls, which may impact performance somewhat. I don't think this is much of a concern; it's rare that Python code execution would be your performance bottleneck in a web app.</p> <p><strong>UPDATE</strong>: Django's own <a href="http://docs.djangoproject.com/en/dev/topics/class-based-views/">generic views</a> are now class-based.</p> <p><strong>UPDATE</strong>: FWIW, I've changed my opinion on class-based views since this answer was written. After having used them extensively on a couple of projects, I feel they tend to lead to code that is satisfyingly DRY to write, but very hard to read and maintain later, because functionality is spread across so many different places, and subclasses are so dependent on every implementation detail of the superclasses and mixins. I now feel that <a href="https://docs.djangoproject.com/en/dev/ref/template-response/">TemplateResponse</a> and view decorators is a better answer for decomposing view code.</p>
36
2008-08-29T04:29:22Z
[ "python", "django", "views", "oop" ]
Class views in Django
742
<p><a href="http://www.djangoproject.com/">Django</a> view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach.</p> <p>For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc...</p> <p>One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? </p>
30
2008-08-03T15:55:28Z
123,090
<p>Generic views will usually be the way to go, but ultimately you're free to handle URLs however you want. FormWizard does things in a class-based way, as do some apps for RESTful APIs.</p> <p>Basically with a URL you are given a bunch of variables and place to provide a callable, what callable you provide is completely up to you - the standard way is to provide a function - but ultimately Django puts no restrictions on what you do.</p> <p>I do agree that a few more examples of how to do this would be good, FormWizard is probably the place to start though.</p>
0
2008-09-23T19:05:51Z
[ "python", "django", "views", "oop" ]
Class views in Django
742
<p><a href="http://www.djangoproject.com/">Django</a> view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach.</p> <p>For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc...</p> <p>One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? </p>
30
2008-08-03T15:55:28Z
2,921,293
<p>I needed to use class based views, but I wanted to be able to use the full name of the class in my URLconf without always having to instantiate the view class before using it. What helped me was a surprisingly simple metaclass:</p> <pre><code>class CallableViewClass(type): def __call__(cls, *args, **kwargs): if args and isinstance(args[0], HttpRequest): instance = super(CallableViewClass, cls).__call__() return instance.__call__(*args, **kwargs) else: instance = super(CallableViewClass, cls).__call__(*args, **kwargs) return instance class View(object): __metaclass__ = CallableViewClass def __call__(self, request, *args, **kwargs): if hasattr(self, request.method): handler = getattr(self, request.method) if hasattr(handler, '__call__'): return handler(request, *args, **kwargs) return HttpResponseBadRequest('Method Not Allowed', status=405) </code></pre> <p>I can now both instantiate view classes and use the instances as view functions, OR I can simply point my URLconf to my class and have the metaclass instantiate (and call) the view class for me. This works by checking the first argument to <code>__call__</code> – if it's a <code>HttpRequest</code>, it must be an actual HTTP request because it would be nonsense to attept to instantiate a view class with an <code>HttpRequest</code> instance.</p> <pre><code>class MyView(View): def __init__(self, arg=None): self.arg = arg def GET(request): return HttpResponse(self.arg or 'no args provided') @login_required class MyOtherView(View): def POST(request): pass # And all the following work as expected. urlpatterns = patterns('' url(r'^myview1$', 'myapp.views.MyView', name='myview1'), url(r'^myview2$', myapp.views.MyView, name='myview2'), url(r'^myview3$', myapp.views.MyView('foobar'), name='myview3'), url(r'^myotherview$', 'myapp.views.MyOtherView', name='otherview'), ) </code></pre> <p>(I posted a snippet for this at <a href="http://djangosnippets.org/snippets/2041/">http://djangosnippets.org/snippets/2041/</a>)</p>
11
2010-05-27T13:02:08Z
[ "python", "django", "views", "oop" ]
Class views in Django
742
<p><a href="http://www.djangoproject.com/">Django</a> view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach.</p> <p>For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc...</p> <p>One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? </p>
30
2008-08-03T15:55:28Z
26,250,049
<p>You can use the Django Generic Views. You can easily achieve desired functionality thorough Django generic Views</p>
0
2014-10-08T05:53:09Z
[ "python", "django", "views", "oop" ]
Python and MySQL
766
<p>I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.</p> <p>I found <a href="http://barryp.org/software/bpgsql/">bpgsql</a> really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?</p>
20
2008-08-03T17:44:07Z
777
<p>I don't have any experience with <a href="http://www.SiteGround.com" rel="nofollow">http://www.SiteGround.com</a> as a web host personally. </p> <p>This is just a guess, but it's common for a shared host to support Python and MySQL with the MySQLdb module (e.g., GoDaddy does this). Try the following CGI script to see if MySQLdb is installed.</p> <pre><code>#!/usr/bin/python<br><br>module_name = 'MySQLdb'<br>head = '''Content-Type: text/html<br><br>%s is ''' % module_name<br><br>try:<br> __import__(module_name)<br> print head + 'installed'<br>except ImportError:<br> print head + 'not installed'<br></code></pre>
5
2008-08-03T18:32:27Z
[ "python", "mysql", "postgresql", "bpgsql" ]
Python and MySQL
766
<p>I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.</p> <p>I found <a href="http://barryp.org/software/bpgsql/">bpgsql</a> really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?</p>
20
2008-08-03T17:44:07Z
802
<p>I uploaded it and got an internal error</p> <pre><code>Premature end of script headers<br></code></pre> <p>After much playing around, I found that if I had</p> <pre><code>import cgi<br>import cgitb; cgitb.enable()<br>import MySQLdb<br></code></pre> <p>It would give me a much more useful answer and say that it was not installed, you can see it yourself -> <a href="http://woarl.com/db.py" rel="nofollow">http://woarl.com/db.py</a></p> <p>Oddly enough, this would produce an error</p> <pre><code>import MySQLdb<br>import cgi<br>import cgitb; cgitb.enable()<br></code></pre> <p>I looked at some of the other files I had up there and it seems that library was one of the ones I had already tried.</p>
4
2008-08-03T20:07:05Z
[ "python", "mysql", "postgresql", "bpgsql" ]
Python and MySQL
766
<p>I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.</p> <p>I found <a href="http://barryp.org/software/bpgsql/">bpgsql</a> really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?</p>
20
2008-08-03T17:44:07Z
1,619
<p>MySQLdb is what I have used before.</p> <p>If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem). But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do with it.</p> <p>Another option may be to call your host and complain, or change hosts. Honestly these days, any self respecting web host that supports python and mysql ought to have MySQLdb pre installed.</p>
17
2008-08-04T21:54:11Z
[ "python", "mysql", "postgresql", "bpgsql" ]
Python and MySQL
766
<p>I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.</p> <p>I found <a href="http://barryp.org/software/bpgsql/">bpgsql</a> really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?</p>
20
2008-08-03T17:44:07Z
8,332
<p>You could try setting up your own python installation using <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#creating-a-virtual-python" rel="nofollow">Virtual Python</a>. Check out how to setup Django using it <a href="http://forums.site5.com/showthread.php?t=10236" rel="nofollow">here</a>. That was written a long time ago, but it shows how I got MySQLdb setup without having root access or anything like it. Once you've got the basics going, you can install any python library you want.</p>
4
2008-08-11T23:16:33Z
[ "python", "mysql", "postgresql", "bpgsql" ]
Python and MySQL
766
<p>I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.</p> <p>I found <a href="http://barryp.org/software/bpgsql/">bpgsql</a> really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?</p>
20
2008-08-03T17:44:07Z
4,813,530
<p>You really want MySQLdb for any MySQL + Python code. However, you shouldn't need root access or anything to use it. You can build/install it in a user directory (~/lib/python2.x/site-packages), and just add that to your PYTHON_PATH env variable. This should work for just about any python library.</p> <p>Give it a shot, there really isn't a good alternative.</p>
3
2011-01-27T06:48:31Z
[ "python", "mysql", "postgresql", "bpgsql" ]
Python and MySQL
766
<p>I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.</p> <p>I found <a href="http://barryp.org/software/bpgsql/">bpgsql</a> really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?</p>
20
2008-08-03T17:44:07Z
33,058,407
<p>Take a pick at</p> <p><a href="https://docs.djangoproject.com/en/1.8/ref/databases/" rel="nofollow">https://docs.djangoproject.com/en/1.8/ref/databases/</a></p> <p>MySQLdb is mostly used driver, but if you are using python3 and django 1.8.x that will not work, then you should use mysqlclient that is a folk of MySQLdb on the following link</p> <p><a href="https://pypi.python.org/pypi/mysqlclient" rel="nofollow">https://pypi.python.org/pypi/mysqlclient</a></p>
1
2015-10-10T20:00:39Z
[ "python", "mysql", "postgresql", "bpgsql" ]
How do I use Python's itertools.groupby()?
773
<p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p> <ul> <li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li> <li>Divide it into groups based on some criteria</li> <li>Then later iterate over each of these groups separately.</li> </ul> <p>I've reviewed <a href="https://docs.python.org/2/library/itertools.html">the documentation</a>, and <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby">the examples</a>, but I've had trouble trying to apply them beyond a simple list of numbers. </p> <p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.</p>
256
2008-08-03T18:27:09Z
783
<p>Can you show us your code?</p> <p>The example on the Python docs is quite straightforward:</p> <pre><code>groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) </code></pre> <p>So in your case, data is a list of nodes, keyfunc is where the logic of your criteria function goes and then <code>groupby()</code> groups the data.</p> <p>You must be careful to <strong>sort the data</strong> by the criteria before you call <code>groupby</code> or it won't work. <code>groupby</code> method actually just iterates through a list and whenever the key changes it creates a new group.</p>
52
2008-08-03T18:40:09Z
[ "python", "iteration" ]
How do I use Python's itertools.groupby()?
773
<p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p> <ul> <li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li> <li>Divide it into groups based on some criteria</li> <li>Then later iterate over each of these groups separately.</li> </ul> <p>I've reviewed <a href="https://docs.python.org/2/library/itertools.html">the documentation</a>, and <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby">the examples</a>, but I've had trouble trying to apply them beyond a simple list of numbers. </p> <p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.</p>
256
2008-08-03T18:27:09Z
7,286
<p>As Sebastjan said, <strong>you first have to sort your data. This is important.</strong></p> <p>The part I didn't get is that in the example construction</p> <pre><code>groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) </code></pre> <p><code>k</code> is the current grouping key, and <code>g</code> is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the <code>groupby</code> iterator itself returns iterators.</p> <p>Here's an example of that, using clearer variable names:</p> <pre><code>from itertools import groupby things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")] for key, group in groupby(things, lambda x: x[0]): for thing in group: print "A %s is a %s." % (thing[1], key) print " " </code></pre> <p>This will give you the output:</p> <blockquote> <p>A bear is a animal.<br> A duck is a animal.</p> <p>A cactus is a plant.</p> <p>A speed boat is a vehicle.<br> A school bus is a vehicle.</p> </blockquote> <p>In this example, <code>things</code> is a list of tuples where the first item in each tuple is the group the second item belongs to. </p> <p>The <code>groupby()</code> function takes two arguments: (1) the data to group and (2) the function to group it with. </p> <p>Here, <code>lambda x: x[0]</code> tells <code>groupby()</code> to use the first item in each tuple as the grouping key.</p> <p>In the above <code>for</code> statement, <code>groupby</code> returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group.</p> <p>Here's a slightly different example with the same data, using a list comprehension:</p> <pre><code>for key, group in groupby(things, lambda x: x[0]): listOfThings = " and ".join([thing[1] for thing in group]) print key + "s: " + listOfThings + "." </code></pre> <p>This will give you the output:</p> <blockquote> <p>animals: bear and duck.<br> plants: cactus.<br> vehicles: speed boat and school bus.</p> </blockquote>
394
2008-08-10T18:45:32Z
[ "python", "iteration" ]
How do I use Python's itertools.groupby()?
773
<p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p> <ul> <li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li> <li>Divide it into groups based on some criteria</li> <li>Then later iterate over each of these groups separately.</li> </ul> <p>I've reviewed <a href="https://docs.python.org/2/library/itertools.html">the documentation</a>, and <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby">the examples</a>, but I've had trouble trying to apply them beyond a simple list of numbers. </p> <p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.</p>
256
2008-08-03T18:27:09Z
37,252
<p>A neato trick with groupby is to run length encoding in one line:</p> <pre><code>[(c,len(list(cgen))) for c,cgen in groupby(some_string)] </code></pre> <p>will give you a list of 2-tuples where the first element is the char and the 2nd is the number of repetitions.</p>
24
2008-08-31T23:27:16Z
[ "python", "iteration" ]
How do I use Python's itertools.groupby()?
773
<p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p> <ul> <li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li> <li>Divide it into groups based on some criteria</li> <li>Then later iterate over each of these groups separately.</li> </ul> <p>I've reviewed <a href="https://docs.python.org/2/library/itertools.html">the documentation</a>, and <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby">the examples</a>, but I've had trouble trying to apply them beyond a simple list of numbers. </p> <p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.</p>
256
2008-08-03T18:27:09Z
1,573,195
<p>@CaptSolo, I tried your example, but it didn't work.</p> <pre><code>from itertools import groupby [(c,len(list(cs))) for c,cs in groupby('Pedro Manoel')] </code></pre> <p>Output:</p> <pre><code>[('P', 1), ('e', 1), ('d', 1), ('r', 1), ('o', 1), (' ', 1), ('M', 1), ('a', 1), ('n', 1), ('o', 1), ('e', 1), ('l', 1)] </code></pre> <p>As you can see, there are two o's and two e's, but they got into separate groups. That's when I realized you need to sort the list passed to the groupby function. So, the correct usage would be:</p> <pre><code>name = list('Pedro Manoel') name.sort() [(c,len(list(cs))) for c,cs in groupby(name)] </code></pre> <p>Output:</p> <pre><code>[(' ', 1), ('M', 1), ('P', 1), ('a', 1), ('d', 1), ('e', 2), ('l', 1), ('n', 1), ('o', 2), ('r', 1)] </code></pre> <p>Just remembering, if the list is not sorted, the groupby function <strong>will not work</strong>!</p>
5
2009-10-15T15:41:51Z
[ "python", "iteration" ]
How do I use Python's itertools.groupby()?
773
<p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p> <ul> <li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li> <li>Divide it into groups based on some criteria</li> <li>Then later iterate over each of these groups separately.</li> </ul> <p>I've reviewed <a href="https://docs.python.org/2/library/itertools.html">the documentation</a>, and <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby">the examples</a>, but I've had trouble trying to apply them beyond a simple list of numbers. </p> <p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.</p>
256
2008-08-03T18:27:09Z
14,443,477
<p>Another example:</p> <pre><code>for key, igroup in itertools.groupby(xrange(12), lambda x: x // 5): print key, list(igroup) </code></pre> <p>results in</p> <pre><code>0 [0, 1, 2, 3, 4] 1 [5, 6, 7, 8, 9] 2 [10, 11] </code></pre> <p>Note that igroup is an iterator (a sub-iterator as the documentation calls it).</p> <p>This is useful for chunking a generator:</p> <pre><code>def chunker(items, chunk_size): '''Group items in chunks of chunk_size''' for _key, group in itertools.groupby(enumerate(items), lambda x: x[0] // chunk_size): yield (g[1] for g in group) with open('file.txt') as fobj: for chunk in chunker(fobj): process(chunk) </code></pre> <p>Another example of groupby - when the keys are not sorted. In the following example, items in xx are grouped by values in yy. In this case, one set of zeros is output first, followed by a set of ones, followed again by a set of zeros.</p> <pre><code>xx = range(10) yy = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0] for group in itertools.groupby(iter(xx), lambda x: yy[x]): print group[0], list(group[1]) </code></pre> <p>Produces:</p> <pre><code>0 [0, 1, 2] 1 [3, 4, 5] 0 [6, 7, 8, 9] </code></pre>
15
2013-01-21T16:54:08Z
[ "python", "iteration" ]
How do I use Python's itertools.groupby()?
773
<p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p> <ul> <li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li> <li>Divide it into groups based on some criteria</li> <li>Then later iterate over each of these groups separately.</li> </ul> <p>I've reviewed <a href="https://docs.python.org/2/library/itertools.html">the documentation</a>, and <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby">the examples</a>, but I've had trouble trying to apply them beyond a simple list of numbers. </p> <p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.</p>
256
2008-08-03T18:27:09Z
16,427,674
<p>I would like to give another example where groupby without sort is not working. Adapted from example by James Sulak</p> <pre><code>from itertools import groupby things = [("vehicle", "bear"), ("animal", "duck"), ("animal", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")] for key, group in groupby(things, lambda x: x[0]): for thing in group: print "A %s is a %s." % (thing[1], key) print " " </code></pre> <p>output is</p> <pre><code>A bear is a vehicle. A duck is a animal. A cactus is a animal. A speed boat is a vehicle. A school bus is a vehicle. </code></pre> <p>there are two groups with vehicule, whereas one could expect only one group</p>
8
2013-05-07T20:09:46Z
[ "python", "iteration" ]
How do I use Python's itertools.groupby()?
773
<p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p> <ul> <li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li> <li>Divide it into groups based on some criteria</li> <li>Then later iterate over each of these groups separately.</li> </ul> <p>I've reviewed <a href="https://docs.python.org/2/library/itertools.html">the documentation</a>, and <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby">the examples</a>, but I've had trouble trying to apply them beyond a simple list of numbers. </p> <p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.</p>
256
2008-08-03T18:27:09Z
20,013,133
<p>WARNING:</p> <p>The syntax list(groupby(...)) won't work the way that you intend. It seems to destroy the internal iterator objects, so using</p> <pre><code>for x in list(groupby(range(10))): print(list(x[1])) </code></pre> <p>will produce:</p> <pre><code>[] [] [] [] [] [] [] [] [] [9] </code></pre> <p>Instead, of list(groupby(...)), try [(k, list(g)) for k,g in groupby(...)], or if you use that syntax often,</p> <pre><code>def groupbylist(*args, **kwargs): return [(k, list(g)) for k, g in groupby(*args, **kwargs)] </code></pre> <p>and get access to the groupby functionality while avoiding those pesky (for small data) iterators all together.</p>
10
2013-11-16T00:39:31Z
[ "python", "iteration" ]
How do I use Python's itertools.groupby()?
773
<p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p> <ul> <li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li> <li>Divide it into groups based on some criteria</li> <li>Then later iterate over each of these groups separately.</li> </ul> <p>I've reviewed <a href="https://docs.python.org/2/library/itertools.html">the documentation</a>, and <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby">the examples</a>, but I've had trouble trying to apply them beyond a simple list of numbers. </p> <p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.</p>
256
2008-08-03T18:27:09Z
31,660,194
<blockquote> <p><strong>How do I use Python's itertools.groupby()?</strong></p> </blockquote> <p>You can use groupby to group things to iterate over. You give groupby an iterable, and a optional <strong>key</strong> function/callable by which to check the items as they come out of the iterable, and it returns an iterator that gives a two-tuple of the result of the key callable and the actual items in another iterable. From the help:</p> <pre><code>groupby(iterable[, keyfunc]) -&gt; create an iterator which returns (key, sub-iterator) grouped by each value of key(value). </code></pre> <p>Here's an example of groupby using a coroutine to group by a count, it uses a key callable (in this case, <code>coroutine.send</code>) to just spit out the count for however many iterations and a grouped sub-iterator of elements:</p> <pre><code>import itertools def grouper(iterable, n): def coroutine(n): yield # queue up coroutine for i in itertools.count(): for j in range(n): yield i groups = coroutine(n) next(groups) # queue up coroutine for c, objs in itertools.groupby(iterable, groups.send): yield c, list(objs) # or instead of materializing a list of objs, just: # return itertools.groupby(iterable, groups.send) list(grouper(range(10), 3)) </code></pre> <p>prints</p> <pre><code>[(0, [0, 1, 2]), (1, [3, 4, 5]), (2, [6, 7, 8]), (3, [9])] </code></pre>
3
2015-07-27T18:06:30Z
[ "python", "iteration" ]
How do I use Python's itertools.groupby()?
773
<p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p> <ul> <li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li> <li>Divide it into groups based on some criteria</li> <li>Then later iterate over each of these groups separately.</li> </ul> <p>I've reviewed <a href="https://docs.python.org/2/library/itertools.html">the documentation</a>, and <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby">the examples</a>, but I've had trouble trying to apply them beyond a simple list of numbers. </p> <p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.</p>
256
2008-08-03T18:27:09Z
36,057,344
<p>Thanks for lots of nice anwser, this is a hackerrank challenge about <strong>groupby</strong>, this is <a href="https://www.hackerrank.com/challenges/compress-the-string/submissions/code/18455859" rel="nofollow">link</a>.</p> <pre><code>args = "1234567890" for key, group in groupby(args): # print group # you can look what group is. print((len(list(group)), int(key)), end=" ") </code></pre> <p>the output:</p> <p>(1, 1) (1, 2) (1, 3) (1, 4) (1, 5) (1, 6) (1, 7) (1, 8) (1, 9) (1, 0)</p> <p>just count the num occurrence.</p>
2
2016-03-17T10:08:34Z
[ "python", "iteration" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
982
<p>In Python monkey patching generally works by overwriting a class or functions signature with your own. Below is an example from the <a href="http://wiki.zope.org/zope2/MonkeyPatch">Zope Wiki</a>:</p> <pre><code>from SomeOtherProduct.SomeModule import SomeClass<br>def speak(self):<br> return "ook ook eee eee eee!"<br>SomeClass.speak = speak<br></code></pre> <p>That code will overwrite/create a method called speak on the class. In Jeff Atwood's <a href="http://www.codinghorror.com/blog/archives/001151.html">recent post on monkey patching</a>. He shows an example in C# 3.0 which is the current language I use for work.</p>
14
2008-08-04T02:31:13Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
984
<p>I don't know Python syntax, but I know Ruby can do it, and it is rather trivial. Let's say you want to add a method to Array that prints the length to standard out:</p> <pre><code>class Array<br> def print_length<br> puts length<br> end<br>end<br></code></pre> <p>If you don't want to modify the whole class, you can just add the method to a single instance of the array, and no other arrays will have the method:</p> <pre><code>array = [1, 2, 3]<br>def array.print_length<br> puts length<br>end<br></code></pre> <p>Just be aware of the issues involved in using this feature. Jeff Atwood actually <a href="http://www.codinghorror.com/blog/archives/001151.html" rel="nofollow">wrote about it</a> not too long ago.</p>
-6
2008-08-04T02:36:40Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
2,982
<p>In Python, there is a difference between functions and bound methods.</p> <pre><code>&gt;&gt;&gt; def foo(): ... print "foo" ... &gt;&gt;&gt; class A: ... def bar( self ): ... print "bar" ... &gt;&gt;&gt; a = A() &gt;&gt;&gt; foo &lt;function foo at 0x00A98D70&gt; &gt;&gt;&gt; a.bar &lt;bound method A.bar of &lt;__main__.A instance at 0x00A9BC88&gt;&gt; &gt;&gt;&gt; </code></pre> <p>Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called.</p> <p>Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want:</p> <pre><code>&gt;&gt;&gt; def fooFighters( self ): ... print "fooFighters" ... &gt;&gt;&gt; A.fooFighters = fooFighters &gt;&gt;&gt; a2 = A() &gt;&gt;&gt; a2.fooFighters &lt;bound method A.fooFighters of &lt;__main__.A instance at 0x00A9BEB8&gt;&gt; &gt;&gt;&gt; a2.fooFighters() fooFighters </code></pre> <p>Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves):</p> <pre><code>&gt;&gt;&gt; a.fooFighters() fooFighters </code></pre> <p>The problem comes when you want to attach a method to a single instance:</p> <pre><code>&gt;&gt;&gt; def barFighters( self ): ... print "barFighters" ... &gt;&gt;&gt; a.barFighters = barFighters &gt;&gt;&gt; a.barFighters() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: barFighters() takes exactly 1 argument (0 given) </code></pre> <p>The function is not automatically bound when it's attached directly to an instance:</p> <pre><code>&gt;&gt;&gt; a.barFighters &lt;function barFighters at 0x00A98EF0&gt; </code></pre> <p>To bind it, we can use the <a href="http://docs.python.org/library/types.html?highlight=methodtype#module-types">MethodType function in the types module</a>:</p> <pre><code>&gt;&gt;&gt; import types &gt;&gt;&gt; a.barFighters = types.MethodType( barFighters, a ) &gt;&gt;&gt; a.barFighters &lt;bound method ?.barFighters of &lt;__main__.A instance at 0x00A9BC88&gt;&gt; &gt;&gt;&gt; a.barFighters() barFighters </code></pre> <p>This time other instances of the class have not been affected:</p> <pre><code>&gt;&gt;&gt; a2.barFighters() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: A instance has no attribute 'barFighters' </code></pre> <p>More information can be found by reading about <a href="http://users.rcn.com/python/download/Descriptor.htm">descriptors</a> and <a href="http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html">metaclass</a> <a href="http://www.gnosis.cx/publish/programming/metaclass_2.html">programming</a>.</p>
576
2008-08-06T00:33:35Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
4,600
<p>What you're looking for is <code>setattr</code> I believe. Use this to set an attribute on an object.</p> <pre><code>&gt;&gt;&gt; def printme(s): print repr(s)<br>&gt;&gt;&gt; class A: pass<br>&gt;&gt;&gt; setattr(A,'printme',printme)<br>&gt;&gt;&gt; a = A()<br>&gt;&gt;&gt; a.printme() # s becomes the implicit 'self' variable<br>&lt; __ main __ . A instance at 0xABCDEFG&gt;<br></code></pre>
4
2008-08-07T11:30:16Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
22,525
<p>What Jason Pratt posted is correct.</p> <pre><code>&gt;&gt;&gt; class Test(object): ... def a(self): ... pass ... &gt;&gt;&gt; def b(self): ... pass ... &gt;&gt;&gt; Test.b = b &gt;&gt;&gt; type(b) &lt;type 'function'&gt; &gt;&gt;&gt; type(Test.a) &lt;type 'instancemethod'&gt; &gt;&gt;&gt; type(Test.b) &lt;type 'instancemethod'&gt; </code></pre> <p>As you can see, Python doesn't consider b() any different than a(). In Python all methods are just variables that happen to be functions. </p>
3
2008-08-22T14:40:21Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
959,064
<p>Module <strong>new</strong> is deprecated since python 2.6 and removed in 3.0, use <strong>types</strong></p> <p>see <a href="http://docs.python.org/library/new.html">http://docs.python.org/library/new.html</a></p> <p>In the example below I've deliberately removed return value from <code>patch_me()</code> function. I think that giving return value may make one believe that patch returns a new object, which is not true - it modifies the incoming one. Probably this can facilitate a more disciplined use of monkeypatching.</p> <pre><code>import types class A(object):#but seems to work for old style objects too pass def patch_me(target): def method(target,x): print "x=",x print "called from", target target.method = types.MethodType(method,target) #add more if needed a = A() print a #out: &lt;__main__.A object at 0x2b73ac88bfd0&gt; patch_me(a) #patch instance a.method(5) #out: x= 5 #out: called from &lt;__main__.A object at 0x2b73ac88bfd0&gt; patch_me(A) A.method(6) #can patch class too #out: x= 6 #out: called from &lt;class '__main__.A'&gt; </code></pre>
66
2009-06-06T05:31:38Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
8,961,717
<p>I think that the above answers missed the key point. </p> <p>Let's have a class with a method:</p> <pre><code>class A(object): def m(self): pass </code></pre> <p>Now, let's play with it in ipython:</p> <pre><code>In [2]: A.m Out[2]: &lt;unbound method A.m&gt; </code></pre> <p>Ok, so <em>m()</em> somehow becomes an unbound method of <em>A</em>. But is it really like that?</p> <pre><code>In [5]: A.__dict__['m'] Out[5]: &lt;function m at 0xa66b8b4&gt; </code></pre> <p>It turns out that <em>m()</em> is just a function, reference to which is added to <em>A</em> class dictionary - there's no magic. Then why <em>A.m</em> gives us an unbound method? It's because the dot is not translated to a simple dictionary lookup. It's de facto a call of A.__class__.__getattribute__(A, 'm'):</p> <pre><code>In [11]: class MetaA(type): ....: def __getattribute__(self, attr_name): ....: print str(self), '-', attr_name In [12]: class A(object): ....: __metaclass__ = MetaA In [23]: A.m &lt;class '__main__.A'&gt; - m &lt;class '__main__.A'&gt; - m </code></pre> <p>Now, I'm not sure out of the top of my head why the last line is printed twice, but still it's clear what's going on there.</p> <p>Now, what the default __getattribute__ does is that it checks if the attribute is a so-called <a href="http://docs.python.org/reference/datamodel.html#implementing-descriptors" rel="nofollow">descriptor</a> or not, i.e. if it implements a special __get__ method. If it implements that method, then what is returned is the result of calling that __get__ method. Going back to the first version of our <em>A</em> class, this is what we have:</p> <pre><code>In [28]: A.__dict__['m'].__get__(None, A) Out[28]: &lt;unbound method A.m&gt; </code></pre> <p>And because Python functions implement the descriptor protocol, if they are called on behalf of an object, they bind themselves to that object in their __get__ method.</p> <p>Ok, so how to add a method to an existing object? Assuming you don't mind patching class, it's as simple as:</p> <pre><code>B.m = m </code></pre> <p>Then <em>B.m</em> "becomes" an unbound method, thanks to the descriptor magic.</p> <p>And if you want to add a method just to a single object, then you have to emulate the machinery yourself, by using types.MethodType:</p> <pre><code>b.m = types.MethodType(m, b) </code></pre> <p>By the way:</p> <pre><code>In [2]: A.m Out[2]: &lt;unbound method A.m&gt; In [59]: type(A.m) Out[59]: &lt;type 'instancemethod'&gt; In [60]: type(b.m) Out[60]: &lt;type 'instancemethod'&gt; In [61]: types.MethodType Out[61]: &lt;type 'instancemethod'&gt; </code></pre>
25
2012-01-22T14:20:54Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
9,041,763
<p>Consolidating Jason Pratt's and the community wiki answers, with a look at the results of different methods of binding:</p> <p>Especially note how adding the binding function as a class method <em>works</em>, but the referencing scope is incorrect.</p> <pre><code>#!/usr/bin/python -u import types import inspect ## dynamically adding methods to a unique instance of a class # get a list of a class's method type attributes def listattr(c): for m in [(n, v) for n, v in inspect.getmembers(c, inspect.ismethod) if isinstance(v,types.MethodType)]: print m[0], m[1] # externally bind a function as a method of an instance of a class def ADDMETHOD(c, method, name): c.__dict__[name] = types.MethodType(method, c) class C(): r = 10 # class attribute variable to test bound scope def __init__(self): pass #internally bind a function as a method of self's class -- note that this one has issues! def addmethod(self, method, name): self.__dict__[name] = types.MethodType( method, self.__class__ ) # predfined function to compare with def f0(self, x): print 'f0\tx = %d\tr = %d' % ( x, self.r) a = C() # created before modified instnace b = C() # modified instnace def f1(self, x): # bind internally print 'f1\tx = %d\tr = %d' % ( x, self.r ) def f2( self, x): # add to class instance's .__dict__ as method type print 'f2\tx = %d\tr = %d' % ( x, self.r ) def f3( self, x): # assign to class as method type print 'f3\tx = %d\tr = %d' % ( x, self.r ) def f4( self, x): # add to class instance's .__dict__ using a general function print 'f4\tx = %d\tr = %d' % ( x, self.r ) b.addmethod(f1, 'f1') b.__dict__['f2'] = types.MethodType( f2, b) b.f3 = types.MethodType( f3, b) ADDMETHOD(b, f4, 'f4') b.f0(0) # OUT: f0 x = 0 r = 10 b.f1(1) # OUT: f1 x = 1 r = 10 b.f2(2) # OUT: f2 x = 2 r = 10 b.f3(3) # OUT: f3 x = 3 r = 10 b.f4(4) # OUT: f4 x = 4 r = 10 k = 2 print 'changing b.r from {0} to {1}'.format(b.r, k) b.r = k print 'new b.r = {0}'.format(b.r) b.f0(0) # OUT: f0 x = 0 r = 2 b.f1(1) # OUT: f1 x = 1 r = 10 !!!!!!!!! b.f2(2) # OUT: f2 x = 2 r = 2 b.f3(3) # OUT: f3 x = 3 r = 2 b.f4(4) # OUT: f4 x = 4 r = 2 c = C() # created after modifying instance # let's have a look at each instance's method type attributes print '\nattributes of a:' listattr(a) # OUT: # attributes of a: # __init__ &lt;bound method C.__init__ of &lt;__main__.C instance at 0x000000000230FD88&gt;&gt; # addmethod &lt;bound method C.addmethod of &lt;__main__.C instance at 0x000000000230FD88&gt;&gt; # f0 &lt;bound method C.f0 of &lt;__main__.C instance at 0x000000000230FD88&gt;&gt; print '\nattributes of b:' listattr(b) # OUT: # attributes of b: # __init__ &lt;bound method C.__init__ of &lt;__main__.C instance at 0x000000000230FE08&gt;&gt; # addmethod &lt;bound method C.addmethod of &lt;__main__.C instance at 0x000000000230FE08&gt;&gt; # f0 &lt;bound method C.f0 of &lt;__main__.C instance at 0x000000000230FE08&gt;&gt; # f1 &lt;bound method ?.f1 of &lt;class __main__.C at 0x000000000237AB28&gt;&gt; # f2 &lt;bound method ?.f2 of &lt;__main__.C instance at 0x000000000230FE08&gt;&gt; # f3 &lt;bound method ?.f3 of &lt;__main__.C instance at 0x000000000230FE08&gt;&gt; # f4 &lt;bound method ?.f4 of &lt;__main__.C instance at 0x000000000230FE08&gt;&gt; print '\nattributes of c:' listattr(c) # OUT: # attributes of c: # __init__ &lt;bound method C.__init__ of &lt;__main__.C instance at 0x0000000002313108&gt;&gt; # addmethod &lt;bound method C.addmethod of &lt;__main__.C instance at 0x0000000002313108&gt;&gt; # f0 &lt;bound method C.f0 of &lt;__main__.C instance at 0x0000000002313108&gt;&gt; </code></pre> <p>Personally, I prefer the external ADDMETHOD function route, as it allows me to dynamically assign new method names within an iterator as well.</p> <pre><code>def y(self, x): pass d = C() for i in range(1,5): ADDMETHOD(d, y, 'f%d' % i) print '\nattributes of d:' listattr(d) # OUT: # attributes of d: # __init__ &lt;bound method C.__init__ of &lt;__main__.C instance at 0x0000000002303508&gt;&gt; # addmethod &lt;bound method C.addmethod of &lt;__main__.C instance at 0x0000000002303508&gt;&gt; # f0 &lt;bound method C.f0 of &lt;__main__.C instance at 0x0000000002303508&gt;&gt; # f1 &lt;bound method ?.y of &lt;__main__.C instance at 0x0000000002303508&gt;&gt; # f2 &lt;bound method ?.y of &lt;__main__.C instance at 0x0000000002303508&gt;&gt; # f3 &lt;bound method ?.y of &lt;__main__.C instance at 0x0000000002303508&gt;&gt; # f4 &lt;bound method ?.y of &lt;__main__.C instance at 0x0000000002303508&gt;&gt; </code></pre>
3
2012-01-28T00:12:05Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
9,636,303
<p>Since this question asked for non-Python versions, here's JavaScript:</p> <pre><code>a.methodname = function () { console.log("Yay, a new method!") } </code></pre>
4
2012-03-09T15:07:08Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
16,240,409
<p>There are at least two ways for attach a method to an instance without <code>types.MethodType</code>:</p> <pre><code>&gt;&gt;&gt; class A: ... def m(self): ... print 'im m, invoked with: ', self &gt;&gt;&gt; a = A() &gt;&gt;&gt; a.m() im m, invoked with: &lt;__main__.A instance at 0x973ec6c&gt; &gt;&gt;&gt; a.m &lt;bound method A.m of &lt;__main__.A instance at 0x973ec6c&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; def foo(firstargument): ... print 'im foo, invoked with: ', firstargument &gt;&gt;&gt; foo &lt;function foo at 0x978548c&gt; </code></pre> <p>1:</p> <pre><code>&gt;&gt;&gt; a.foo = foo.__get__(a, A) # or foo.__get__(a, type(a)) &gt;&gt;&gt; a.foo() im foo, invoked with: &lt;__main__.A instance at 0x973ec6c&gt; &gt;&gt;&gt; a.foo &lt;bound method A.foo of &lt;__main__.A instance at 0x973ec6c&gt;&gt; </code></pre> <p>2:</p> <pre><code>&gt;&gt;&gt; instancemethod = type(A.m) &gt;&gt;&gt; instancemethod &lt;type 'instancemethod'&gt; &gt;&gt;&gt; a.foo2 = instancemethod(foo, a, type(a)) &gt;&gt;&gt; a.foo2() im foo, invoked with: &lt;__main__.A instance at 0x973ec6c&gt; &gt;&gt;&gt; a.foo2 &lt;bound method instance.foo of &lt;__main__.A instance at 0x973ec6c&gt;&gt; </code></pre> <p>Useful links:<br> <a href="http://docs.python.org/2/reference/datamodel.html#invoking-descriptors">Data model - invoking descriptors</a><br> <a href="http://docs.python.org/2.7/howto/descriptor.html#invoking-descriptors">Descriptor HowTo Guide - invoking descriptors</a></p>
7
2013-04-26T15:47:35Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
18,434,150
<p>You guys should really look at <a href="http://github.com/clarete/forbiddenfruit" rel="nofollow">forbidden fruit</a>, it's a python library that provides support to monkey patching ANY python class, even strings.</p>
2
2013-08-25T21:56:46Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
24,748,849
<p>If it can be of any help, I recently released a Python library named Gorilla to make the process of monkey patching more convenient.</p> <p>Using a function <code>needle()</code> to patch a module named <code>guineapig</code> goes as follows:</p> <pre><code>import gorilla import guineapig @gorilla.patch(guineapig) def needle(): print("awesome") </code></pre> <p>But it also takes care of more interesting use cases as shown in the <a href="http://gorilla.readthedocs.org/en/latest/faq.html" rel="nofollow">FAQ</a> from the <a href="http://gorilla.readthedocs.org/" rel="nofollow">documentation</a>.</p> <p>The code is available on <a href="https://github.com/christophercrouzet/gorilla" rel="nofollow">GitHub</a>.</p>
1
2014-07-15T02:12:30Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
24,865,663
<p>You can use lambda to bind a method to an instance:</p> <pre><code>def run(self): print self._instanceString class A(object): def __init__(self): self._instanceString = "This is instance string" a = A() a.run = lambda: run(a) a.run() </code></pre> <p>This is instance string</p> <p>Process finished with exit code 0</p>
4
2014-07-21T12:55:54Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
28,060,251
<blockquote> <h1>Adding a Method to an Existing Object Instance</h1> <p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in python, I think this is called Monkey Patching (or in some cases Duck Punching). I understand that it's not always a good decision to do so. <strong>But, how might one do this?</strong></p> </blockquote> <h2>Yes, it is possible. (But not recommended.)</h2> <p>Since it's instructive, however, I'm going to show you three ways of doing this.</p> <p>Here's some setup code. We need a class definition. It could be imported, but it really doesn't matter.</p> <pre><code>class Foo(object): '''An empty class to demonstrate adding a method to an instance''' </code></pre> <p>Create an instance:</p> <pre><code>foo = Foo() </code></pre> <p>Create a method to add to it:</p> <pre><code>def sample_method(self, bar, baz): print(bar + baz) </code></pre> <h3>Method one - types.MethodType</h3> <p>First, import types, from which we'll get the method constructor:</p> <pre><code>import types </code></pre> <p>Now we add the method to the instance. To do this, we require the MethodType constructor from the <code>types</code> module (which we imported above).</p> <p>The argument signature for types.MethodType is <code>(function, instance, class)</code>:</p> <pre><code>foo.sample_method = types.MethodType(sample_method, foo, Foo) </code></pre> <p>and usage: </p> <pre><code>&gt;&gt;&gt; foo.sample_method(1,2) 3 </code></pre> <h2>Method two: lexical binding</h2> <p>First, we create a wrapper function that binds the method to the instance:</p> <pre><code>def bind(instance, method): def binding_scope_fn(*args, **kwargs): return method(instance, *args, **kwargs) return binding_scope_fn </code></pre> <p>usage:</p> <pre><code>&gt;&gt;&gt; foo.sample_method = bind(foo, sample_method) &gt;&gt;&gt; foo.sample_method(1,2) 3 </code></pre> <h2>Method three: functools.partial</h2> <pre><code>&gt;&gt;&gt; from functools import partial &gt;&gt;&gt; foo.sample_method = partial(sample_method, foo) &gt;&gt;&gt; foo.sample_method(1,2) 3 </code></pre> <p>This makes sense when you consider that bound methods are partial functions of the instance.</p> <h2>Unbound function as an object attribute - why this doesn't work:</h2> <p>If we try to add the sample_method in the same way as we might add it to the class, it is unbound from the instance, and doesn't take the implicit self as the first argument.</p> <pre><code>&gt;&gt;&gt; foo.sample_method = sample_method &gt;&gt;&gt; foo.sample_method(1,2) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: sample_method() takes exactly 3 arguments (2 given) </code></pre> <p>We can make the unbound function work by explicitly passing the instance (or anything, since this method doesn't actually use the <code>self</code> argument variable), but it would not be consistent with the expected signature of other instances (if we're monkey-patching this instance):</p> <pre><code>&gt;&gt;&gt; foo.sample_method(foo, 1, 2) 3 </code></pre> <hr> <h1>Disclaimer</h1> <p>Note, just because this is possible doesn't make it recommended. In fact, I suggest that you not do this unless you have a really good reason. It is far better to define the correct method in the class definition or less preferably to monkey-patch the class directly, like this:</p> <pre><code>Foo.sample_method = sample_method </code></pre>
10
2015-01-21T05:31:23Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
32,076,685
<h1>This is actually an addon to the answer of "Jason Pratt"</h1> <p>Although Jasons answer works, it does only work if one wants to add a function to a class. It did not work for me when I tried to reload an already existing method from the .py source code file.</p> <p>It took me for ages to find a workaround, but the trick seems simple... 1.st import the code from the source code file 2.nd force a reload 3.rd use types.FunctionType(...) to convert the imported and bound method to a function you can also pass on the current global variables, as the reloaded method would be in a different namespace 4.th now you can continue as suggested by "Jason Pratt" using the types.MethodType(...)</p> <p>Example:</p> <pre><code># this class resides inside ReloadCodeDemo.py class A: def bar( self ): print "bar1" def reloadCode(self, methodName): ''' use this function to reload any function of class A''' import types import ReloadCodeDemo as ReloadMod # import the code as module reload (ReloadMod) # force a reload of the module myM = getattr(ReloadMod.A,methodName) #get reloaded Method myTempFunc = types.FunctionType(# convert the method to a simple function myM.im_func.func_code, #the methods code globals(), # globals to use argdefs=myM.im_func.func_defaults # default values for variables if any ) myNewM = types.MethodType(myTempFunc,self,self.__class__) #convert the function to a method setattr(self,methodName,myNewM) # add the method to the function if __name__ == '__main__': a = A() a.bar() # now change your code and save the file a.reloadCode('bar') # reloads the file a.bar() # now executes the reloaded code </code></pre>
3
2015-08-18T15:32:47Z
[ "python", "oop", "methods", "monkeypatching" ]
Adding a Method to an Existing Object Instance
972
<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p> <p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p> <p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p> <p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p> <p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p> <p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
364
2008-08-04T02:17:51Z
34,404,761
<p>This question was opened years ago, but hey, there's an easy way to simulate the binding of a function to a class instance using decorators:</p> <pre><code>def binder (function, instance): copy_of_function = type (function) (function.func_code, {}) copy_of_function.__bind_to__ = instance def bound_function (*args, **kwargs): return copy_of_function (copy_of_function.__bind_to__, *args, **kwargs) return bound_function class SupaClass (object): def __init__ (self): self.supaAttribute = 42 def new_method (self): print self.supaAttribute supaInstance = SupaClass () supaInstance.supMethod = binder (new_method, supaInstance) otherInstance = SupaClass () otherInstance.supaAttribute = 72 otherInstance.supMethod = binder (new_method, otherInstance) otherInstance.supMethod () supaInstance.supMethod () </code></pre> <p>There, when you pass the function and the instance to the binder decorator, it will create a new function, with the same code object as the first one. Then, the given instance of the class is stored in an attribute of the newly created function. The decorator return a (third) function calling automatically the copied function, giving the instance as the first parameter. <br/> <br/> In conclusion you get a function simulating it's binding to the class instance. Letting the original function unchanged.</p>
1
2015-12-21T21:39:00Z
[ "python", "oop", "methods", "monkeypatching" ]
How do you express binary literals in Python?
1,476
<p>How do you express an integer as a binary number with Python literals?</p> <p>I was easily able to find the answer for hex:</p> <pre><code> &gt;&gt;&gt; 0x12AF 4783 &gt;&gt;&gt; 0x100 256 </code></pre> <p>and octal:</p> <pre><code> &gt;&gt;&gt; 01267 695 &gt;&gt;&gt; 0100 64 </code></pre> <p><strong>How do you use literals to express binary in Python?</strong></p> <hr> <p><strong><em>Summary of Answers</em></strong></p> <ul> <li>Python 2.5 and earlier: can express binary using <code>int('01010101111',2)</code> but not with a literal.</li> <li>Python 2.5 and earlier: there is <em>no way</em> to express binary literals.</li> <li>Python 2.6 beta: You can do like so: <code>0b1100111</code> or <code>0B1100111</code>.</li> <li>Python 2.6 beta: will also allow <code>0o27</code> or <code>0O27</code> (second character is the letter O) to represent an octal.</li> <li>Python 3.0 beta: Same as 2.6, but will no longer allow the older <code>027</code> syntax for octals.</li> </ul>
251
2008-08-04T18:20:36Z
1,478
<p>As far as I can tell Python, up through 2.5, only supports hexadecimal &amp; octal literals. I did find some discussions about adding binary to future versions but nothing definite.</p>
-1
2008-08-04T18:26:13Z
[ "python", "syntax", "binary", "integer", "literals" ]
How do you express binary literals in Python?
1,476
<p>How do you express an integer as a binary number with Python literals?</p> <p>I was easily able to find the answer for hex:</p> <pre><code> &gt;&gt;&gt; 0x12AF 4783 &gt;&gt;&gt; 0x100 256 </code></pre> <p>and octal:</p> <pre><code> &gt;&gt;&gt; 01267 695 &gt;&gt;&gt; 0100 64 </code></pre> <p><strong>How do you use literals to express binary in Python?</strong></p> <hr> <p><strong><em>Summary of Answers</em></strong></p> <ul> <li>Python 2.5 and earlier: can express binary using <code>int('01010101111',2)</code> but not with a literal.</li> <li>Python 2.5 and earlier: there is <em>no way</em> to express binary literals.</li> <li>Python 2.6 beta: You can do like so: <code>0b1100111</code> or <code>0B1100111</code>.</li> <li>Python 2.6 beta: will also allow <code>0o27</code> or <code>0O27</code> (second character is the letter O) to represent an octal.</li> <li>Python 3.0 beta: Same as 2.6, but will no longer allow the older <code>027</code> syntax for octals.</li> </ul>
251
2008-08-04T18:20:36Z
1,479
<p>I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct().</p> <p>EDIT: lbrandy's answer is correct in all cases.</p>
-1
2008-08-04T18:27:26Z
[ "python", "syntax", "binary", "integer", "literals" ]
How do you express binary literals in Python?
1,476
<p>How do you express an integer as a binary number with Python literals?</p> <p>I was easily able to find the answer for hex:</p> <pre><code> &gt;&gt;&gt; 0x12AF 4783 &gt;&gt;&gt; 0x100 256 </code></pre> <p>and octal:</p> <pre><code> &gt;&gt;&gt; 01267 695 &gt;&gt;&gt; 0100 64 </code></pre> <p><strong>How do you use literals to express binary in Python?</strong></p> <hr> <p><strong><em>Summary of Answers</em></strong></p> <ul> <li>Python 2.5 and earlier: can express binary using <code>int('01010101111',2)</code> but not with a literal.</li> <li>Python 2.5 and earlier: there is <em>no way</em> to express binary literals.</li> <li>Python 2.6 beta: You can do like so: <code>0b1100111</code> or <code>0B1100111</code>.</li> <li>Python 2.6 beta: will also allow <code>0o27</code> or <code>0O27</code> (second character is the letter O) to represent an octal.</li> <li>Python 3.0 beta: Same as 2.6, but will no longer allow the older <code>027</code> syntax for octals.</li> </ul>
251
2008-08-04T18:20:36Z
1,484
<pre><code>&gt;&gt;&gt; print int('01010101111',2) 687 &gt;&gt;&gt; print int('11111111',2) 255 </code></pre> <p>Another way.</p>
57
2008-08-04T18:34:45Z
[ "python", "syntax", "binary", "integer", "literals" ]
How do you express binary literals in Python?
1,476
<p>How do you express an integer as a binary number with Python literals?</p> <p>I was easily able to find the answer for hex:</p> <pre><code> &gt;&gt;&gt; 0x12AF 4783 &gt;&gt;&gt; 0x100 256 </code></pre> <p>and octal:</p> <pre><code> &gt;&gt;&gt; 01267 695 &gt;&gt;&gt; 0100 64 </code></pre> <p><strong>How do you use literals to express binary in Python?</strong></p> <hr> <p><strong><em>Summary of Answers</em></strong></p> <ul> <li>Python 2.5 and earlier: can express binary using <code>int('01010101111',2)</code> but not with a literal.</li> <li>Python 2.5 and earlier: there is <em>no way</em> to express binary literals.</li> <li>Python 2.6 beta: You can do like so: <code>0b1100111</code> or <code>0B1100111</code>.</li> <li>Python 2.6 beta: will also allow <code>0o27</code> or <code>0O27</code> (second character is the letter O) to represent an octal.</li> <li>Python 3.0 beta: Same as 2.6, but will no longer allow the older <code>027</code> syntax for octals.</li> </ul>
251
2008-08-04T18:20:36Z
13,107
<p>For reference&mdash;<em>future</em> Python possibilities:<br /> Starting with Python 2.6 you can express binary literals using the prefix <strong>0b</strong> or <strong>0B</strong>:</p> <pre><code>&gt;&gt;&gt; 0b101111 47 </code></pre> <p>You can also use the new <strong>bin</strong> function to get the binary representation of a number:</p> <pre><code>&gt;&gt;&gt; bin(173) '0b10101101' </code></pre> <p>Development version of the documentation: <a href="http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax">What's New in Python 2.6</a></p>
204
2008-08-16T12:35:36Z
[ "python", "syntax", "binary", "integer", "literals" ]
How do you express binary literals in Python?
1,476
<p>How do you express an integer as a binary number with Python literals?</p> <p>I was easily able to find the answer for hex:</p> <pre><code> &gt;&gt;&gt; 0x12AF 4783 &gt;&gt;&gt; 0x100 256 </code></pre> <p>and octal:</p> <pre><code> &gt;&gt;&gt; 01267 695 &gt;&gt;&gt; 0100 64 </code></pre> <p><strong>How do you use literals to express binary in Python?</strong></p> <hr> <p><strong><em>Summary of Answers</em></strong></p> <ul> <li>Python 2.5 and earlier: can express binary using <code>int('01010101111',2)</code> but not with a literal.</li> <li>Python 2.5 and earlier: there is <em>no way</em> to express binary literals.</li> <li>Python 2.6 beta: You can do like so: <code>0b1100111</code> or <code>0B1100111</code>.</li> <li>Python 2.6 beta: will also allow <code>0o27</code> or <code>0O27</code> (second character is the letter O) to represent an octal.</li> <li>Python 3.0 beta: Same as 2.6, but will no longer allow the older <code>027</code> syntax for octals.</li> </ul>
251
2008-08-04T18:20:36Z
37,226,387
<blockquote> <h1>How do you express binary literals in Python?</h1> </blockquote> <p>They're not "binary" literals, but rather, "integer literals". You can express integer literals with a binary format with a <code>0</code> followed by a <code>B</code> or <code>b</code> followed by a series of zeros and ones, for example:</p> <pre><code>&gt;&gt;&gt; 0b0010101010 170 &gt;&gt;&gt; 0B010101 21 </code></pre> <p>From the Python 3 <a href="https://docs.python.org/3/reference/lexical_analysis.html#integer-literals" rel="nofollow">docs</a>, these are the ways of providing integer literals in Python:</p> <blockquote> <p>Integer literals are described by the following lexical definitions:</p> <pre><code>integer ::= decimalinteger | octinteger | hexinteger | bininteger decimalinteger ::= nonzerodigit digit* | "0"+ nonzerodigit ::= "1"..."9" digit ::= "0"..."9" octinteger ::= "0" ("o" | "O") octdigit+ hexinteger ::= "0" ("x" | "X") hexdigit+ bininteger ::= "0" ("b" | "B") bindigit+ octdigit ::= "0"..."7" hexdigit ::= digit | "a"..."f" | "A"..."F" bindigit ::= "0" | "1" </code></pre> <p>There is no limit for the length of integer literals apart from what can be stored in available memory.</p> <p>Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0.</p> <p>Some examples of integer literals:</p> <pre><code>7 2147483647 0o177 0b100110111 3 79228162514264337593543950336 0o377 0xdeadbeef </code></pre> </blockquote> <h2>Other ways of expressing binary:</h2> <p>You can have the zeros and ones in a string object which can be manipulated (although you should probably just do bitwise operations on the integer in most cases) - just pass int the string of zeros and ones and the base you are converting from (2):</p> <pre><code>&gt;&gt;&gt; int('010101', 2) 21 </code></pre> <p>You can optionally have the <code>0b</code> or <code>0B</code> prefix:</p> <pre><code>&gt;&gt;&gt; int('0b0010101010', 2) 170 </code></pre> <p>If you pass it <code>0</code> as the base, it will assume base 10 if the string doesn't specify with a prefix:</p> <pre><code>&gt;&gt;&gt; int('10101', 0) 10101 &gt;&gt;&gt; int('0b10101', 0) 21 </code></pre> <h2>Converting from int back to human readable binary:</h2> <p>You can pass an integer to bin to see the string representation of a binary literal:</p> <pre><code>&gt;&gt;&gt; bin(21) '0b10101' </code></pre> <p>And you can combine <code>bin</code> and <code>int</code> to go back and forth:</p> <pre><code>&gt;&gt;&gt; bin(int('010101', 2)) '0b10101' </code></pre> <p>You can use a format specification as well, if you want to have minimum width with preceding zeros:</p> <pre><code>&gt;&gt;&gt; format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0)) '0000010101' &gt;&gt;&gt; format(int('010101', 2), '010b') '0000010101' </code></pre>
2
2016-05-14T11:58:03Z
[ "python", "syntax", "binary", "integer", "literals" ]
How do you express binary literals in Python?
1,476
<p>How do you express an integer as a binary number with Python literals?</p> <p>I was easily able to find the answer for hex:</p> <pre><code> &gt;&gt;&gt; 0x12AF 4783 &gt;&gt;&gt; 0x100 256 </code></pre> <p>and octal:</p> <pre><code> &gt;&gt;&gt; 01267 695 &gt;&gt;&gt; 0100 64 </code></pre> <p><strong>How do you use literals to express binary in Python?</strong></p> <hr> <p><strong><em>Summary of Answers</em></strong></p> <ul> <li>Python 2.5 and earlier: can express binary using <code>int('01010101111',2)</code> but not with a literal.</li> <li>Python 2.5 and earlier: there is <em>no way</em> to express binary literals.</li> <li>Python 2.6 beta: You can do like so: <code>0b1100111</code> or <code>0B1100111</code>.</li> <li>Python 2.6 beta: will also allow <code>0o27</code> or <code>0O27</code> (second character is the letter O) to represent an octal.</li> <li>Python 3.0 beta: Same as 2.6, but will no longer allow the older <code>027</code> syntax for octals.</li> </ul>
251
2008-08-04T18:20:36Z
37,955,839
<p>0 in the start here specifies that the base is 8 (not 10), which is pretty easy to see: </p> <pre><code>&gt;&gt;&gt; int('010101', 0) 4161 </code></pre> <p>If you don't start with a 0, then python assumes the number is base 10.</p> <pre><code>&gt;&gt;&gt; int('10101', 0) 10101 </code></pre>
0
2016-06-21T22:48:20Z
[ "python", "syntax", "binary", "integer", "literals" ]
Any experiences with Protocol Buffers?
1,734
<p>I was just looking through some information about Google's <a href="http://code.google.com/apis/protocolbuffers/">protocol buffers</a> data interchange format. Has anyone played around with the code or even created a project around it?</p> <p>I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data.</p>
20
2008-08-05T00:12:55Z
1,780
<P>If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea.</P> <P>Maybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a public facing api. Until then... <A href="http://en.wikipedia.org/wiki/JSON">JSON</A>?</P>
8
2008-08-05T01:14:30Z
[ "python", "xml", "database", "protocol-buffers" ]
Any experiences with Protocol Buffers?
1,734
<p>I was just looking through some information about Google's <a href="http://code.google.com/apis/protocolbuffers/">protocol buffers</a> data interchange format. Has anyone played around with the code or even created a project around it?</p> <p>I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data.</p>
20
2008-08-05T00:12:55Z
6,161
<p>Protocol buffers are intended to optimize communications between machines. They are really not intended for human interaction. Also, the format is binary, so it could not replace XML in that use case. </p> <p>I would also recommend <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> as being the most compact text-based format.</p>
10
2008-08-08T17:12:24Z
[ "python", "xml", "database", "protocol-buffers" ]
Any experiences with Protocol Buffers?
1,734
<p>I was just looking through some information about Google's <a href="http://code.google.com/apis/protocolbuffers/">protocol buffers</a> data interchange format. Has anyone played around with the code or even created a project around it?</p> <p>I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data.</p>
20
2008-08-05T00:12:55Z
123,093
<p>From your brief description, it sounds like protocol buffers is not the right fit. The phrase "structured content created by hand in a text editor" pretty much screams for XML.</p> <p>But if you want efficient, low latency communications with data structures that are not shared outside your organization, binary serialization such as protocol buffers can offer a huge win.</p>
3
2008-09-23T19:06:08Z
[ "python", "xml", "database", "protocol-buffers" ]
Any experiences with Protocol Buffers?
1,734
<p>I was just looking through some information about Google's <a href="http://code.google.com/apis/protocolbuffers/">protocol buffers</a> data interchange format. Has anyone played around with the code or even created a project around it?</p> <p>I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data.</p>
20
2008-08-05T00:12:55Z
1,418,610
<p>Another drawback of binary format like PB is that if there is a single bit of error, the entire data file is not parsable, but with JSON or XML, as the last resort you can still manually fix the error because it is human readable and has redundancy built-in..</p>
3
2009-09-13T19:15:23Z
[ "python", "xml", "database", "protocol-buffers" ]
How do I make a menu that does not require the user to press [enter] to make a selection?
1,829
<p>I've got a menu in Python. That part was easy. I'm using <code>raw_input()</code> to get the selection from the user. </p> <p>The problem is that <code>raw_input</code> (and input) require the user to press <kbd>Enter</kbd> after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:</p> <pre><code>import sys print """Menu 1) Say Foo 2) Say Bar""" answer = raw_input("Make a selection&gt; ") if "1" in answer: print "foo" elif "2" in answer: print "bar" </code></pre> <p>It would be great to have something like</p> <pre><code>print menu while lastKey = "": lastKey = check_for_recent_keystrokes() if "1" in lastKey: #do stuff... </code></pre>
12
2008-08-05T02:39:23Z
1,840
<p><strong>On Linux:</strong></p> <ul> <li>set raw mode</li> <li>select and read the keystroke</li> <li>restore normal settings</li> </ul> <pre> import sys import select import termios import tty def getkey(): old_settings = termios.tcgetattr(sys.stdin) tty.setraw(sys.stdin.fileno()) select.select([sys.stdin], [], [], 0) answer = sys.stdin.read(1) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) return answer print """Menu 1) Say Foo 2) Say Bar""" answer=getkey() if "1" in answer: print "foo" elif "2" in answer: print "bar" </pre>
8
2008-08-05T02:54:54Z
[ "python" ]
How do I make a menu that does not require the user to press [enter] to make a selection?
1,829
<p>I've got a menu in Python. That part was easy. I'm using <code>raw_input()</code> to get the selection from the user. </p> <p>The problem is that <code>raw_input</code> (and input) require the user to press <kbd>Enter</kbd> after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:</p> <pre><code>import sys print """Menu 1) Say Foo 2) Say Bar""" answer = raw_input("Make a selection&gt; ") if "1" in answer: print "foo" elif "2" in answer: print "bar" </code></pre> <p>It would be great to have something like</p> <pre><code>print menu while lastKey = "": lastKey = check_for_recent_keystrokes() if "1" in lastKey: #do stuff... </code></pre>
12
2008-08-05T02:39:23Z
1,852
<p><strong>On Windows:</strong></p> <pre><code>import msvcrt answer=msvcrt.getch() </code></pre>
6
2008-08-05T03:11:55Z
[ "python" ]
How do I make a menu that does not require the user to press [enter] to make a selection?
1,829
<p>I've got a menu in Python. That part was easy. I'm using <code>raw_input()</code> to get the selection from the user. </p> <p>The problem is that <code>raw_input</code> (and input) require the user to press <kbd>Enter</kbd> after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:</p> <pre><code>import sys print """Menu 1) Say Foo 2) Say Bar""" answer = raw_input("Make a selection&gt; ") if "1" in answer: print "foo" elif "2" in answer: print "bar" </code></pre> <p>It would be great to have something like</p> <pre><code>print menu while lastKey = "": lastKey = check_for_recent_keystrokes() if "1" in lastKey: #do stuff... </code></pre>
12
2008-08-05T02:39:23Z
1,870
<p>Wow, that took forever. Ok, here's what I've ended up with </p> <pre><code>#!C:\python25\python.exe<br>import msvcrt<br>print """Menu<br>1) Say Foo <br>2) Say Bar"""<br>while 1:<br> char = msvcrt.getch()<br> if char == chr(27): #escape<br> break<br> if char == "1":<br> print "foo"<br> break<br> if char == "2":<br> print "Bar"<br> break<br></code></pre> <p>It fails hard using IDLE, the python...thing...that comes with python. But once I tried it in DOS (er, CMD.exe), as a real program, then it ran fine.</p> <p>No one try it in IDLE, unless you have Task Manager handy.</p> <p>I've already forgotten how I lived with menus that arn't super-instant responsive.</p>
2
2008-08-05T03:51:57Z
[ "python" ]
How do I make a menu that does not require the user to press [enter] to make a selection?
1,829
<p>I've got a menu in Python. That part was easy. I'm using <code>raw_input()</code> to get the selection from the user. </p> <p>The problem is that <code>raw_input</code> (and input) require the user to press <kbd>Enter</kbd> after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:</p> <pre><code>import sys print """Menu 1) Say Foo 2) Say Bar""" answer = raw_input("Make a selection&gt; ") if "1" in answer: print "foo" elif "2" in answer: print "bar" </code></pre> <p>It would be great to have something like</p> <pre><code>print menu while lastKey = "": lastKey = check_for_recent_keystrokes() if "1" in lastKey: #do stuff... </code></pre>
12
2008-08-05T02:39:23Z
1,885
<p>The reason msvcrt fails in IDLE is because IDLE is not accessing the library that runs msvcrt. Whereas when you run the program natively in cmd.exe it works nicely. For the same reason that your program blows up on Mac and Linux terminals.</p> <p>But I guess if you're going to be using this specifically for windows, more power to ya.</p>
0
2008-08-05T04:28:03Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
1,857
<pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; print os.name posix &gt;&gt;&gt; import platform &gt;&gt;&gt; platform.system() 'Linux' &gt;&gt;&gt; platform.release() '2.6.22-15-generic' </code></pre> <p>See: <a href="https://docs.python.org/2/library/platform.html">platform — Access to underlying platform’s identifying data</a></p>
341
2008-08-05T03:27:03Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
1,871
<p>Dang -- lbrandy beat me to the punch, but that doesn't mean I can't provide you with the system results for Vista!</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.name 'nt' &gt;&gt;&gt; import platform &gt;&gt;&gt; platform.system() 'Windows' &gt;&gt;&gt; platform.release() 'Vista' </code></pre>
112
2008-08-05T03:57:22Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
1,879
<p>For the record here's the results on Mac:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.name 'posix' &gt;&gt;&gt; import platform &gt;&gt;&gt; platform.system() 'Darwin' &gt;&gt;&gt; platform.release() '8.11.1' </code></pre>
91
2008-08-05T04:13:53Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
28,426
<p>You can also use sys.platform if you already have imported sys and you don't want to import another module</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.platform 'linux2' </code></pre>
30
2008-08-26T15:41:50Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
553,500
<p>I do this</p> <pre><code>import sys print sys.platform </code></pre> <p>Docs here : <a href="http://docs.python.org/library/sys.html#sys.platform">sys.platform</a>. </p> <p>Everything you need is probably in the sys module.</p>
13
2009-02-16T14:43:18Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
3,021,004
<p>I am using the WLST tool that comes with weblogic, and it doesn't implement the platform package. </p> <pre><code>wls:/offline&gt; import os wls:/offline&gt; print os.name java wls:/offline&gt; import sys wls:/offline&gt; print sys.platform 'java1.5.0_11' </code></pre> <p>Apart from patching the system <em>javaos.py</em> (<a href="http://osdir.com/ml/lang.jython.devel/2006-08/msg00035.html" rel="nofollow">issue with os.system() on windows 2003 with jdk1.5</a>) (which I can't do, I have to use weblogic out of the box), this is what I use:</p> <pre><code>def iswindows(): os = java.lang.System.getProperty( "os.name" ) return "win" in os.lower() </code></pre>
7
2010-06-11T07:37:56Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
6,477,354
<pre><code>&gt;&gt;&gt; import platform &gt;&gt;&gt; platform.system() </code></pre>
7
2011-06-25T11:10:45Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
7,587,420
<p>in the same vein....</p> <pre><code>import platform is_windows=(platform.system().lower().find("win") &gt; -1) if(is_windows): lv_dll=LV_dll("my_so_dll.dll") else: lv_dll=LV_dll("./my_so_dll.so") </code></pre>
2
2011-09-28T17:54:43Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
7,707,465
<p>/usr/bin/python3.2</p> <pre><code>def cls(): from subprocess import call from platform import system os = system() if os == 'Linux': call('clear', shell = True) elif os == 'Windows': call('cls', shell = True) </code></pre>
3
2011-10-10T00:11:15Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
14,231,316
<p>For Jython the only way to get os name I found is to check <code>os.name</code> Java property (tried with <code>sys</code>, <code>os</code> and <code>platform</code> modules for Jython 2.5.3 on WinXP):</p> <pre><code>def get_os_platform(): """return platform name, but for Jython it uses os.name Java property""" ver = sys.platform.lower() if ver.startswith('java'): import java.lang ver = java.lang.System.getProperty("os.name").lower() print('platform: %s' % (ver)) return ver </code></pre>
5
2013-01-09T08:47:48Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
14,477,954
<p>A comparison between the different methods, and what they return on different operating systems can be found here: <a href="https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version">OS_flavor_name_version</a></p> <p>Methods that are compared:</p> <pre><code>import platform import sys def linux_distribution(): try: return platform.linux_distribution() except: return "N/A" print("""Python version: %s dist: %s linux_distribution: %s system: %s machine: %s platform: %s uname: %s version: %s mac_ver: %s """ % ( sys.version.split('\n'), str(platform.dist()), linux_distribution(), platform.system(), platform.machine(), platform.platform(), platform.uname(), platform.version(), platform.mac_ver(), )) </code></pre>
15
2013-01-23T10:55:26Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
14,885,455
<p>Interesting results on windows 8:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.name 'nt' &gt;&gt;&gt; import platform &gt;&gt;&gt; platform.system() 'Windows' &gt;&gt;&gt; platform.release() 'post2008Server' </code></pre> <p><strong>Edit:</strong> That's a <a href="http://bugs.python.org/issue16176" rel="nofollow">bug</a></p>
3
2013-02-14T22:44:56Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
15,674,751
<p>If you not looking for the kernel version etc, but looking for the linux distribution you may want to use the following </p> <p>in python2.6+ </p> <pre><code>&gt;&gt;&gt; import platform &gt;&gt;&gt; print platform.linux_distribution() ('CentOS Linux', '6.0', 'Final') &gt;&gt;&gt; print platform.linux_distribution()[0] CentOS Linux &gt;&gt;&gt; print platform.linux_distribution()[1] 6.0 </code></pre> <p>in python2.4</p> <pre><code>&gt;&gt;&gt; import platform &gt;&gt;&gt; print platform.dist() ('centos', '6.0', 'Final') &gt;&gt;&gt; print platform.dist()[0] centos &gt;&gt;&gt; print platform.dist()[1] 6.0 </code></pre> <p>Obviously, this will work only if you are running this on linux. If you want to have more generic script across platforms, you can mix this with code samples given in other answers.</p>
2
2013-03-28T05:19:17Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
25,863,224
<p>Sample code to differentiate OS's using python: </p> <pre><code>from sys import platform as _platform if _platform == "linux" or _platform == "linux2": # linux elif _platform == "darwin": # MAC OS X elif _platform == "win32": # Windows </code></pre>
35
2014-09-16T07:42:41Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
26,643,177
<p>Check the available tests with module platform and print the answer out for your system:</p> <pre><code>import platform print dir(platform) for x in dir(platform): if x[0].isalnum(): try: result = getattr(platform, x)() print "platform."+x+": "+result except TypeError: continue </code></pre>
0
2014-10-30T00:43:08Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
27,990,199
<p>try this:</p> <pre><code>import os os.uname() </code></pre> <p>and you can make it :</p> <pre><code>info=os.uname() info[0] info[1] </code></pre>
2
2015-01-16T18:13:11Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
31,296,120
<p>Watch out if you're on Windows with Cygwin where <code>os.name</code> is <code>posix</code>.</p> <pre><code>&gt;&gt;&gt; import os, platform &gt;&gt;&gt; print os.name posix &gt;&gt;&gt; print platform.system() CYGWIN_NT-6.3-WOW </code></pre>
2
2015-07-08T14:46:49Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
34,014,856
<p>Just for completeness, "OS" environment variable seems to be defined everywhere. On Windows XP/7/8/10 it is set to "Windows_NT". On Linux SuSE SP2 it is set to "x86-64 linux sles11[2]". I don't have access to OS-X or BSD machines, would be interesting to check there as well.</p> <pre><code>import os os_name = os.getenv("OS") if os_name == "Windows_NT": # Windows elif "linux" in os_name: # Linux elif ... </code></pre>
-4
2015-12-01T07:28:39Z
[ "python" ]
How to check what OS am I running on in Python?
1,854
<p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
270
2008-08-05T03:23:18Z
39,051,901
<p>You can also use only platform module without importing os module to get all the information.</p> <pre><code>&gt;&gt;&gt; import platform &gt;&gt;&gt; platform.os.name 'posix' &gt;&gt;&gt; platform.uname() ('Darwin', 'mainframe.local', '15.3.0', 'Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64', 'x86_64', 'i386') </code></pre> <p>A nice and tidy layout for reporting purpose can be achieved using this line:</p> <pre><code>for i in zip(['system','node','release','version','machine','processor'],platform.uname()):print i[0],':',i[1] </code></pre> <p>That gives this output:</p> <pre><code>system : Darwin node : mainframe.local release : 15.3.0 version : Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64 machine : x86_64 processor : i386 </code></pre> <p>What is missing usually is the operating system version but you should know if you are running windows, linux or mac a platform indipendent way is to use this test:</p> <pre><code>In []: for i in [platform.linux_distribution(),platform.mac_ver(),platform.win32_ver()]: ....: if i[0]: ....: print 'Version: ',i[0] </code></pre>
1
2016-08-20T08:03:03Z
[ "python" ]
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
1,983
<p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p> <p>When should I use one or the other, and why?</p>
31
2008-08-05T07:18:55Z
1,987
<p>The list [1,2,3] is dynamic and flexible but that flexibility comes at a speed cost.</p> <p>The tuple (1,2,3) is fixed (immutable) and therefore faster.</p>
19
2008-08-05T07:27:40Z
[ "python", "list", "tuples" ]
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
1,983
<p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p> <p>When should I use one or the other, and why?</p>
31
2008-08-05T07:18:55Z
2,277
<p>From the <a href="http://www.python.org/doc/faq/general/#why-are-there-separate-tuple-and-list-data-types">Python FAQ</a>:</p> <blockquote> <p>Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers.</p> <p>Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one.</p> </blockquote> <p>Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data.</p>
26
2008-08-05T13:22:43Z
[ "python", "list", "tuples" ]

Dataset Card for "stackoverflow_python"

Dataset Summary

This dataset comes originally from kaggle. It was originally split into three tables (CSV files) (Questions, Answers, and Tags) now merged into a single table. Each row corresponds to a pair (question-answer) and their associated tags.

The dataset contains all questions asked between August 2, 2008 and Ocotober 19, 2016.

Supported Tasks and Leaderboards

This might be useful for open-domain question-answering tasks.

Additional information

License

All Stack Overflow user contributions are licensed under CC-BY-SA 3.0 with attribution required.

Downloads last month
123
Edit dataset card

Models trained or fine-tuned on koutch/stackoverflow_python

Spaces using koutch/stackoverflow_python 4