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
Python variable scope error
370,357
<p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p> <pre><code>a, b, c = (1, 2, 3) print(a, b, c) def test(): print(a) print(b) print(c) # (A) #c+=1 # (B) test() </code></pre> <p>However, when I uncomment line <strong>(B)</strong>, I get an <em>UnboundLocalError: 'c' not assigned</em> at line <strong>(A)</strong>. The values of <em>a</em> and <em>b</em> are printed correctly. This has me completely baffled for two reasons:</p> <ol> <li><p>Why is there a runtime error thrown at line <strong>(A)</strong> because of a later statement on line <strong>(B)</strong>?</p></li> <li><p>Why are variables <em>a</em> and <em>b</em> printed as expected, while <em>c</em> raises an error?</p></li> </ol> <p>The only explanation I can come up with is that a <strong>local</strong> variable <em>c</em> is created by the assignment <code>c+=1</code>, which takes precedent over the "global" variable <em>c</em> even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.</p> <p>Could someone please explain this behavior?</p>
136
2008-12-16T03:06:52Z
24,035,261
<p>The best example that makes it clear is:</p> <pre><code>bar = 42 def foo(): print bar if False: bar = 0 </code></pre> <p>when calling <code>foo()</code> , this also <strong>raises</strong> <code>UnboundLocalError</code> although we will never reach to line <code>bar=0</code>, so logically local variable should never be created.</p> <p>The mystery lies in "<strong>Python is an Interpreted Language</strong>" and the declaration of the function <code>foo</code> is interpreted as a single statement (i.e. a compound statement), it just interprets it dumbly and creates local and global scopes. So <code>bar</code> is recognized in local scope before execution.</p> <p>For <strong>more examples</strong> like this Read this post: <a href="http://blog.amir.rachum.com/blog/2013/07/09/python-common-newbie-mistakes-part-2/" rel="nofollow">http://blog.amir.rachum.com/blog/2013/07/09/python-common-newbie-mistakes-part-2/</a></p> <p>This post provides a Complete Description and Analyses of the Python Scoping of variables:</p>
4
2014-06-04T10:39:21Z
[ "python", "variables", "scope" ]
Python variable scope error
370,357
<p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p> <pre><code>a, b, c = (1, 2, 3) print(a, b, c) def test(): print(a) print(b) print(c) # (A) #c+=1 # (B) test() </code></pre> <p>However, when I uncomment line <strong>(B)</strong>, I get an <em>UnboundLocalError: 'c' not assigned</em> at line <strong>(A)</strong>. The values of <em>a</em> and <em>b</em> are printed correctly. This has me completely baffled for two reasons:</p> <ol> <li><p>Why is there a runtime error thrown at line <strong>(A)</strong> because of a later statement on line <strong>(B)</strong>?</p></li> <li><p>Why are variables <em>a</em> and <em>b</em> printed as expected, while <em>c</em> raises an error?</p></li> </ol> <p>The only explanation I can come up with is that a <strong>local</strong> variable <em>c</em> is created by the assignment <code>c+=1</code>, which takes precedent over the "global" variable <em>c</em> even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.</p> <p>Could someone please explain this behavior?</p>
136
2008-12-16T03:06:52Z
34,153,129
<p>The best way to reach class variable is directly accesing by class name</p> <pre><code>class Employee: counter=0 def __init__(self): Employee.counter+=1 </code></pre>
0
2015-12-08T10:09:47Z
[ "python", "variables", "scope" ]
Differences between Python game libraries Pygame and Pyglet?
370,680
<p>I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days.</p> <p>How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use?</p> <p>Finally, would you say that one is more Pythonic than the other?</p>
33
2008-12-16T07:55:22Z
371,249
<p><strong>Pygame: LGPL license</strong></p> <p><em>Pyglet: BSD license</em></p> <p><strong>Pygame relies on SDL libraries heavily</strong></p> <p><em>Pyglet is a pure python library with fewer dependencies, I think it requires better understanding of OpenGL</em></p> <p><strong>Pygame is around here for a long time, a lot of people used it</strong></p> <p><em>Pyglet is a new lib</em></p> <p><strong>Pygame is geared towards game development (cursors, sprites, joystick/gamepad support)</strong></p> <p><em>Pyglet is more general purpose (though it has a Sprite class)</em></p> <p>I found also this discussion on pyglet-users mailing list: <a href="http://www.mail-archive.com/[email protected]/msg00482.html">from pygame+pyopengl to pyglet</a></p> <p>Disclaimer: I did not use either yet, only tried some tutorials ;-)</p>
25
2008-12-16T13:08:52Z
[ "python", "pygame", "pyglet" ]
Differences between Python game libraries Pygame and Pyglet?
370,680
<p>I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days.</p> <p>How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use?</p> <p>Finally, would you say that one is more Pythonic than the other?</p>
33
2008-12-16T07:55:22Z
397,025
<p>I was considering both Pygame and Pyglet for a small 2D shooter, and after looking at source code and some tutorials went with Pyglet. I was very happy with the results.</p> <p>Pyglet worked immediately and was enjoyable to work with, and conceptually very clean. It certainly had a Pythonic feel to me: you could get a straightforward and readable example going very quickly, and it uses decorators to good effect for event handling. It also didn't force a particular program structure, which made it easy for me to mix in the physics modelling of Pymunk (<a href="http://code.google.com/p/pymunk/">http://code.google.com/p/pymunk/</a>). </p> <p>While it is based on OpenGL and you can use those features for special effects, I was able to do just fine without any knowledge of them.</p> <p>It also works well with py2exe and py2app, which is important because a lot of people do not have a Python interpreter installed.</p> <p>On the downside, there is less information about it on the web because it is newer, as well as fewer sample games to look at. </p> <p>Also, it changed quite a bit from previous versions, so some of the tutorials which are there are now out of date (there is the "new style event loop" and the Sprite class as major additions.)</p> <p>I would recommend downloading the examples (there is a nice Asteroids clone called Astraea included) and seeing if you like the style. </p>
21
2008-12-29T02:40:06Z
[ "python", "pygame", "pyglet" ]
Differences between Python game libraries Pygame and Pyglet?
370,680
<p>I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days.</p> <p>How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use?</p> <p>Finally, would you say that one is more Pythonic than the other?</p>
33
2008-12-16T07:55:22Z
414,112
<p>I would like to add that there is a fast sprite library <a href="http://arcticpaint.com/projects/rabbyt/" rel="nofollow">Rabbyt</a> which may be a good complement for Pyglet.</p>
5
2009-01-05T18:59:37Z
[ "python", "pygame", "pyglet" ]
Differences between Python game libraries Pygame and Pyglet?
370,680
<p>I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days.</p> <p>How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use?</p> <p>Finally, would you say that one is more Pythonic than the other?</p>
33
2008-12-16T07:55:22Z
2,477,829
<p>Having looked at both pygame and pyglet I found pyglet easier to pick up and was able to write a simple breakout style game within a few days.</p>
2
2010-03-19T14:00:39Z
[ "python", "pygame", "pyglet" ]
Differences between Python game libraries Pygame and Pyglet?
370,680
<p>I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days.</p> <p>How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use?</p> <p>Finally, would you say that one is more Pythonic than the other?</p>
33
2008-12-16T07:55:22Z
4,520,448
<p>Pyglet is good (for 2D games) if you never intend to draw any vector graphics or primitives within the game itself, and just stick to loading images from disk. It's also much cleaner because there's no need to write you're own game loop and have to worry about speed and timing and responsiveness.</p> <p>However, if you ever have to generate graphics on-the-fly, and then save them, either as a variable or as a file, then pyglet becomes considerably more complicated because you start having to muck around with the low-level OpenGL functions. In those scenarios, pygame is much more user-friendly, with it's software rendering and Surface class. Or you could use Python Imaging Library and interface it with pyglet.</p> <p>Obviously, for 3D games, you're going to have to muck around with OpenGL functions anyway, in which case I recommend pyglet over pygame + PyOpenGL.</p>
9
2010-12-23T16:08:56Z
[ "python", "pygame", "pyglet" ]
Trac documentation?
370,733
<p>I'm trying to write my first little plugin for <a href="http://trac.edgewall.org">Trac</a> and am kind of lost as to what the API exactly is. For example, exactly which fields are offered for "ticket" objects, among many other things.</p> <p>Does anyone know of a good place to look for Trac API documentation? Can't find anything on the web site but maybe I'm just looking wrong...</p>
12
2008-12-16T08:50:10Z
370,743
<p><a href="http://trac.edgewall.org/wiki/TracDev/ComponentArchitecture" rel="nofollow">http://trac.edgewall.org/wiki/TracDev/ComponentArchitecture</a> is a start.</p>
4
2008-12-16T08:55:55Z
[ "python", "documentation", "trac" ]
Trac documentation?
370,733
<p>I'm trying to write my first little plugin for <a href="http://trac.edgewall.org">Trac</a> and am kind of lost as to what the API exactly is. For example, exactly which fields are offered for "ticket" objects, among many other things.</p> <p>Does anyone know of a good place to look for Trac API documentation? Can't find anything on the web site but maybe I'm just looking wrong...</p>
12
2008-12-16T08:50:10Z
370,755
<p>The component architecture is important, but the real starting page for development is: <a href="http://trac.edgewall.org/wiki/TracDev">http://trac.edgewall.org/wiki/TracDev</a></p> <p>Have also a look at the trac-hacks web site <a href="http://trac-hacks.org/">http://trac-hacks.org/</a> This is really a good source of examples, and many times you will find something close to what you want to do, that you can simply adapt from.</p> <p>Think also about installing this development plugin: <a href="http://trac-hacks.org/wiki/TracDeveloperPlugin">http://trac-hacks.org/wiki/TracDeveloperPlugin</a> It makes it much easier to debug your plugin with it</p>
11
2008-12-16T08:58:33Z
[ "python", "documentation", "trac" ]
Trac documentation?
370,733
<p>I'm trying to write my first little plugin for <a href="http://trac.edgewall.org">Trac</a> and am kind of lost as to what the API exactly is. For example, exactly which fields are offered for "ticket" objects, among many other things.</p> <p>Does anyone know of a good place to look for Trac API documentation? Can't find anything on the web site but maybe I'm just looking wrong...</p>
12
2008-12-16T08:50:10Z
370,759
<p>It's all in Trac's Trac!</p> <p>The pages on <a href="http://trac.edgewall.org/wiki/TracDev/PluginDevelopment">plugin development</a> and the <a href="http://trac.edgewall.org/wiki/TracDev/ComponentArchitecture">component architecture</a> give a good overview. Unfortunately, I can't find any API documentation. Your best bet is to 'use the source'. Check out the <a href="http://trac.edgewall.org/browser/trunk/trac/ticket/model.py">Ticket.py</a> file for the Ticket class. If you would rather query the database directly, look at the <a href="http://trac.edgewall.org/wiki/TracDev/DatabaseSchema">database schema</a>.</p>
5
2008-12-16T09:03:41Z
[ "python", "documentation", "trac" ]
Trac documentation?
370,733
<p>I'm trying to write my first little plugin for <a href="http://trac.edgewall.org">Trac</a> and am kind of lost as to what the API exactly is. For example, exactly which fields are offered for "ticket" objects, among many other things.</p> <p>Does anyone know of a good place to look for Trac API documentation? Can't find anything on the web site but maybe I'm just looking wrong...</p>
12
2008-12-16T08:50:10Z
377,004
<p>Each component of Trac has an api.py that's loaded with docstrings on all the interfaces you can implement. I've found them to be extremely valuable when implementing my own plugins.</p> <p>For example:</p> <p><a href="http://trac.edgewall.org/browser/trunk/trac/ticket/api.py" rel="nofollow">http://trac.edgewall.org/browser/trunk/trac/ticket/api.py</a></p> <p>or</p> <p><a href="http://trac.edgewall.org/browser/trunk/trac/wiki/api.py" rel="nofollow">http://trac.edgewall.org/browser/trunk/trac/wiki/api.py</a></p> <p>are two API's I've often used. Another thing I often do is look for existing plugins on <a href="http://www.trachacks.org" rel="nofollow">TracHacks</a> which implement features I'd like in my plugin and just rip out the useful bits of those.</p>
4
2008-12-18T05:47:30Z
[ "python", "documentation", "trac" ]
Trac documentation?
370,733
<p>I'm trying to write my first little plugin for <a href="http://trac.edgewall.org">Trac</a> and am kind of lost as to what the API exactly is. For example, exactly which fields are offered for "ticket" objects, among many other things.</p> <p>Does anyone know of a good place to look for Trac API documentation? Can't find anything on the web site but maybe I'm just looking wrong...</p>
12
2008-12-16T08:50:10Z
4,889,232
<p>I know this is way late and you probably found your answer by now, but for anyone else who ends up here looking for the same thing, the API is online on the Trac website at <a href="http://www.edgewall.org/docs/tags-trac-0.12/epydoc/" rel="nofollow">http://www.edgewall.org/docs/tags-trac-0.12/epydoc/</a> (for 0.12).</p>
3
2011-02-03T17:06:50Z
[ "python", "documentation", "trac" ]
Has anyone tried NetBeans 6.5 Python IDE?
371,037
<p>Has anyone tried the <a href="http://en.wikipedia.org/wiki/NetBeans#Other%5FNetBeans%5FIDE%5FBundles" rel="nofollow">NetBeans 6.5 Python IDE</a>?</p> <p>What are your opinions? Is it better/worse than <a href="http://en.wikipedia.org/wiki/PyDev" rel="nofollow">PyDev</a>? Do you like it? How does it integrate with source control tools (especially <a href="http://en.wikipedia.org/wiki/Mercurial" rel="nofollow">Mercurial</a>)?</p>
14
2008-12-16T11:23:32Z
371,314
<p>Compared to pydev, I found it very, very slow, and it crashed (once) when I created a project from existing sources. It's still beta, though.</p> <p>Integration with SCMs will be as good as netbeans is already (I only tried subversion, which worked fine).</p> <p>Feature-wise it was about the same : refactor, debugging, code assist... I'll stick with pydev for the moment, which is IMHO a great tool.</p>
2
2008-12-16T13:32:23Z
[ "python", "ide", "netbeans" ]
Has anyone tried NetBeans 6.5 Python IDE?
371,037
<p>Has anyone tried the <a href="http://en.wikipedia.org/wiki/NetBeans#Other%5FNetBeans%5FIDE%5FBundles" rel="nofollow">NetBeans 6.5 Python IDE</a>?</p> <p>What are your opinions? Is it better/worse than <a href="http://en.wikipedia.org/wiki/PyDev" rel="nofollow">PyDev</a>? Do you like it? How does it integrate with source control tools (especially <a href="http://en.wikipedia.org/wiki/Mercurial" rel="nofollow">Mercurial</a>)?</p>
14
2008-12-16T11:23:32Z
371,438
<p>Sun use Mercurial internally now, so expect that their IDE support for it will be top notch.</p>
2
2008-12-16T14:20:28Z
[ "python", "ide", "netbeans" ]
Has anyone tried NetBeans 6.5 Python IDE?
371,037
<p>Has anyone tried the <a href="http://en.wikipedia.org/wiki/NetBeans#Other%5FNetBeans%5FIDE%5FBundles" rel="nofollow">NetBeans 6.5 Python IDE</a>?</p> <p>What are your opinions? Is it better/worse than <a href="http://en.wikipedia.org/wiki/PyDev" rel="nofollow">PyDev</a>? Do you like it? How does it integrate with source control tools (especially <a href="http://en.wikipedia.org/wiki/Mercurial" rel="nofollow">Mercurial</a>)?</p>
14
2008-12-16T11:23:32Z
371,600
<p>I started using it a little while back and I like it. I usually develop in a simple editor (SciTE), NetBeans is nice to organize larger projects.</p> <p><a href="http://coreygoldberg.blogspot.com/2008/12/python-trying-out-netbeans-ide.html" rel="nofollow">wrote about it briefly here</a></p>
1
2008-12-16T15:08:08Z
[ "python", "ide", "netbeans" ]
Has anyone tried NetBeans 6.5 Python IDE?
371,037
<p>Has anyone tried the <a href="http://en.wikipedia.org/wiki/NetBeans#Other%5FNetBeans%5FIDE%5FBundles" rel="nofollow">NetBeans 6.5 Python IDE</a>?</p> <p>What are your opinions? Is it better/worse than <a href="http://en.wikipedia.org/wiki/PyDev" rel="nofollow">PyDev</a>? Do you like it? How does it integrate with source control tools (especially <a href="http://en.wikipedia.org/wiki/Mercurial" rel="nofollow">Mercurial</a>)?</p>
14
2008-12-16T11:23:32Z
376,922
<p>BraveSirFoobar, it would be nice to know more about what problems you found -- the very, very slow part, as well as the crash. The first time you run the IDE it will index information about your Python platform and project and libraries - such that it can do quick code completion, go to declaration etc. later - but once that's done it's not supposed to be slow - but there might be bugs.</p> <p>Mercurial should definitely be supported well, since the NetBeans project itself (and Solaris and Java) are all hosted in Mercurial repositories.</p> <p>We plan to have really deep support for Python, much in the style of our Ruby support. One of the things which really helped in our Ruby work was the feedback from our early adopters, so if you try Python and have issues with it, please let us know so we can fix it. (Feedback links here: <a href="http://wiki.netbeans.org/Python" rel="nofollow">http://wiki.netbeans.org/Python</a> )</p> <p>-- Tor</p>
4
2008-12-18T04:39:53Z
[ "python", "ide", "netbeans" ]
Has anyone tried NetBeans 6.5 Python IDE?
371,037
<p>Has anyone tried the <a href="http://en.wikipedia.org/wiki/NetBeans#Other%5FNetBeans%5FIDE%5FBundles" rel="nofollow">NetBeans 6.5 Python IDE</a>?</p> <p>What are your opinions? Is it better/worse than <a href="http://en.wikipedia.org/wiki/PyDev" rel="nofollow">PyDev</a>? Do you like it? How does it integrate with source control tools (especially <a href="http://en.wikipedia.org/wiki/Mercurial" rel="nofollow">Mercurial</a>)?</p>
14
2008-12-16T11:23:32Z
416,219
<p>I will share some of the feelings from using it for quite a while now. Things that are roughly the same quality as in Eclipse+Pydev+mercurial:</p> <ol> <li>editor, code-completion</li> <li>debugger features</li> </ol> <p>Things that are better:</p> <ol> <li>autoimport</li> <li>color schemes (Norway today rocks)</li> <li>Mercurial support (though it is getting better and better in Eclipse)</li> </ol> <p>Things that are worse:</p> <ol> <li>zipped egg packages are not recognized for either code completion or the autoimport</li> <li>libdyn packages (e.g. datetime) are not recognized</li> <li>debugger is having trouble with multiprocessing package</li> <li>you cannot choose file from outside of the project (/usr/bin/paster) to be the main file (this is what I use to debug <a href="http://en.wikipedia.org/wiki/Pylons%5F%28web%5Fframework%29" rel="nofollow">Pylons</a> applications)</li> </ol> <p>Does anyone have something to add to the list?</p>
5
2009-01-06T11:43:39Z
[ "python", "ide", "netbeans" ]
Has anyone tried NetBeans 6.5 Python IDE?
371,037
<p>Has anyone tried the <a href="http://en.wikipedia.org/wiki/NetBeans#Other%5FNetBeans%5FIDE%5FBundles" rel="nofollow">NetBeans 6.5 Python IDE</a>?</p> <p>What are your opinions? Is it better/worse than <a href="http://en.wikipedia.org/wiki/PyDev" rel="nofollow">PyDev</a>? Do you like it? How does it integrate with source control tools (especially <a href="http://en.wikipedia.org/wiki/Mercurial" rel="nofollow">Mercurial</a>)?</p>
14
2008-12-16T11:23:32Z
478,975
<p>After looking at this, I decided to go ahead with PyDev than NetBeans.</p> <p>However best wishes to NetBeans team for a faster and better Python support. Cant wait for that :)</p>
0
2009-01-26T06:22:50Z
[ "python", "ide", "netbeans" ]
Has anyone tried NetBeans 6.5 Python IDE?
371,037
<p>Has anyone tried the <a href="http://en.wikipedia.org/wiki/NetBeans#Other%5FNetBeans%5FIDE%5FBundles" rel="nofollow">NetBeans 6.5 Python IDE</a>?</p> <p>What are your opinions? Is it better/worse than <a href="http://en.wikipedia.org/wiki/PyDev" rel="nofollow">PyDev</a>? Do you like it? How does it integrate with source control tools (especially <a href="http://en.wikipedia.org/wiki/Mercurial" rel="nofollow">Mercurial</a>)?</p>
14
2008-12-16T11:23:32Z
971,730
<p>How does it compare with PyDev Extensions? I've recently installed it and, to be honest, couldn't imagine myself going back to PyDev.</p> <p>NetBeans seems interesting though, if only I wasn't already hooked onto a couple of other Eclipse plug-ins as well.</p>
0
2009-06-09T18:28:32Z
[ "python", "ide", "netbeans" ]
Has anyone tried NetBeans 6.5 Python IDE?
371,037
<p>Has anyone tried the <a href="http://en.wikipedia.org/wiki/NetBeans#Other%5FNetBeans%5FIDE%5FBundles" rel="nofollow">NetBeans 6.5 Python IDE</a>?</p> <p>What are your opinions? Is it better/worse than <a href="http://en.wikipedia.org/wiki/PyDev" rel="nofollow">PyDev</a>? Do you like it? How does it integrate with source control tools (especially <a href="http://en.wikipedia.org/wiki/Mercurial" rel="nofollow">Mercurial</a>)?</p>
14
2008-12-16T11:23:32Z
1,068,597
<p>Having worked with PyDev and PyDev extension for Eclipse for the past few months, the move to NetBeans has been a very pleasurable one.</p> <p>Without having to hunt all the different plug-ins for PyDev and Eclipse, NetBeans had everything I needed out of the box: auto completion, super fast index search, style control import control, you name it. And it seemed LESS bug prone than Eclipse (which is pretty stable). Also, the built-in Vim like auto code snippets it uses are just fantastic. IMO, it beats Eclipse hands down.</p> <p>I'm hooked.</p>
2
2009-07-01T11:26:38Z
[ "python", "ide", "netbeans" ]
String conversion in Python
371,155
<p>I'm using Python 2.5. The DLL I imported is created using the CLR. The DLL function is returning a string. I'm trying to apply "partition" attribute to it. I'm not able to do it. Even the partition is not working. I think "all strings returned from CLR are returned as Unicode".</p>
-3
2008-12-16T12:27:53Z
371,200
<p>Could you post your error message? Could you post what type of object you have (<code>type(yourvar)</code>)?</p> <p>Please check if you have a <code>partition(sep)</code> method for this object (<code>dir(yourvar)</code>).</p> <p>Applying <code>partition</code> method should look like:</p> <pre><code>&gt;&gt;&gt; us=u"Привет, Unicode String!" &gt;&gt;&gt; us.partition(' ') (u'\u041f\u0440\u0438\u0432\u0435\u0442,', u' ', u'Unicode String!') </code></pre> <p>You can also try <code>split</code> function instead of <code>partition</code>:</p> <pre><code>&gt;&gt;&gt; from string import split &gt;&gt;&gt; split(us,' ',1) [u'\u041f\u0440\u0438\u0432\u0435\u0442,', u'Unicode String!'] </code></pre>
2
2008-12-16T12:46:24Z
[ "python", "clr" ]
String conversion in Python
371,155
<p>I'm using Python 2.5. The DLL I imported is created using the CLR. The DLL function is returning a string. I'm trying to apply "partition" attribute to it. I'm not able to do it. Even the partition is not working. I think "all strings returned from CLR are returned as Unicode".</p>
-3
2008-12-16T12:27:53Z
371,201
<p>If by <em>CLR</em> you mean <a href="http://msdn.microsoft.com/en-us/library/ddk909ch.aspx" rel="nofollow">.NET CLR</a>, try using <a href="http://www.codeplex.com/IronPython" rel="nofollow">IronPython</a> :</p> <blockquote> <p>IronPython is a new implementation of the Python programming language running on .NET. It supports an interactive console with fully dynamic compilation. It is well integrated with the rest of the .NET Framework and makes all .NET libraries easily available to Python programmers, while maintaining full compatibility with the Python language.</p> </blockquote> <p>In IronPython, loading (importing) and calling a .NET dll is well documented and straight forward.</p>
1
2008-12-16T12:46:26Z
[ "python", "clr" ]
What's the most pythonic way of testing that inputs are well-formed numbers
371,419
<p>I have a function that expects real numbers (either integers or floats) as its input, and I'm trying to validate this input before doing mathematical operations on it.</p> <p>My first instinct is to cast inputs as floats from within a try-except block.</p> <pre><code>try: myinput = float(input) except: raise ValueError("input is not a well-formed number") </code></pre> <p>I could also call <code>isinstance(mydata, (float, int, long) )</code> but the list of "all these could be numbers" seems a bit inelegant to me.</p> <p>What's the most pythonic way of going about it? Is there another option I overlooked?</p>
2
2008-12-16T14:15:10Z
371,436
<p>Maybe you can use a combination of <code>assert</code> and <code>isinstance</code> statements. Something like the following is I think a more pythonic way, as you throw an exception whenever your inputs don't follow your requirements. Unfortunately I don't see any better definition of what is a valid number than yours. Maybe someone will come with a better idea.</p> <pre><code>number = (float, int, long) assert isinstance(mydata, (float, int, long)) </code></pre>
2
2008-12-16T14:19:43Z
[ "python", "idioms" ]
What's the most pythonic way of testing that inputs are well-formed numbers
371,419
<p>I have a function that expects real numbers (either integers or floats) as its input, and I'm trying to validate this input before doing mathematical operations on it.</p> <p>My first instinct is to cast inputs as floats from within a try-except block.</p> <pre><code>try: myinput = float(input) except: raise ValueError("input is not a well-formed number") </code></pre> <p>I could also call <code>isinstance(mydata, (float, int, long) )</code> but the list of "all these could be numbers" seems a bit inelegant to me.</p> <p>What's the most pythonic way of going about it? Is there another option I overlooked?</p>
2
2008-12-16T14:15:10Z
371,461
<p>To quote myself from <a href="http://stackoverflow.com/questions/367560/how-much-input-validation-should-i-be-doing-on-my-python-functionsmethods#368072">How much input validation should I be doing on my python functions/methods?</a>:</p> <blockquote> <p>For calculations like sum, factorial etc, pythons built-in type checks will do fine. The calculations will end upp calling add, mul etc for the types, and if they break, they will throw the correct exception anyway. By enforcing your own checks, you may invalidate otherwise working input.</p> </blockquote> <p>Thus, the best option is to leave the type checking up to Python. If the calculation fails, Python's type checking will give an exception, so if you do it yourself, you just duplicate code which means more work on your behalf.</p>
12
2008-12-16T14:26:45Z
[ "python", "idioms" ]
What's the most pythonic way of testing that inputs are well-formed numbers
371,419
<p>I have a function that expects real numbers (either integers or floats) as its input, and I'm trying to validate this input before doing mathematical operations on it.</p> <p>My first instinct is to cast inputs as floats from within a try-except block.</p> <pre><code>try: myinput = float(input) except: raise ValueError("input is not a well-formed number") </code></pre> <p>I could also call <code>isinstance(mydata, (float, int, long) )</code> but the list of "all these could be numbers" seems a bit inelegant to me.</p> <p>What's the most pythonic way of going about it? Is there another option I overlooked?</p>
2
2008-12-16T14:15:10Z
371,573
<p>In Python 2.6 and 3.0, a type hierarchy of numeric abstract data types has been <a href="http://www.python.org/dev/peps/pep-3141/" rel="nofollow">added</a>, so you could perform your check as:</p> <pre><code>&gt;&gt;&gt; import numbers &gt;&gt;&gt; isValid = isinstance(myinput , numbers.Real) </code></pre> <p>numbers.Real will match integral or float type, but not non-numeric types, or complex numbers (use numbers.Complex for that). It'll also match rational numbers , but presumably you'd want to include those as well. ie:</p> <pre><code>&gt;&gt;&gt; [isinstance(x, numbers.Real) for x in [4, 4.5, "some string", 3+2j]] [True, True, False, False] </code></pre> <p>Unfortunately, this is all in Python >=2.6, so won't be useful if you're developing for 2.5 or earlier.</p>
5
2008-12-16T14:58:08Z
[ "python", "idioms" ]
What's the most pythonic way of testing that inputs are well-formed numbers
371,419
<p>I have a function that expects real numbers (either integers or floats) as its input, and I'm trying to validate this input before doing mathematical operations on it.</p> <p>My first instinct is to cast inputs as floats from within a try-except block.</p> <pre><code>try: myinput = float(input) except: raise ValueError("input is not a well-formed number") </code></pre> <p>I could also call <code>isinstance(mydata, (float, int, long) )</code> but the list of "all these could be numbers" seems a bit inelegant to me.</p> <p>What's the most pythonic way of going about it? Is there another option I overlooked?</p>
2
2008-12-16T14:15:10Z
372,346
<p>I don't get the question.</p> <p>There are two things with wildly different semantics tossed around as "alternatives".</p> <p>A type conversion is one thing. It works with any object that supports <code>__float__</code>, which can be quite a variety of objects, few of which are actually numeric.</p> <pre><code>try: myinput = float(input) except: raise ValueError("input is not a well-formed number") # at this point, input may not be numeric at all # it may, however, have produced a numeric value </code></pre> <p>A type test is another thing. This works only with objects that are proper instances of a specific set of classes.</p> <pre><code>isinstance(input, (float, int, long) ) # at this point, input is one of a known list of numeric types </code></pre> <p>Here's the example class that responds to <code>float</code>, but is still not numeric.</p> <pre><code>class MyStrangeThing( object ): def __init__( self, aString ): # Some fancy parsing def __float__( self ): # extract some numeric value from my thing </code></pre> <p>The question "real numbers (either integers or floats)" is generally irrelevant. Many things are "numeric" and can be used in a numeric operation but aren't ints or floats. For example, you may have downloaded or created a rational numbers package.</p> <p>There's no point in overvalidating inputs, unless you have an algorithm that will not work with some types. These are rare, but some calculations require integers, specifically so they can do integer division and remainder operations. For those, you might want to assert that your values are ints.</p>
1
2008-12-16T19:15:47Z
[ "python", "idioms" ]
Python - Using __getattribute__ method
371,753
<p>I want to override access to one variable in a class, but return all others normally. How do I accomplish this with <code>__getattribute__</code>?</p> <p>I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error:</p> <pre><code>class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__dict__[name] &gt;&gt;&gt; print D().test 0.0 &gt;&gt;&gt; print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp </code></pre>
50
2008-12-16T16:04:38Z
371,833
<p>You get a recursion error because you call the same function, your <code>__getattribute__</code>. If you use <code>object</code>'s <code>__getattribute__</code> instead, it works:</p> <pre><code>class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return object.__getattribute__(self, name) </code></pre> <p>This works because <code>object</code> (in this example) is the base class. By calling the base version of <code>__getattribute__</code> you avoid the recursive hell you were in before.</p> <p>Ipython output with code in foo.py:</p> <pre><code>In [1]: from foo import * In [2]: d = D() In [3]: d.test Out[3]: 0.0 In [4]: d.test2 Out[4]: 21 </code></pre> <p><strong>Update:</strong></p> <p>There's something in the section titled <a href="http://docs.python.org/reference/datamodel.html#more-attribute-access-for-new-style-classes"><em>More attribute access for new-style classes</em></a> in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.</p>
73
2008-12-16T16:26:37Z
[ "python", "oop", "class", "recursion" ]
Python - Using __getattribute__ method
371,753
<p>I want to override access to one variable in a class, but return all others normally. How do I accomplish this with <code>__getattribute__</code>?</p> <p>I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error:</p> <pre><code>class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__dict__[name] &gt;&gt;&gt; print D().test 0.0 &gt;&gt;&gt; print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp </code></pre>
50
2008-12-16T16:04:38Z
371,844
<p>Are you sure you want to use <code>__getattribute__</code>? What are you actually trying to achieve?</p> <p>The easiest way to do what you ask is:</p> <pre><code>class D(object): def __init__(self): self.test = 20 self.test2 = 21 test = 0 </code></pre> <p>or:</p> <pre><code>class D(object): def __init__(self): self.test = 20 self.test2 = 21 @property def test(self): return 0 </code></pre> <p>Edit: Note that an instance of <code>D</code> would have different values of <code>test</code> in each case. In the first case <code>d.test</code> would be 20, in the second it would be 0. I'll leave it to you to work out why.</p> <p>Edit2: Greg pointed out that example 2 will fail because the property is read only and the <code>__init__</code> method tried to set it to 20. A more complete example for that would be:</p> <pre><code>class D(object): def __init__(self): self.test = 20 self.test2 = 21 _test = 0 def get_test(self): return self._test def set_test(self, value): self._test = value test = property(get_test, set_test) </code></pre> <p>Obviously, as a class this is almost entirely useless, but it gives you an idea to move on from.</p>
13
2008-12-16T16:32:36Z
[ "python", "oop", "class", "recursion" ]
Python - Using __getattribute__ method
371,753
<p>I want to override access to one variable in a class, but return all others normally. How do I accomplish this with <code>__getattribute__</code>?</p> <p>I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error:</p> <pre><code>class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__dict__[name] &gt;&gt;&gt; print D().test 0.0 &gt;&gt;&gt; print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp </code></pre>
50
2008-12-16T16:04:38Z
371,864
<p><a href="http://docs.python.org/reference/datamodel.html#object.__getattribute__" rel="nofollow">Python language reference:</a></p> <blockquote> <p>In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, <code>object.__getattribute__(self, name)</code>.</p> </blockquote> <p>Meaning:</p> <pre><code>def __getattribute__(self,name): ... return self.__dict__[name] </code></pre> <p>You're calling for an attribute called <code>__dict__</code>. Because it's an attribute, <code>__getattribute__</code> gets called in search for <code>__dict__</code> which calls <code>__getattribute__</code> which calls ... yada yada yada</p> <pre><code>return object.__getattribute__(self, name) </code></pre> <p>Using the base classes <code>__getattribute__</code> helps finding the real attribute.</p>
15
2008-12-16T16:39:23Z
[ "python", "oop", "class", "recursion" ]
Python - Using __getattribute__ method
371,753
<p>I want to override access to one variable in a class, but return all others normally. How do I accomplish this with <code>__getattribute__</code>?</p> <p>I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error:</p> <pre><code>class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__dict__[name] &gt;&gt;&gt; print D().test 0.0 &gt;&gt;&gt; print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp </code></pre>
50
2008-12-16T16:04:38Z
372,919
<p>Actually, I believe you want to use the <code>__getattr__</code> special method instead.</p> <p>Quote from the Python docs:</p> <blockquote> <p><code>__getattr__( self, name)</code> </p> <p>Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.<br> Note that if the attribute is found through the normal mechanism, <code>__getattr__()</code> is not called. (This is an intentional asymmetry between <code>__getattr__()</code> and <code>__setattr__()</code>.) This is done both for efficiency reasons and because otherwise <code>__setattr__()</code> would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the <code>__getattribute__()</code> method below for a way to actually get total control in new-style classes. </p> </blockquote> <p>Note: for this to work, the instance should <em>not</em> have a <code>test</code> attribute, so the line <code>self.test=20</code> should be removed.</p>
19
2008-12-16T22:01:38Z
[ "python", "oop", "class", "recursion" ]
Python - Using __getattribute__ method
371,753
<p>I want to override access to one variable in a class, but return all others normally. How do I accomplish this with <code>__getattribute__</code>?</p> <p>I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error:</p> <pre><code>class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__dict__[name] &gt;&gt;&gt; print D().test 0.0 &gt;&gt;&gt; print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp </code></pre>
50
2008-12-16T16:04:38Z
16,811,277
<p>Here is a more reliable version:</p> <pre><code>class D(object): def __init__(self): self.test = 20 self.test2 = 21 def __getattribute__(self, name): if name == 'test': return 0. else: return super(D, self).__getattribute__(name) </code></pre> <p>It calls <strong>__<em>getattribute</em>__</strong> method from parent class, eventually falling back to object.<strong>__<em>getattribute</em>__</strong> method if other ancestors don't override it.</p>
5
2013-05-29T10:18:19Z
[ "python", "oop", "class", "recursion" ]
Python - Using __getattribute__ method
371,753
<p>I want to override access to one variable in a class, but return all others normally. How do I accomplish this with <code>__getattribute__</code>?</p> <p>I tried the following (which should also illustrate what I'm trying to do) but I get a recursion error:</p> <pre><code>class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__dict__[name] &gt;&gt;&gt; print D().test 0.0 &gt;&gt;&gt; print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp </code></pre>
50
2008-12-16T16:04:38Z
28,356,216
<p><strong>Best Practice</strong></p> <p>The proper way to programmatically control access to a single attribute is with <a href="https://docs.python.org/library/functions.html#property" rel="nofollow"><code>property</code></a>. Class <code>D</code> should be written as follows (with the setter and deleter optionally to replicate apparent intended behavior):</p> <pre><code>class D(object): def __init__(self): self.test2=21 @property def test(self): return 0. @test.setter def test(self, value): '''dummy function to avoid AttributeError on setting property''' @test.deleter def test(self): '''dummy function to avoid AttributeError on deleting property''' </code></pre> <p>And usage:</p> <pre><code>&gt;&gt;&gt; o = D() &gt;&gt;&gt; o.test 0.0 &gt;&gt;&gt; o.test = 'foo' &gt;&gt;&gt; o.test 0.0 &gt;&gt;&gt; del o.test &gt;&gt;&gt; o.test 0.0 </code></pre> <p><strong>Options for <code>__getattribute__</code></strong></p> <p>If you insist on using the <code>__getattribute__</code> (really only best when you need to control access to <em>all</em> attributes) you can either call <code>__getattr__</code> (which, if <code>__getattribute__</code> is defined, <a href="https://docs.python.org/reference/datamodel.html#more-attribute-access-for-new-style-classes" rel="nofollow">isn't called unless <code>__getattribute__</code> calls it</a>) or call the parent class's <code>__getattribute__</code> with <a href="https://docs.python.org/library/functions.html#super" rel="nofollow"><code>super</code></a>, i.e.:</p> <pre><code>class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__getattr__(name) </code></pre> <p>or</p> <pre><code>class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return super(D, self).__getattribute__(name) </code></pre> <p>And both will behave like this (with an error on a repeated deletion):</p> <pre><code>&gt;&gt;&gt; o = D() &gt;&gt;&gt; o.test = 'foo' &gt;&gt;&gt; o.test 0.0 &gt;&gt;&gt; del o.test &gt;&gt;&gt; o.test 0.0 &gt;&gt;&gt; del o.test Traceback (most recent call last): File "&lt;pyshell#216&gt;", line 1, in &lt;module&gt; del o.test AttributeError: test </code></pre>
1
2015-02-05T23:48:48Z
[ "python", "oop", "class", "recursion" ]
When is white space not important in Python?
372,007
<p>When is white space not important in Python?</p> <p>It seems to be ignored inside a list, for example:</p> <pre><code>for x in range(5): list += [x, 1 ,2,3, 4,5] </code></pre>
3
2008-12-16T17:21:05Z
372,025
<p>White space is only important for indentation of statements. You have a single statement across several lines, and only the indentation of the beginning of the statement on the first line is significant. See <em><a href="http://www.secnetix.de/~olli/Python/block_indentation.hawk" rel="nofollow">Python: Myths about Indentation</a></em> for more information.</p>
14
2008-12-16T17:26:39Z
[ "python", "whitespace" ]
When is white space not important in Python?
372,007
<p>When is white space not important in Python?</p> <p>It seems to be ignored inside a list, for example:</p> <pre><code>for x in range(5): list += [x, 1 ,2,3, 4,5] </code></pre>
3
2008-12-16T17:21:05Z
372,108
<p>Your question is really about when Python implicitly joins lines of code.</p> <p>Python will implicitly join lines that are contained within (parentheses), {braces}, and [brackets], as in your example code. You can also explicitly join lines with a backslash (\) at the end of a line.</p> <p>More here on <a href="http://docs.python.org/reference/lexical_analysis.html#implicit-line-joining" rel="nofollow">implicit line continuation</a>: </p> <p>Mr. Gamble's answer is correct for indentation.</p>
7
2008-12-16T17:52:23Z
[ "python", "whitespace" ]
Difference between abstract class and interface in Python
372,042
<p>What is the difference between abstract class and interface in Python?</p>
302
2008-12-16T17:32:27Z
372,066
<p>Python doesn't really have either concept.</p> <p>It uses duck typing, which removed the need for interfaces (at least for the computer :-))</p> <p>Python &lt;= 2.5: Base classes obviously exist, but there is no explicit way to mark a method as 'pure virtual', so the class isn't really abstract.</p> <p>Python >= 2.6: Abstract base classes do <a href="http://www.python.org/dev/peps/pep-3119/">exist</a> (<a href="http://docs.python.org/library/abc.html">http://docs.python.org/library/abc.html</a>). And allow you to specify methods that must be implemented in subclasses. I don't much like the syntax, but the feature is there. Most of the time it's probably better to use duck typing from the 'using' client side.</p>
29
2008-12-16T17:38:22Z
[ "python", "interface", "abstract-class" ]
Difference between abstract class and interface in Python
372,042
<p>What is the difference between abstract class and interface in Python?</p>
302
2008-12-16T17:32:27Z
372,107
<p>Python >= 2.6 has <a href="http://docs.python.org/library/abc.html">Abstract Base Classes</a>.</p> <blockquote> <p>Abstract Base Classes (abbreviated ABCs) complement duck-typing by providing a way to define interfaces when other techniques like hasattr() would be clumsy. Python comes with many builtin ABCs for data structures (in the collections module), numbers (in the numbers module), and streams (in the io module). You can create your own ABC with the abc module.</p> </blockquote> <p>There is also the <a href="http://pypi.python.org/pypi/zope.interface">Zope Interface</a> module, which is used by projects outside of zope, like twisted. I'm not really familiar with it, but there's a wiki page <a href="http://wiki.zope.org/Interfaces/FrontPage">here</a> that might help.</p> <p>In general, you don't need the concept of abstract classes, or interfaces in python (edited - see S.Lott's answer for details).</p>
85
2008-12-16T17:51:35Z
[ "python", "interface", "abstract-class" ]
Difference between abstract class and interface in Python
372,042
<p>What is the difference between abstract class and interface in Python?</p>
302
2008-12-16T17:32:27Z
372,121
<p>What you'll see sometimes is the following:</p> <pre><code>class Abstract1( object ): """Some description that tells you it's abstract, often listing the methods you're expected to supply.""" def aMethod( self ): raise NotImplementedError( "Should have implemented this" ) </code></pre> <p>Because Python doesn't have (and doesn't need) a formal Interface contract, the Java-style distinction between abstraction and interface doesn't exist. If someone goes through the effort to define a formal interface, it will also be an abstract class. The only differences would be in the stated intent in the docstring. </p> <p>And the difference between abstract and interface is a hairsplitting thing when you have duck typing.</p> <p>Java uses interfaces because it doesn't have multiple inheritance.</p> <p>Because Python has multiple inheritance, you may also see something like this</p> <pre><code>class SomeAbstraction( object ): pass # lots of stuff - but missing something class Mixin1( object ): def something( self ): pass # one implementation class Mixin2( object ): def something( self ): pass # another class Concrete1( SomeAbstraction, Mixin1 ): pass class Concrete2( SomeAbstraction, Mixin2 ): pass </code></pre> <p>This uses a kind of abstract superclass with mixins to create concrete subclasses that are disjoint.</p>
355
2008-12-16T17:59:23Z
[ "python", "interface", "abstract-class" ]
Difference between abstract class and interface in Python
372,042
<p>What is the difference between abstract class and interface in Python?</p>
302
2008-12-16T17:32:27Z
372,188
<p>In general, interfaces are used only in languages that use the single-inheritance class model. In these single-inheritance languages, interfaces are typically used if any class could use a particular method or set of methods. Also in these single-inheritance languages, abstract classes are used to either have defined class variables in addition to none or more methods, or to exploit the single-inheritance model to limit the range of classes that could use a set of methods. </p> <p>Languages that support the multiple-inheritance model tend to use only classes or abstract base classes and not interfaces. Since Python supports multiple inheritance, it does not use interfaces and you would want to use base classes or abstract base classes.</p> <p><a href="http://docs.python.org/library/abc.html">http://docs.python.org/library/abc.html</a></p>
12
2008-12-16T18:19:55Z
[ "python", "interface", "abstract-class" ]
Difference between abstract class and interface in Python
372,042
<p>What is the difference between abstract class and interface in Python?</p>
302
2008-12-16T17:32:27Z
16,447,106
<p>In a more basic way to explain: An interface is sort of like an empty muffin pan. It's a class file with a set of method definitions that have no code.</p> <p>An abstract class is the same thing, but not all functions need to be empty. Some can have code. It's not strictly empty.</p> <p>Why differentiate: There's not much practical difference in Python, but on the planning level for a large project, it could be more common to talk about interfaces, since there's no code. Especially if you're working with Java programmers who are accustomed to the term.</p>
21
2013-05-08T17:51:11Z
[ "python", "interface", "abstract-class" ]
Difference between abstract class and interface in Python
372,042
<p>What is the difference between abstract class and interface in Python?</p>
302
2008-12-16T17:32:27Z
31,439,126
<blockquote> <h1>What is the difference between abstract class and interface in Python?</h1> </blockquote> <p>In Python, there is none! An abstract class defines an interface.</p> <h2>Using an Abstract Base Class</h2> <p>For example, say we want to use one of the abstract base classes from the <code>collections</code> module:</p> <pre><code>import collections class MySet(collections.Set): pass </code></pre> <p>If we try to use it, we get an <code>TypeError</code> because the class we created does not support the expected behavior of sets:</p> <pre><code>&gt;&gt;&gt; MySet() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: Can't instantiate abstract class MySet with abstract methods __contains__, __iter__, __len__ </code></pre> <p>So we are required to implement at <em>least</em> <code>__contains__</code>, <code>__iter__</code>, and <code>__len__</code>. Let's use this implementation example from the <a href="https://docs.python.org/2/library/collections.html#collections-abstract-base-classes">documentation</a>:</p> <pre><code>class ListBasedSet(collections.Set): ''' Alternate set implementation favoring space over speed and not requiring the set elements to be hashable. ''' def __init__(self, iterable): self.elements = lst = [] for value in iterable: if value not in lst: lst.append(value) def __iter__(self): return iter(self.elements) def __contains__(self, value): return value in self.elements def __len__(self): return len(self.elements) s1 = ListBasedSet('abcdef') s2 = ListBasedSet('defghi') overlap = s1 &amp; s2 </code></pre> <h2>Implementation: Creating an Abstract Base Class</h2> <p>We can create our own Abstract Base Class by setting the metaclass to <code>abc.ABCMeta</code> and using the <code>abc.abstractmethod</code> decorator on relevant methods. The metaclass will be add the decorated functions to the <code>__abstractmethods__</code> attribute, preventing instantiation until those are defined.</p> <pre><code>import abc </code></pre> <p>For example, "effable" is defined as something that can be expressed in words. Say we wanted to define an abstract base class that is effable, in Python 2:</p> <pre><code>class Effable(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def __str__(self): raise NotImplementedError('users must define __str__ to use this base class') </code></pre> <p>Or in Python 3, with the slight change in metaclass declaration:</p> <pre><code>class Effable(object, metaclass=abc.ABCMeta): @abc.abstractmethod def __str__(self): raise NotImplementedError('users must define __str__ to use this base class') </code></pre> <p>Now if we try to create an effable object without implementing the interface:</p> <pre><code>class MyEffable(Effable): pass </code></pre> <p>and attempt to instantiate it:</p> <pre><code>&gt;&gt;&gt; MyEffable() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: Can't instantiate abstract class MyEffable with abstract methods __str__ </code></pre> <p>We are told that we haven't finished the job.</p> <p>Now if we comply by providing the expected interface:</p> <pre><code>class MyEffable(Effable): def __str__(self): return 'expressable!' </code></pre> <p>we are then able to use the concrete version of the class derived from the abstract one:</p> <pre><code>&gt;&gt;&gt; me = MyEffable() &gt;&gt;&gt; print(me) expressable! </code></pre> <p>There are other things we could do with this, like register virtual subclasses that already implement these interfaces, but I think that is beyond the scope of this question. The other methods demonstrated here would have to adapt this method using the <code>abc</code> module to do so, however.</p> <h2>Conclusion</h2> <p>We have demonstrated that the creation of an Abstract Base Class defines an interface in Python, thus they are one and the same.</p>
37
2015-07-15T19:15:20Z
[ "python", "interface", "abstract-class" ]
UTF in Python Regex
372,102
<p>I'm aware that Python 3 fixes a lot of UTF issues, I am not however able to use Python 3, I am using 2.5.1</p> <p>I'm trying to regex a document but the document has UTF hyphens in it – rather than -. Python can't match these and if I put them in the regex it throws a wobbly.</p> <p>How can I force Python to use a UTF string or in some way match a character such as that?</p> <p>Thanks for your help</p>
7
2008-12-16T17:49:12Z
372,128
<p>You have to escape the character in question (–) and put a u in front of the string literal to make it a unicode string. </p> <p>So, for example, this:</p> <pre><code>re.compile("–") </code></pre> <p>becomes this:</p> <pre><code>re.compile(u"\u2013") </code></pre>
7
2008-12-16T18:01:19Z
[ "python", "regex" ]
UTF in Python Regex
372,102
<p>I'm aware that Python 3 fixes a lot of UTF issues, I am not however able to use Python 3, I am using 2.5.1</p> <p>I'm trying to regex a document but the document has UTF hyphens in it – rather than -. Python can't match these and if I put them in the regex it throws a wobbly.</p> <p>How can I force Python to use a UTF string or in some way match a character such as that?</p> <p>Thanks for your help</p>
7
2008-12-16T17:49:12Z
372,193
<p>After a quick test and visit to <a href="http://www.python.org/dev/peps/pep-0263/" rel="nofollow">PEP 0264: Defining Python Source Code Encodings</a>, I see you may need to tell Python the whole file is UTF-8 encoded by adding adding a comment like this to the first line.</p> <pre><code># encoding: utf-8 </code></pre> <p>Here's the test file I created and ran on Python 2.5.1 / OS X 10.5.6</p> <pre><code># encoding: utf-8 import re x = re.compile("–") print x.search("xxx–x").start() </code></pre>
4
2008-12-16T18:20:34Z
[ "python", "regex" ]
UTF in Python Regex
372,102
<p>I'm aware that Python 3 fixes a lot of UTF issues, I am not however able to use Python 3, I am using 2.5.1</p> <p>I'm trying to regex a document but the document has UTF hyphens in it – rather than -. Python can't match these and if I put them in the regex it throws a wobbly.</p> <p>How can I force Python to use a UTF string or in some way match a character such as that?</p> <p>Thanks for your help</p>
7
2008-12-16T17:49:12Z
372,210
<p>Don't use UTF-8 in a regular expression. UTF-8 is a multibyte encoding where some unicode code points are encoded by 2 or more bytes. You may match parts of your string that you didn't plan to match. Instead use unicode strings as suggested.</p>
3
2008-12-16T18:27:38Z
[ "python", "regex" ]
Set timeout for xmlrpclib.ServerProxy
372,365
<p>I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. </p> <p>This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to update the timeout on my ServerProxy object?</p> <p>I can't see a clear way to get access to the socket to update it.</p>
14
2008-12-16T19:22:27Z
372,442
<p>I have looked at several ways to solve this issue and by far the most elegant is described here: <a href="https://seattle.cs.washington.edu/browser/seattle/trunk/demokit/timeout_xmlrpclib.py?rev=692" rel="nofollow">https://seattle.cs.washington.edu/browser/seattle/trunk/demokit/timeout_xmlrpclib.py?rev=692</a></p> <p>The technique was originally presented here, but this link is dead: <a href="https://seattle.cs.washington.edu/browser/seattle/trunk/demokit/timeout_xmlrpclib.py?rev=692" rel="nofollow">http://blog.bjola.ca/2007/08/using-timeout-with-xmlrpclib.html</a></p> <p>This works with Python 2.5 and 2.6. The new link claims to work with Python 3.0 as well.</p>
5
2008-12-16T19:45:15Z
[ "python", "xml-rpc" ]
Set timeout for xmlrpclib.ServerProxy
372,365
<p>I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. </p> <p>This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to update the timeout on my ServerProxy object?</p> <p>I can't see a clear way to get access to the socket to update it.</p>
14
2008-12-16T19:22:27Z
375,000
<p>Here is a verbatim copy from <a href="http://code.activestate.com/recipes/473878/" rel="nofollow">http://code.activestate.com/recipes/473878/</a></p> <pre><code>def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None): import threading class InterruptableThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.result = None def run(self): try: self.result = func(*args, **kwargs) except: self.result = default it = InterruptableThread() it.start() it.join(timeout_duration) if it.isAlive(): return default else: return it.result </code></pre>
1
2008-12-17T15:53:56Z
[ "python", "xml-rpc" ]
Set timeout for xmlrpclib.ServerProxy
372,365
<p>I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. </p> <p>This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to update the timeout on my ServerProxy object?</p> <p>I can't see a clear way to get access to the socket to update it.</p>
14
2008-12-16T19:22:27Z
1,766,187
<p>An more straightforward solution is at: <a href="http://www.devpicayune.com/entry/200609191448">http://www.devpicayune.com/entry/200609191448</a></p> <pre><code>import xmlrpclib import socket x = xmlrpclib.ServerProxy('http:1.2.3.4') socket.setdefaulttimeout(10) #set the timeout to 10 seconds x.func_name(args) #times out after 10 seconds socket.setdefaulttimeout(None) #sets the default back </code></pre>
16
2009-11-19T20:09:22Z
[ "python", "xml-rpc" ]
Set timeout for xmlrpclib.ServerProxy
372,365
<p>I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. </p> <p>This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to update the timeout on my ServerProxy object?</p> <p>I can't see a clear way to get access to the socket to update it.</p>
14
2008-12-16T19:22:27Z
2,116,786
<p>clean non global version.</p> <pre><code>import xmlrpclib import httplib class TimeoutHTTPConnection(httplib.HTTPConnection): def connect(self): httplib.HTTPConnection.connect(self) self.sock.settimeout(self.timeout) class TimeoutHTTP(httplib.HTTP): _connection_class = TimeoutHTTPConnection def set_timeout(self, timeout): self._conn.timeout = timeout class TimeoutTransport(xmlrpclib.Transport): def __init__(self, timeout=10, *l, **kw): xmlrpclib.Transport.__init__(self, *l, **kw) self.timeout = timeout def make_connection(self, host): conn = TimeoutHTTP(host) conn.set_timeout(self.timeout) return conn class TimeoutServerProxy(xmlrpclib.ServerProxy): def __init__(self, uri, timeout=10, *l, **kw): kw['transport'] = TimeoutTransport( timeout=timeout, use_datetime=kw.get('use_datetime', 0)) xmlrpclib.ServerProxy.__init__(self, uri, *l, **kw) if __name__ == "__main__": s = TimeoutServerProxy('http://127.0.0.1:9090', timeout=2) s.dummy() </code></pre>
14
2010-01-22T11:10:29Z
[ "python", "xml-rpc" ]
Set timeout for xmlrpclib.ServerProxy
372,365
<p>I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. </p> <p>This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to update the timeout on my ServerProxy object?</p> <p>I can't see a clear way to get access to the socket to update it.</p>
14
2008-12-16T19:22:27Z
2,138,709
<p>Based on the one from antonylesuisse, a working version (on python >= 2.6).</p> <pre><code># -*- coding: utf8 -*- import xmlrpclib import httplib import socket class TimeoutHTTP(httplib.HTTP): def __init__(self, host='', port=None, strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): if port == 0: port = None self._setup(self._connection_class(host, port, strict, timeout)) class TimeoutTransport(xmlrpclib.Transport): def __init__(self, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, *args, **kwargs): xmlrpclib.Transport.__init__(self, *args, **kwargs) self.timeout = timeout def make_connection(self, host): host, extra_headers, x509 = self.get_host_info(host) conn = TimeoutHTTP(host, timeout=self.timeout) return conn class TimeoutServerProxy(xmlrpclib.ServerProxy): def __init__(self, uri, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, *args, **kwargs): kwargs['transport'] = TimeoutTransport(timeout=timeout, use_datetime=kwargs.get('use_datetime', 0)) xmlrpclib.ServerProxy.__init__(self, uri, *args, **kwargs) </code></pre>
1
2010-01-26T10:15:16Z
[ "python", "xml-rpc" ]
Set timeout for xmlrpclib.ServerProxy
372,365
<p>I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. </p> <p>This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to update the timeout on my ServerProxy object?</p> <p>I can't see a clear way to get access to the socket to update it.</p>
14
2008-12-16T19:22:27Z
7,915,395
<p>Here is code that works on Python 2.7 (probably for other 2.x versions of Python) without raising <em>AttributeError, instance has no attribute 'getresponse'</em>.</p> <pre><code> class TimeoutHTTPConnection(httplib.HTTPConnection): def connect(self): httplib.HTTPConnection.connect(self) self.sock.settimeout(self.timeout) class TimeoutHTTP(httplib.HTTP): _connection_class = TimeoutHTTPConnection def set_timeout(self, timeout): self._conn.timeout = timeout class TimeoutTransport(xmlrpclib.Transport): def __init__(self, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, *args, **kwargs): xmlrpclib.Transport.__init__(self, *args, **kwargs) self.timeout = timeout def make_connection(self, host): if self._connection and host == self._connection[0]: return self._connection[1] chost, self._extra_headers, x509 = self.get_host_info(host) self._connection = host, httplib.HTTPConnection(chost) return self._connection[1] transport = TimeoutTransport(timeout=timeout) xmlrpclib.ServerProxy.__init__(self, uri, transport=transport, allow_none=True) </code></pre>
2
2011-10-27T11:46:37Z
[ "python", "xml-rpc" ]
Set timeout for xmlrpclib.ServerProxy
372,365
<p>I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. </p> <p>This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to update the timeout on my ServerProxy object?</p> <p>I can't see a clear way to get access to the socket to update it.</p>
14
2008-12-16T19:22:27Z
14,397,619
<p>Here another smart and very <strong>pythonic</strong> solution using Python's <code>with</code> statement:</p> <pre><code>import socket import xmlrpc.client class MyServerProxy: def __init__(self, url, timeout=None): self.__url = url self.__timeout = timeout self.__prevDefaultTimeout = None def __enter__(self): try: if self.__timeout: self.__prevDefaultTimeout = socket.getdefaulttimeout() socket.setdefaulttimeout(self.__timeout) proxy = xmlrpc.client.ServerProxy(self.__url, allow_none=True) except Exception as ex: raise Exception("Unable create XMLRPC-proxy for url '%s': %s" % (self.__url, ex)) return proxy def __exit__(self, type, value, traceback): if self.__prevDefaultTimeout is None: socket.setdefaulttimeout(self.__prevDefaultTimeout) </code></pre> <p>This class can be used like this:</p> <pre><code>with MyServerProxy('http://1.2.3.4', 20) as proxy: proxy.dummy() </code></pre>
0
2013-01-18T11:05:39Z
[ "python", "xml-rpc" ]
Set timeout for xmlrpclib.ServerProxy
372,365
<p>I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. </p> <p>This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to update the timeout on my ServerProxy object?</p> <p>I can't see a clear way to get access to the socket to update it.</p>
14
2008-12-16T19:22:27Z
15,969,144
<p>The following example works with Python 2.7.4.</p> <pre><code>import xmlrpclib from xmlrpclib import * import httplib def Server(url, *args, **kwargs): t = TimeoutTransport(kwargs.get('timeout', 20)) if 'timeout' in kwargs: del kwargs['timeout'] kwargs['transport'] = t server = xmlrpclib.Server(url, *args, **kwargs) return server TimeoutServerProxy = Server class TimeoutTransport(xmlrpclib.Transport): def __init__(self, timeout, use_datetime=0): self.timeout = timeout return xmlrpclib.Transport.__init__(self, use_datetime) def make_connection(self, host): conn = xmlrpclib.Transport.make_connection(self, host) conn.timeout = self.timeout return connrpclib.Server(url, *args, **kwargs) </code></pre>
0
2013-04-12T10:36:02Z
[ "python", "xml-rpc" ]
Set timeout for xmlrpclib.ServerProxy
372,365
<p>I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. </p> <p>This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to update the timeout on my ServerProxy object?</p> <p>I can't see a clear way to get access to the socket to update it.</p>
14
2008-12-16T19:22:27Z
26,774,377
<p>Based on the one from antonylesuisse, but works on Python 2.7.5, resolving the problem:<code>AttributeError: TimeoutHTTP instance has no attribute 'getresponse'</code></p> <pre><code>class TimeoutHTTP(httplib.HTTP): def __init__(self, host='', port=None, strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): if port == 0: port = None self._setup(self._connection_class(host, port, strict, timeout)) def getresponse(self, *args, **kw): return self._conn.getresponse(*args, **kw) class TimeoutTransport(xmlrpclib.Transport): def __init__(self, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, *l, **kw): xmlrpclib.Transport.__init__(self, *l, **kw) self.timeout=timeout def make_connection(self, host): host, extra_headers, x509 = self.get_host_info(host) conn = TimeoutHTTP(host, timeout=self.timeout) return conn class TimeoutServerProxy(xmlrpclib.ServerProxy): def __init__(self, uri, timeout= socket._GLOBAL_DEFAULT_TIMEOUT, *l, **kw): kw['transport']=TimeoutTransport(timeout=timeout, use_datetime=kw.get('use_datetime',0)) xmlrpclib.ServerProxy.__init__(self, uri, *l, **kw) proxy = TimeoutServerProxy('http://127.0.0.1:1989', timeout=30) print proxy.test_connection() </code></pre>
0
2014-11-06T07:58:16Z
[ "python", "xml-rpc" ]
Set timeout for xmlrpclib.ServerProxy
372,365
<p>I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. </p> <p>This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to update the timeout on my ServerProxy object?</p> <p>I can't see a clear way to get access to the socket to update it.</p>
14
2008-12-16T19:22:27Z
33,944,151
<p>I wanted a small, clean, but also explicit version, so based on all other answers here, this is what I came up with:</p> <pre><code>import xmlrpclib class TimeoutTransport(xmlrpclib.Transport): def __init__(self, timeout, use_datetime=0): self.timeout = timeout # xmlrpclib uses old-style classes so we cannot use super() xmlrpclib.Transport.__init__(self, use_datetime) def make_connection(self, host): connection = xmlrpclib.Transport.make_connection(self, host) connection.timeout = self.timeout return connection class TimeoutServerProxy(xmlrpclib.ServerProxy): def __init__(self, uri, timeout=10, transport=None, encoding=None, verbose=0, allow_none=0, use_datetime=0): t = TimeoutTransport(timeout) xmlrpclib.ServerProxy.__init__(self, uri, t, encoding, verbose, allow_none, use_datetime) proxy = TimeoutServerProxy(some_url) </code></pre> <p>I didn't realize at first <code>xmlrpclib</code> has old-style classes so I found it useful with a comment on that, otherwise everything should be pretty self-explanatory.</p> <p>I don't see why <code>httplib.HTTP</code> would have to be subclassed as well, if someone can enlighten me on this, please do. The above solution is tried and works.</p>
1
2015-11-26T17:20:22Z
[ "python", "xml-rpc" ]
Protecting online static content
372,465
<p>How would I only allow users authenticated via Python code to access certain files on the server?</p> <p>For instance, say I have <code>/static/book.txt</code> which I want to protect. When a user accesses <code>/some/path/that/validates/him</code>, a Python script deems him worthy of accessing <code>/static/book.txt</code> and redirects him to that path.</p> <p>How would I stop users who bypass the script and directly access <code>/static/book.txt</code>?</p>
0
2008-12-16T19:50:23Z
372,482
<p>Lighttpd has <a href="http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModSecDownload" rel="nofollow">mod_secdownload</a> for this. Basically, it won't serve the static content directly unless you generate a short-lived static URL for it.</p> <p>Note that you can do similar things on S3 for static content. It's a quite useful feature.</p>
3
2008-12-16T19:54:29Z
[ "python", "security", "apache", "download", "lighttpd" ]
Protecting online static content
372,465
<p>How would I only allow users authenticated via Python code to access certain files on the server?</p> <p>For instance, say I have <code>/static/book.txt</code> which I want to protect. When a user accesses <code>/some/path/that/validates/him</code>, a Python script deems him worthy of accessing <code>/static/book.txt</code> and redirects him to that path.</p> <p>How would I stop users who bypass the script and directly access <code>/static/book.txt</code>?</p>
0
2008-12-16T19:50:23Z
372,488
<p>You might want to just have your Python script open the file and dump the contents as its output if the user is properly authenticated. Put the files you want to protect in a folder that is outside of the webserver root.</p>
3
2008-12-16T19:55:15Z
[ "python", "security", "apache", "download", "lighttpd" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,517
<p>Impossible to answer without knowing the shape of the data and the structure that you've designed to contain it.</p>
0
2008-12-16T20:06:48Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,524
<p>I wouldn't consider it fair to blame any shortcomings of your design to OOP. Just like any other programming platform out there OO can be used for both good and less than optimal design. Rarely will this be the fault of the programming model itself. </p> <p>But to try to answer your question: Allocating 250000 new object requires some overhead in all OO language that I'm aware of, so if you can get away with streaming the data through the same instance, you're probably better off. </p>
2
2008-12-16T20:10:28Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,566
<p>You'd have similar issues with procedural/functional programming languages. How do you store that much data in memory? A struct or array wouldn't work either. </p> <p>You need to take special steps to manage this scale of data.</p> <p>BTW: I wouldn't use this as a reason to pick either an OO language or not. </p>
3
2008-12-16T20:24:58Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,595
<p>The "overhead" depends largely on the platform and the implementation you chose.</p> <p>Now if you have a memory problem reading millions of data from a multiple Gb file, you're having an algorithm problem where the memory consumption of objects is definitely not the biggest concern, the concern yould be more about how you do fetch, process and store the data.</p>
0
2008-12-16T20:34:36Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,641
<p>Like the other posters have stated. I do not believe Objects are going to lend a significant amount of overhead to your process. It will need to store a pointer to the object but the rest of the 'doubles' will be taking 99% of your program's memory.</p> <p>Can you partition this data into much smaller subsets? What is the task that you are trying to accomplish? I would be interested in seeing what you need all the data in memory for. Perhaps you can just serialize it, or use something like lazy evaluation in haskell.</p> <p>Please post a follow up so we can understand your problem domain better.</p>
0
2008-12-16T20:43:57Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,656
<p>See <a href="http://code.activestate.com/recipes/546530/" rel="nofollow">http://code.activestate.com/recipes/546530/</a></p> <p>This is the approximate size of Python objects.</p> <p>The OO size "penalty" is often offset by the ability to (a) simplify processing and (b) keep less stuff in memory in the first place.</p> <p>There is no OO performance overhead. Zero. In C++, the class definitions are optimized out of existence, and all you have left is C. In Python -- like all dynamic languages -- the dynamic programming environment adds some run-time lookups. Mostly, these are direct hashes into dictionaries. It's slower than code where a compiler did all the resolving for you. However it's still very fast with relatively low overhead.</p> <p>A bad algorithm in C can easily be slower than the right algorithm in Python.</p>
2
2008-12-16T20:48:12Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,658
<p>I don't think the question is overhead coming from OO.</p> <p>If we accept C++ as an OO language and remember that the C++ compiler is a preprocessor to C (at least it used to be, when I used C++), anything done in C++ is really done in C. C has very little overhead. So it would depend on the libraries.</p> <p>I think any overhead would come from interpretation, managed execution or memory management. For those that have the tools and the know-how, it would be very easy to find out which is most efficient, C++ or Python.</p> <p>I can't see where C++ would add much avoidable overhead. I don't know much about Python.</p>
0
2008-12-16T20:48:41Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,706
<p>compared to the size of your data set, the overhead of 250K objects is negligible</p> <p>i think you're on the wrong path; don't blame objects for that ;-)</p>
0
2008-12-16T21:03:58Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,724
<p>Please define "manipulate". If you really want to manipulate 4 gigs of data why do you want to manipulate it by pulling it ALL into memory right away?</p> <p>I mean, who needs 4 gig of RAM anyway? :)</p>
0
2008-12-16T21:09:31Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,748
<p>Slightly OT: the <a href="http://en.wikipedia.org/wiki/Flyweight_pattern" rel="nofollow">flyweight design pattern</a> can be useful for minimising overheads when you're manipulating large datasets. Without knowing the details of your problem I'm not sure how applicable it is, but it's worth a look...</p>
3
2008-12-16T21:15:02Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,779
<p>Actual C++ OO memory overhead is one pointer (4-8 bytes, depending) per object with virtual methods. However, as mentioned in other answers, the default memory allocation overhead from dynamic allocation is likely to be significantly greater than this.</p> <p>If you're doing things halfway reasonably, neither overhead is likely to be significant compared with an 1000*8-byte double array. If you're actually worried about allocation overhead, you can write your own allocator -- but, check first to see if it will actually buy you a significant improvement.</p>
1
2008-12-16T21:24:38Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,798
<p>If you have to manipulate data sets this big on a regular basis, could you just get a <a href="http://h10010.www1.hp.com/wwpc/us/en/sm/WF05a/12454-12454-296719-307907-296721-3211286.html" rel="nofollow">64-bit machine</a> with bucket-loads of RAM? For various reasons, I've found myself working with fairly resource hungry software (in this case SQL Server Analysis Services). Older 64-bit machines of this sort can take large amounts of RAM and feature CPUs that while not cutting-edge are still respectably fast.</p> <p>I got some secondhand HP workstations and fitted them with several fast SCSI disks. In mid-2007 these machines with 4 or 8GB of RAM and 5x 10K or 15K SCSI disks cost between £1,500-£2,000 to buy. The disks were half the cost of the machines and you may not need the I/O performance so you probably won't need to spend this much. <a href="http://h10010.www1.hp.com/wwpc/ca/en/sm/WF06b/12132708-12132710-12132712-12132712-12132712-12132804-77987465.html" rel="nofollow">XW9300's</a> of the sort that I bought can be purchased of ebay quite cheaply now - <a href="http://stackoverflow.com/questions/181050/can-you-allocate-a-very-large-single-chunk-of-memory-4gb-in-c-or-c#188564">this posting of mine</a> goes into various options for using ebay to get a high-spec 64-bit box on the cheap. You can get memory upgrades to 16 or 32GB for these machines off ebay for quite a small fraction of the list price of the parts.</p>
0
2008-12-16T21:28:39Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,801
<p>A friend of mine was a professor at MIT and a student asked him why his image analysis program was running so slow. How was it built? Every pixel was an object, and would send messages to its neighbors!</p> <p>If I were you I'd try it in a throw-away program. My suspicion is, unless your classes are very carefully coded, you're going to find it spending a lot of time allocating, initializing, and de-allocating objects, and as Brian said, you might be able to spool the data through a set of re-used objects.</p> <p>Edit: Excuse me. You said you are re-using objects, so that's good. In any case, when you get it running you could profile it or (if you were me) just read the call stack a few random times, and that will answer any questions about where the time goes.</p>
0
2008-12-16T21:29:24Z
[ "python", "oop", "data-analysis" ]
What is the object oriented programming computing overhead cost?
372,511
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
2
2008-12-16T20:04:06Z
372,848
<p>Since you can split the data in half and operate on it, I'm assuming that you're working on each record individually? It sounds to me like you need to change your deserialiser to read one record at a time, manipulate it, and then store out the results.</p> <p>Basically you need a string parser class that does a Peek() which returns a char, knows how to skip whitespace, etc. Wrap a class around that that understands your data format, and you should be able to have it spit out an object at a time as it reads the file.</p>
0
2008-12-16T21:37:35Z
[ "python", "oop", "data-analysis" ]
How do I connect to a MySQL Database in Python?
372,885
<p>How do I connect to a MySQL database using a python program?</p>
674
2008-12-16T21:49:09Z
372,896
<p>Here's one way to do it.</p> <pre><code>#!/usr/bin/python import MySQLdb # connect db = MySQLdb.connect(host="localhost", user="appuser", passwd="", db="onco") cursor = db.cursor() # execute SQL select statement cursor.execute("SELECT * FROM LOCATION") # commit your changes db.commit() # get the number of rows in the resultset numrows = int(cursor.rowcount) # get and display one row at a time. for x in range(0,numrows): row = cursor.fetchone() print row[0], "--&gt;", row[1] </code></pre> <p>From <a href="http://it.toolbox.com/blogs/lim/connecting-to-mysql-from-python-4529">here</a>.</p>
118
2008-12-16T21:51:56Z
[ "python", "mysql" ]
How do I connect to a MySQL Database in Python?
372,885
<p>How do I connect to a MySQL database using a python program?</p>
674
2008-12-16T21:49:09Z
372,899
<p>Try using MySQLdb</p> <p>There is a how to page here: <a href="http://www.kitebird.com/articles/pydbapi.html">http://www.kitebird.com/articles/pydbapi.html</a></p> <p><hr /></p> <p>From the page:</p> <pre><code># server_version.py - retrieve and display database server version import MySQLdb conn = MySQLdb.connect (host = "localhost", user = "testuser", passwd = "testpass", db = "test") cursor = conn.cursor () cursor.execute ("SELECT VERSION()") row = cursor.fetchone () print "server version:", row[0] cursor.close () conn.close () </code></pre>
15
2008-12-16T21:52:49Z
[ "python", "mysql" ]
How do I connect to a MySQL Database in Python?
372,885
<p>How do I connect to a MySQL database using a python program?</p>
674
2008-12-16T21:49:09Z
373,011
<p><a href="http://pypi.python.org/pypi/MySQL-python/">MySQLdb</a> is the straightforward way. You get to execute SQL queries over a connection. Period.</p> <p>My preferred way, which is also pythonic, is to use the mighty <a href="http://www.sqlalchemy.org/">SQLAlchemy</a> instead. Here is a <a href="http://www.sqlalchemy.org/docs/05/sqlexpression.html">query related</a> tutorial, and here is a tutorial on <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html">ORM capabilities</a> of SQLALchemy.</p>
5
2008-12-16T22:29:06Z
[ "python", "mysql" ]
How do I connect to a MySQL Database in Python?
372,885
<p>How do I connect to a MySQL database using a python program?</p>
674
2008-12-16T21:49:09Z
622,308
<h2>Connecting to MYSQL with Python in 3 steps</h2> <p><strong>1 - Setting</strong></p> <p>You must install a MySQL driver before doing anything. Unlike PHP, only the SQLite driver is installed by default with Python. The most used package to do so is <a href="http://pypi.python.org/pypi/MySQL-python/">MySQLdb</a> but it's hard to install it using easy_install.</p> <p>For Windows user, you can get an <a href="http://sourceforge.net/project/showfiles.php?group_id=22307">exe of MySQLdb</a>. </p> <p>For Linux, this is a casual package (python-mysqldb). (You can use <code>sudo apt-get install python-mysqldb</code> (for debian based distros), <code>yum install mysql-python</code> (for rpm-based), or <code>dnf install python-mysql</code> (for modern fedora distro) in command line to download.)</p> <p>For Mac, you can <a href="http://stackoverflow.com/questions/1448429/how-to-install-mysqldb-python-data-access-library-to-mysql-on-mac-os-x#1448476">install MySQLdb using Macport</a>.</p> <p><strong>2 - Usage</strong></p> <p>After installing, reboot. This is not mandatory, but will prevent me from answering 3 or 4 other questions in this post if something goes wrong. So please reboot.</p> <p>Then it is just like using another package :</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/python import MySQLdb db = MySQLdb.connect(host="localhost", # your host, usually localhost user="john", # your username passwd="megajonhy", # your password db="jonhydb") # name of the data base # you must create a Cursor object. It will let # you execute all the queries you need cur = db.cursor() # Use all the SQL you like cur.execute("SELECT * FROM YOUR_TABLE_NAME") # print all the first cell of all the rows for row in cur.fetchall(): print row[0] db.close() </code></pre> <p>Of course, there are thousand of possibilities and options; this is a very basic example. You will have to look at the documentation. <a href="http://www.mikusa.com/python-mysql-docs/">A good starting point</a>.</p> <p><strong>3 - More advanced usage</strong></p> <p>Once you know how it works, you may want to use an <a href="https://en.wikipedia.org/wiki/Object-Relational_Mapping">ORM</a> to avoid writting SQL manually and manipulate your tables as they were Python objects. The most famous ORM in the Python community is <a href="http://www.sqlalchemy.org/">SQLAlchemy</a>. </p> <p>I strongly advise you to use it: your life is going to be much easier.</p> <p>I recently discovered another jewel in the Python world: <a href="http://peewee.readthedocs.org/en/latest/index.html">peewee</a>. It's a very lite ORM, really easy and fast to setup then use. It makes my day for small projects or stand alone apps, where using big tools like SQLAlchemy or Django is overkill :</p> <pre class="lang-py prettyprint-override"><code>import peewee from peewee import * db = MySQLDatabase('jonhydb', user='john',passwd='megajonhy') class Book(peewee.Model): author = peewee.CharField() title = peewee.TextField() class Meta: database = db Book.create_table() book = Book(author="me", title='Peewee is cool') book.save() for book in Book.filter(author="me"): print book.title Peewee is cool </code></pre> <p>This example works out of the box. Nothing other than having peewee (<code>pip install peewee</code> :-)) is required. No complicated setup. It's really cool.</p>
837
2009-03-07T18:57:34Z
[ "python", "mysql" ]
How do I connect to a MySQL Database in Python?
372,885
<p>How do I connect to a MySQL database using a python program?</p>
674
2008-12-16T21:49:09Z
12,904,258
<p>As a db driver, there is also <a href="http://packages.python.org/oursql/index.html">oursql</a>. Some of the reasons listed on that link, which say why oursql is better:</p> <blockquote> <ul> <li>oursql has real parameterization, sending the SQL and data to MySQL completely separately.</li> <li>oursql allows text or binary data to be streamed into the database and streamed out of the database, instead of requiring everything to be buffered in the client.</li> <li>oursql can both insert rows lazily and fetch rows lazily.</li> <li>oursql has unicode support on by default.</li> <li>oursql supports python 2.4 through 2.7 without any deprecation warnings on 2.6+ (see PEP 218) and without completely failing on 2.7 (see PEP 328).</li> <li>oursql runs natively on python 3.x.</li> </ul> </blockquote> <h3>So how to connect to mysql with oursql?</h3> <p>Very similar to mysqldb:</p> <pre><code>import oursql db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name') cur=db_connection.cursor() cur.execute("SELECT * FROM `tbl_name`") for row in cur.fetchall(): print row[0] </code></pre> <p>The <a href="http://packages.python.org/oursql/tutorial.html">tutorial in the documentation</a> is pretty decent.</p> <p>And of course for ORM SQLAlchemy is a good choice, as already mentioned in the other answers.</p>
16
2012-10-15T21:25:05Z
[ "python", "mysql" ]
How do I connect to a MySQL Database in Python?
372,885
<p>How do I connect to a MySQL database using a python program?</p>
674
2008-12-16T21:49:09Z
16,796,108
<p>Oracle (MySQL) now supports a pure Python connector. That means no binaries to install: it's just a Python library. It's called "Connector/Python". </p> <p><a href="http://dev.mysql.com/downloads/connector/python/">http://dev.mysql.com/downloads/connector/python/</a></p>
70
2013-05-28T15:39:22Z
[ "python", "mysql" ]
How do I connect to a MySQL Database in Python?
372,885
<p>How do I connect to a MySQL database using a python program?</p>
674
2008-12-16T21:49:09Z
18,738,239
<p>For python 3.3</p> <p>CyMySQL <a href="https://github.com/nakagami/CyMySQL" rel="nofollow">https://github.com/nakagami/CyMySQL</a></p> <p>I have pip installed on my windows 7, just pip install cymysql</p> <p>(you don't need cython) quick and painless</p>
0
2013-09-11T10:04:37Z
[ "python", "mysql" ]
How do I connect to a MySQL Database in Python?
372,885
<p>How do I connect to a MySQL database using a python program?</p>
674
2008-12-16T21:49:09Z
20,959,654
<p>If you do not need MySQLdb, but would accept any library, I would very, very much recommend MySQL Connector/Python from MySQL: <a href="http://dev.mysql.com/downloads/connector/python/">http://dev.mysql.com/downloads/connector/python/</a>.</p> <p>It is one package (around 110k), pure Python, so it is system independent, and dead simple to install. You just download, double-click, confirm license agreement and go. There is no need for Xcode, MacPorts, compiling, restarting …</p> <p>Then you connect like:</p> <pre><code>import mysql.connector cnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1', database='employees') try: cursor = cnx.cursor() cursor.execute(""" select 3 from your_table """) result = cursor.fetchall() print result finally: cnx.close() </code></pre>
64
2014-01-06T21:32:15Z
[ "python", "mysql" ]
How do I connect to a MySQL Database in Python?
372,885
<p>How do I connect to a MySQL database using a python program?</p>
674
2008-12-16T21:49:09Z
30,619,930
<p>Also take a look at <a href="https://storm.canonical.com" rel="nofollow">Storm</a>. It is a simple SQL mapping tool which allows you to easily edit and create SQL entries without writing the queries.</p> <p>Here is a simple example:</p> <pre><code>from storm.locals import * # User will be the mapped object; you have to create the table before mapping it class User(object): __storm_table__ = "user" # table name ID = Int(primary=True) #field ID name= Unicode() # field name database = create_database("mysql://root:password@localhost:3306/databaseName") store = Store(database) user = User() user.name = u"Mark" print str(user.ID) # None store.add(user) store.flush() # ID is AUTO_INCREMENT print str(user.ID) # 1 (ID) store.commit() # commit all changes to the database </code></pre> <p>To find and object use:</p> <pre><code>michael = store.find(User, User.name == u"Michael").one() print str(user.ID) # 10 </code></pre> <p>Find with primary key:</p> <pre><code>print store.get(User, 1).name #Mark </code></pre> <p>For further information see the <a href="https://storm.canonical.com/Tutorial" rel="nofollow">tutorial</a>.</p>
0
2015-06-03T12:20:16Z
[ "python", "mysql" ]
How do I connect to a MySQL Database in Python?
372,885
<p>How do I connect to a MySQL database using a python program?</p>
674
2008-12-16T21:49:09Z
32,687,395
<p>Just a modification in above answer. Simply run this command to install mysql for python</p> <pre><code>sudo yum install MySQL-python sudo apt-get install MySQL-python </code></pre> <p>remember! It is case sensitive.</p>
2
2015-09-21T04:31:40Z
[ "python", "mysql" ]
How do I connect to a MySQL Database in Python?
372,885
<p>How do I connect to a MySQL database using a python program?</p>
674
2008-12-16T21:49:09Z
34,503,728
<blockquote> <p>Stop Using MySQLDb if you want to avoid installing mysql headers just to access mysql from python.</p> </blockquote> <p>Use <a href="https://github.com/PyMySQL/PyMySQL">pymysql</a> it does all of what MySQLDb does but it was implemented purely in python with <strong><em>NO External Dependencies</em></strong>. This makes the installation process on all operating systems consistent and easy. <code>pymysql</code> is a drop in replacement for MySQLDb and IMHO there is no reason to ever use MySQLDb for anything... EVER! - <em><code>PTSD from installing MySQLDb on Mac OSX and *Nix systems</code></em> but that's just me.</p> <p><strong>Installation</strong></p> <p><code>pip install pymysql</code></p> <blockquote> <p>That's it... you are ready to play.</p> </blockquote> <p><strong>Example usage from pymysql Github repo</strong></p> <pre><code>import pymysql.cursors import pymysql # Connect to the database connection = pymysql.connect(host='localhost', user='user', password='passwd', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: # Create a new record sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ('[email protected]', 'very-secret')) # connection is not autocommit by default. So you must commit to save # your changes. connection.commit() with connection.cursor() as cursor: # Read a single record sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" cursor.execute(sql, ('[email protected]',)) result = cursor.fetchone() print(result) finally: connection.close() </code></pre>
18
2015-12-29T02:52:13Z
[ "python", "mysql" ]
How do I connect to a MySQL Database in Python?
372,885
<p>How do I connect to a MySQL database using a python program?</p>
674
2008-12-16T21:49:09Z
37,970,797
<p>Despite all answers above, in case you do not want to connect to a specific database upfront, for example, if you want to create the database still (!), you can use <code>connection.select_db(database)</code>, as demonstrated in the following.</p> <pre><code>import pymysql.cursors connection = pymysql.connect(host='localhost', user='mahdi', password='mahdi', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) cursor = connection.cursor() cursor.execute("CREATE DATABASE IF NOT EXISTS "+database) connection.select_db(database) sql_create = "CREATE TABLE IF NOT EXISTS "+tablename+(timestamp DATETIME NOT NULL PRIMARY KEY)" cursor.execute(sql_create) connection.commit() cursor.close() </code></pre>
2
2016-06-22T14:18:47Z
[ "python", "mysql" ]
Finding the Current Active Window in Mac OS X using Python
373,020
<p>Is there a way to find the application name of the current active window at a given time on Mac OS X using Python?</p>
12
2008-12-16T22:33:02Z
373,210
<p>First off, do you want the window or the application name? This isn't Windows—an application process on Mac OS X can have multiple windows. (Furthermore, this has also been true of Windows for a few years now, although I have no idea what the API looks like for that.)</p> <p>Second, Carbon or Cocoa?</p> <p>To get the active window in Cocoa:</p> <pre><code>window = NSApp.mainWindow() </code></pre> <p>To get the name of your process in Cocoa:</p> <pre><code>appName = NSProcessInfo.processInfo().processName() </code></pre> <p><strong>Edit:</strong> Oh, I think I know what you want. The name of the frontmost process, right?</p> <p>I don't think there's a way to do it in Cocoa, but here's how to do it in Carbon in C:</p> <pre><code>ProcessSerialNumber psn = { 0L, 0L }; OSStatus err = GetFrontProcess(&amp;psn); /*error check*/ CFStringRef processName = NULL; err = CopyProcessName(&amp;psn, &amp;processName); /*error check*/ </code></pre> <p>Remember to <code>CFRelease(processName)</code> when you're done with it.</p> <p>I'm not sure what that will look like in Python, or if it's even possible. Python doesn't have pointers, which makes that tricky.</p> <p>I know PyObjC would translate the latter argument to <code>CopyProcessName</code> into <code>err, processName = CopyProcessName(…)</code>, but the Carbon bindings don't rely on PyObjC (they're part of core Python 2), and I'm not sure what you do about the PSN either way.</p>
6
2008-12-16T23:52:06Z
[ "python", "objective-c", "cocoa", "osx" ]
Finding the Current Active Window in Mac OS X using Python
373,020
<p>Is there a way to find the application name of the current active window at a given time on Mac OS X using Python?</p>
12
2008-12-16T22:33:02Z
373,310
<p>This should work:</p> <pre><code>#!/usr/bin/python from AppKit import NSWorkspace activeAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName'] print activeAppName </code></pre> <p>Only works on Leopard, or on Tiger if you have PyObjC installed and happen to point at the right python binary in line one (not the case if you've installed universal MacPython, which you'd probably want to do on Tiger). But Peter's answer with the Carbon way of doing this will probably be quite a bit faster, since importing anything from AppKit in Python takes a while, or more accurately, importing something from AppKit for the first time in a Python process takes a while.</p> <p>If you need this inside a PyObjC app, what I describe will work great and fast, since you only experience the lag of importing AppKit once. If you need this to work as a command-line tool, you'll notice the performance hit. If that's relevant to you, you're probably better off building a 10 line Foundation command line tool in Xcode using Peter's code as a starting point.</p>
18
2008-12-17T00:44:22Z
[ "python", "objective-c", "cocoa", "osx" ]
Finding the Current Active Window in Mac OS X using Python
373,020
<p>Is there a way to find the application name of the current active window at a given time on Mac OS X using Python?</p>
12
2008-12-16T22:33:02Z
8,717,955
<p>I post this as an answer because it is too long for a comment. I needed the current frontmost application in a python script that arranges the windows nicely on my screen[1].</p> <p>[1] <a href="https://github.com/SirVer/move_window" rel="nofollow">https://github.com/SirVer/move_window</a></p> <p>Of course, the complete credit goes to Peter! But here is a complete program</p> <pre><code>#include &lt;Carbon/Carbon.h&gt; int main(int, char) { ProcessSerialNumber psn = { 0L, 0L }; OSStatus err = GetFrontProcess(&amp;psn); CFStringRef processName = NULL; err = CopyProcessName(&amp;psn, &amp;processName); printf("%s\n", CFStringGetCStringPtr(processName, NULL)); CFRelease(processName); } </code></pre> <p>Build with <code>gcc -framework Carbon filename.c</code></p>
1
2012-01-03T20:04:07Z
[ "python", "objective-c", "cocoa", "osx" ]
Finding the Current Active Window in Mac OS X using Python
373,020
<p>Is there a way to find the application name of the current active window at a given time on Mac OS X using Python?</p>
12
2008-12-16T22:33:02Z
25,214,024
<p>The method in the accepted answer was deprecated in OS X 10.7+. The current recommended version would be the following:</p> <pre><code>from AppKit import NSWorkspace active_app_name = NSWorkspace.sharedWorkspace().frontmostApplication().localizedName() print active_app_name </code></pre>
8
2014-08-09T00:20:52Z
[ "python", "objective-c", "cocoa", "osx" ]
List all the classes that currently exist
373,067
<p>I'm creating a simple API that creates typed classes based on JSON data that has a mandatory 'type' field defined in it. It uses this string to define a new type, add the fields in the JSON object, instantiate it, and then populate the fields on the instance.</p> <p>What I want to be able to do is allow for these types to be optionally pre-defined in whatever application is using my module. This is so methods and other application-specific attributes not found in the JSON object can be added. I'd like to have my module check if a type already exists, and if it does, use that instead of dynamically creating the type. It would still add attributes from the JSON object, but it would be recycling the existing type.</p> <p>My JSON data is:</p> <pre><code>{ "type": "Person", "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ "212 555-1234", "646 555-4567" ] } </code></pre> <p>My code so far (assume json_object is a dict at this point):</p> <pre><code>if not json_object.has_key('type'): raise TypeError('JSON stream is missing a "type" attribute.') ##### THIS IS WHERE I WANT TO CHECK IF THE TYPE BY THAT NAME EXISTS ALREADY #### # create a type definition and add attributes to it definition = type(json_object['type'], (object,), {}) for key in json_object.keys(): setattr(definition, key, None) # instantiate and populate a test object tester = definition() for key, value in json_object.iteritems(): setattr(tester, key, value) </code></pre>
2
2008-12-16T22:53:42Z
373,076
<p>You can use <code>dir()</code>:</p> <pre><code>Python 2.5.2 (r252:60911, Oct 5 2008, 19:29:17) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; dir() ['__builtins__', '__doc__', '__name__'] &gt;&gt;&gt; class Foo: ... pass ... &gt;&gt;&gt; dir() ['Foo', '__builtins__', '__doc__', '__name__'] &gt;&gt;&gt; type(eval('Foo')) &lt;type 'classobj'&gt; </code></pre>
0
2008-12-16T22:57:15Z
[ "python" ]
List all the classes that currently exist
373,067
<p>I'm creating a simple API that creates typed classes based on JSON data that has a mandatory 'type' field defined in it. It uses this string to define a new type, add the fields in the JSON object, instantiate it, and then populate the fields on the instance.</p> <p>What I want to be able to do is allow for these types to be optionally pre-defined in whatever application is using my module. This is so methods and other application-specific attributes not found in the JSON object can be added. I'd like to have my module check if a type already exists, and if it does, use that instead of dynamically creating the type. It would still add attributes from the JSON object, but it would be recycling the existing type.</p> <p>My JSON data is:</p> <pre><code>{ "type": "Person", "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ "212 555-1234", "646 555-4567" ] } </code></pre> <p>My code so far (assume json_object is a dict at this point):</p> <pre><code>if not json_object.has_key('type'): raise TypeError('JSON stream is missing a "type" attribute.') ##### THIS IS WHERE I WANT TO CHECK IF THE TYPE BY THAT NAME EXISTS ALREADY #### # create a type definition and add attributes to it definition = type(json_object['type'], (object,), {}) for key in json_object.keys(): setattr(definition, key, None) # instantiate and populate a test object tester = definition() for key, value in json_object.iteritems(): setattr(tester, key, value) </code></pre>
2
2008-12-16T22:53:42Z
373,092
<p>If you want to reuse types that you created earlier, it's best to cache them yourself:</p> <pre><code>json_types = {} def get_json_type(name): try: return json_types[name] except KeyError: json_types[name] = t = type(json_object['type'], (object,), {}) # any further initialization of t here return t definition = get_json_type(json_object['type']) tester = definition() # or: tester = get_json_type(json_object['type'])() </code></pre> <p>If you want to have them added to the module namespace, do</p> <pre><code>json_types = globals() </code></pre> <p>instead.</p>
3
2008-12-16T23:06:13Z
[ "python" ]
List all the classes that currently exist
373,067
<p>I'm creating a simple API that creates typed classes based on JSON data that has a mandatory 'type' field defined in it. It uses this string to define a new type, add the fields in the JSON object, instantiate it, and then populate the fields on the instance.</p> <p>What I want to be able to do is allow for these types to be optionally pre-defined in whatever application is using my module. This is so methods and other application-specific attributes not found in the JSON object can be added. I'd like to have my module check if a type already exists, and if it does, use that instead of dynamically creating the type. It would still add attributes from the JSON object, but it would be recycling the existing type.</p> <p>My JSON data is:</p> <pre><code>{ "type": "Person", "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ "212 555-1234", "646 555-4567" ] } </code></pre> <p>My code so far (assume json_object is a dict at this point):</p> <pre><code>if not json_object.has_key('type'): raise TypeError('JSON stream is missing a "type" attribute.') ##### THIS IS WHERE I WANT TO CHECK IF THE TYPE BY THAT NAME EXISTS ALREADY #### # create a type definition and add attributes to it definition = type(json_object['type'], (object,), {}) for key in json_object.keys(): setattr(definition, key, None) # instantiate and populate a test object tester = definition() for key, value in json_object.iteritems(): setattr(tester, key, value) </code></pre>
2
2008-12-16T22:53:42Z
373,104
<p>You can use <code>dir()</code> to get a list of all the names of all objects in the current environment, and you can use <code>globals()</code> to a get a dictionary mapping those names to their values. Thus, to get just the list of objects which are classes, you can do:</p> <pre><code>import types listOfClasses = [cls for cls in globals().values() if type(cls) == types.ClassType] </code></pre>
1
2008-12-16T23:12:58Z
[ "python" ]
XPath in XmlStream.addObserver doesn't work the way it should
373,189
<p>What I want to do is to react only on specified root elements. For example, if user sends XmlStream that looks like:</p> <pre><code>&lt;auth&gt; &lt;login&gt;user&lt;/login&gt; &lt;pass&gt;dupa.8&lt;/pass&gt; &lt;/auth&gt; </code></pre> <p>My method ._auth should be executed. I've done it with addObserver method called inside connectionMade method.</p> <pre><code>self.addObserver("/auth", self._auth) </code></pre> <p>AFAIK XPath - if I write "/auth" it means that I want my root element to be "auth", so that message:</p> <pre><code>&lt;longtagislong&gt; &lt;auth&gt;...&lt;/auth&gt; &lt;/longtagislong&gt; </code></pre> <p>... should be rejected, because auth isn't root.</p> <p>But Twisted however doesn't work the way I thought it should - my _auth method is executed when second message appears (with auth element inside the tree), not the first one - with auth element as a root.</p> <p>So, my question is: how to tell Twisted and addObserver method that I want to react only if root element's name is "auth"?</p>
1
2008-12-16T23:42:35Z
374,548
<p>Ok, finally I got the answer. It's because of XmlStream itself. Connection is active as long as main root element is not closed (for example: <code>&lt;stream/&gt;</code>). Everything inside it is root element for XPath, that's why "/auth" means <code>&lt;stream&gt;&lt;auth&gt;&lt;/auth&gt;&lt;/stream&gt;</code>.</p>
1
2008-12-17T13:40:33Z
[ "python", "twisted" ]
Python regex for MD5 hash
373,194
<p>I've come up with:</p> <pre><code>re.findall("([a-fA-F\d]*)", data) </code></pre> <p>but it's not very fool proof, is there a better way to grab all MD5-hash codes?</p>
15
2008-12-16T23:45:02Z
373,206
<p>How about "([a-fA-F\d]{32})" which requires it to be 32 characters long?</p>
2
2008-12-16T23:51:00Z
[ "python", "regex", "md5" ]
Python regex for MD5 hash
373,194
<p>I've come up with:</p> <pre><code>re.findall("([a-fA-F\d]*)", data) </code></pre> <p>but it's not very fool proof, is there a better way to grab all MD5-hash codes?</p>
15
2008-12-16T23:45:02Z
373,207
<p>Well, since md5 is just a string of 32 hex digits, about all you could add to your expression is a check for "32 digits", perhaps something like this?</p> <pre><code>re.findall(r"([a-fA-F\d]{32})", data) </code></pre>
40
2008-12-16T23:51:02Z
[ "python", "regex", "md5" ]
Python regex for MD5 hash
373,194
<p>I've come up with:</p> <pre><code>re.findall("([a-fA-F\d]*)", data) </code></pre> <p>but it's not very fool proof, is there a better way to grab all MD5-hash codes?</p>
15
2008-12-16T23:45:02Z
373,286
<p>When using regular expressions in Python, you should almost always use the raw string syntax <code>r"..."</code>:</p> <pre><code>re.findall(r"([a-fA-F\d]{32})", data) </code></pre> <p>This will ensure that the backslash in the string is not interpreted by the normal Python escaping, but is instead passed through to the <code>re.findall</code> function so it can see the <code>\d</code> verbatim. In this case you are lucky that <code>\d</code> is not interpreted by the Python escaping, but something like <code>\b</code> (which has completely different meanings in Python escaping and in regular expressions) would be.</p> <p>See the <a href="http://python.org/doc/2.5/lib/module-re.html"><code>re</code> module documentation</a> for more information.</p>
11
2008-12-17T00:31:29Z
[ "python", "regex", "md5" ]
Python regex for MD5 hash
373,194
<p>I've come up with:</p> <pre><code>re.findall("([a-fA-F\d]*)", data) </code></pre> <p>but it's not very fool proof, is there a better way to grab all MD5-hash codes?</p>
15
2008-12-16T23:45:02Z
376,889
<p>Here's a better way to do it than some of the other solutions:</p> <pre><code>re.findall(r'(?i)(?&lt;![a-z0-9])[a-f0-9]{32}(?![a-z0-9])', data) </code></pre> <p>This ensures that the match must be a string of 32 hexadecimal digit characters, <em>but which is not contained within a larger string of other alphanumeric characters.</em> With all the other solutions, if there is a string of 37 contiguous hexadecimals the pattern would match the first 32 and call it a match, or if there is a string of 64 hexadecimals it would split it in half and match each half as an independent match. Excluding these is accomplished via the lookahead and lookbehind assertions, which are non-capturing and will not affect the contents of the match.</p> <p>Note also the (?i) flag which will makes the pattern case-insensitive which saves a little bit of typing, and that wrapping the entire pattern in parentheses is superfluous.</p>
7
2008-12-18T04:13:35Z
[ "python", "regex", "md5" ]
Python regex for MD5 hash
373,194
<p>I've come up with:</p> <pre><code>re.findall("([a-fA-F\d]*)", data) </code></pre> <p>but it's not very fool proof, is there a better way to grab all MD5-hash codes?</p>
15
2008-12-16T23:45:02Z
15,303,876
<h2>MD5 Python Regex With Examples</h2> <p>Since an MD5 is composed of exactly 32 Hexadecimal Characters, and sometimes the hash is presented using lowercase letters, one should account for them as well. </p> <hr> <p>The below example was tested against four different strings:</p> <ul> <li>A valid lowecase MD5 hash</li> <li>A valid uppercase MD5 hash</li> <li>A string of 64 Hexadecimal characters (to ensure a split &amp; match wouldn't occur)</li> <li>A string of 37 Hexadecimal characters (to ensure the leading 32 characters wouldn't match)</li> </ul> <blockquote> <p>900e3f2dd4efc9892793222d7a1cee4a</p> <p>AC905DD4AB2038E5F7EABEAE792AC41B</p> <p>900e3f2dd4efc9892793222d7a1cee4a900e3f2dd4efc9892793222d7a1cee4a</p> <p>900e3f2dd4efc9892793222d7a1cee4a4a4a4</p> </blockquote> <hr> <pre><code> validHash = re.finditer(r'(?=(\b[A-Fa-f0-9]{32}\b))', datahere) result = [match.group(1) for match in validHash] if result: print "Valid MD5" else: print "NOT a Valid MD5" </code></pre> <hr>
3
2013-03-08T21:46:02Z
[ "python", "regex", "md5" ]
Python regex for MD5 hash
373,194
<p>I've come up with:</p> <pre><code>re.findall("([a-fA-F\d]*)", data) </code></pre> <p>but it's not very fool proof, is there a better way to grab all MD5-hash codes?</p>
15
2008-12-16T23:45:02Z
25,231,922
<p>Here's an extremely pedantic expression:</p> <pre><code>re.findall(r"\b([a-f\d]{32}|[A-F\d]{32})\b", data) </code></pre> <ul> <li>string must be exactly 32 characters long,</li> <li>string must be between a word boundary (newline, space, etc),</li> <li>alpha must all be lowercase a-f <strong><em>OR</em></strong> all uppercase A-F, but not mixed.</li> </ul> <p>It's debatable if MD5 is unacceptable if it's a combination of upper and lower, but in my personal experience that only happens when something has gone really wrong, eg:</p> <pre><code>BadBadBadBadBadBadBadBadBadBad00 # obviously not MD5. </code></pre> <p>I have also never seen an all-numeric or an all-alphabetic MD5. There are 6 alpha and 10 numeric symbols in an MD5 string. The chance of getting an all-numeric string is (10/16)^32, or 1 in 3402823. The chance of getting an all-alphabetic string is even smaller (1 in 42 trillion). However, in unknown/unsanitized data, the chance of a 32 character number or string is small but not nearly <strong>so</strong> small. For these reasons, it is sometimes (depending on the data) a good idea to include negative lookaheads that prevent all-numeric or all-alphabetic words for being called as MD5:</p> <pre><code>re.findall(r"\b(?!^[\d]*$)(?!^[a-fA-F]*$)([a-f\d]{32}|[A-F\d]{32})\b", data) 00000000000000000000000000000000 # Null 32bit value, not MD5 01110101001110011101011010101001 # Binary, not MD5 ffffffffffffffffffffffffffffffff # No idea, but not MD5 A32efC32c79823a2123AA8cbDDd3231c # No idea, but not MD5 affa687a87f8abe90d9b9eba09bdbacb # Looks like MD5 C787AFE9D9E86A6A6C78ACE99CA778EE # Looks like MD5 </code></pre>
1
2014-08-10T18:52:35Z
[ "python", "regex", "md5" ]
Close an easygui Python script with the standard 'close' button
373,212
<p>I've created a <em>very</em> simple app, which presents an easygui entrybox() and continues to loop this indefinitely as it receives user input.</p> <p>I can quit the program using the Cancel button as this returns None, but I would also like to be able to use the standard 'close' button to quit the program. (ie. top right of a Windows window, top left of a Mac window) This button currently does nothing.</p> <p>Taking a look at the easygui module I found this line: </p> <pre><code>root.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) </code></pre> <p>This would seem to be the culprit. I'm no TKinter expert but I could probably work out how to alter this handler to act the way I want.</p> <p>However, as I'd rather not mess about with the easygui module, Is there a way to override this behavior from my main script, and have the close button either close the program outright or return None?</p>
3
2008-12-16T23:52:47Z
373,267
<p>I don't know right now, but have you tried something like this?:</p> <pre><code>root.protocol('WM_DELETE_WINDOW', self.quit) </code></pre> <p>or </p> <pre><code>root.protocol('WM_DELETE_WINDOW', self.destroy) </code></pre> <p>I haven't tried, but google something like <code>"Tkinter protocol WM_DELETE_WINDOW"</code></p>
0
2008-12-17T00:24:29Z
[ "python", "user-interface", "tkinter", "easygui" ]
Close an easygui Python script with the standard 'close' button
373,212
<p>I've created a <em>very</em> simple app, which presents an easygui entrybox() and continues to loop this indefinitely as it receives user input.</p> <p>I can quit the program using the Cancel button as this returns None, but I would also like to be able to use the standard 'close' button to quit the program. (ie. top right of a Windows window, top left of a Mac window) This button currently does nothing.</p> <p>Taking a look at the easygui module I found this line: </p> <pre><code>root.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) </code></pre> <p>This would seem to be the culprit. I'm no TKinter expert but I could probably work out how to alter this handler to act the way I want.</p> <p>However, as I'd rather not mess about with the easygui module, Is there a way to override this behavior from my main script, and have the close button either close the program outright or return None?</p>
3
2008-12-16T23:52:47Z
473,695
<p>It would require altering the easygui module, yes. I will get it modified!</p> <p>** I have sent in a e-mail to the EasyGUI creator explaning this [12:12 PM, January 23/09]</p> <p>** I just want to say that the possibility of this change happening - if at all, which I doubt - is very tiny. You see, EasyGUI is intended to be a simple, discrete way to create GUIs. I think that this addition wouldn't help any, especially since the interface is very sequential, so it would be confusing to new users. [12:19 PM, January 23/09]</p> <p>** The EasyGUI creator said this in reply to my e-mail:</p> <blockquote> <p>An easygui dialog should never exit the application -- it should pass back a value to the caller and let the caller decide what to do.</p> <p>But this is an interesting idea. Rather than simply ignoring a click on the "close" icon, easygui boxes could return the same value that a click on the "cancel" button would return. I'll meditate on this.</p> <p>-- Steve Ferg</p> </blockquote> <p>I think that this is progress at least. [2:40 PM, January 23/09]</p>
5
2009-01-23T17:04:00Z
[ "python", "user-interface", "tkinter", "easygui" ]
Close an easygui Python script with the standard 'close' button
373,212
<p>I've created a <em>very</em> simple app, which presents an easygui entrybox() and continues to loop this indefinitely as it receives user input.</p> <p>I can quit the program using the Cancel button as this returns None, but I would also like to be able to use the standard 'close' button to quit the program. (ie. top right of a Windows window, top left of a Mac window) This button currently does nothing.</p> <p>Taking a look at the easygui module I found this line: </p> <pre><code>root.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) </code></pre> <p>This would seem to be the culprit. I'm no TKinter expert but I could probably work out how to alter this handler to act the way I want.</p> <p>However, as I'd rather not mess about with the easygui module, Is there a way to override this behavior from my main script, and have the close button either close the program outright or return None?</p>
3
2008-12-16T23:52:47Z
34,888,002
<p>I found a solution, the answer is below the choice box, when he defines some functions (you can just type to find denyWindowManagerClose) and go to where he defines it. Just erase it and put this code in its place.</p> <pre><code> def denyWindowManagerClose(): #------------------------------------------------------------------ # Changed by ProgrammingBR # Enables the user to close the window without entering a value # Youtube URL: https://www.youtube.com/channel/UCTZh6kWz_iYACNE6Jcy2lhw #------------------------------------------------------------------ global __enterboxText __enterboxText = None boxRoot.quit() </code></pre> <p>You can create a backup file, but this will work for all boxes, the suggestions given here aside from this will not work, I tried the them. if you want to see I have a video on it (it is in Portuguese, but you can follow it) just go to the youtube channel, I will upload it soon and post the link here :)</p>
0
2016-01-19T22:16:44Z
[ "python", "user-interface", "tkinter", "easygui" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
373,348
<p>I don't know if something like that already exists. It would be easy to write your own with time, datetime and/or calendar modules, see <a href="http://docs.python.org/library/time.html" rel="nofollow">http://docs.python.org/library/time.html</a></p> <p>The only concern for a python solution is that your job needs to be always running and possibly be automatically "resurrected" after a reboot, something for which you <strong>do</strong> need to rely on system dependent solutions. </p>
-1
2008-12-17T01:01:33Z
[ "python", "cron" ]
How do I get a Cron like scheduler in Python?
373,335
<p>I'm looking for a library in Python which will provide <code>at</code> and <code>cron</code> like functionality.</p> <p>I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron.</p> <p>For those unfamiliar with <code>cron</code>: you can schedule tasks based upon an expression like: </p> <pre><code> 0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays. </code></pre> <p>The cron time expression syntax is less important, but I would like to have something with this sort of flexibility. </p> <p>If there isn't something that does this for me out-the-box, any suggestions for the building blocks to make something like this would be gratefully received.</p> <p><strong>Edit</strong> I'm not interested in launching processes, just "jobs" also written in Python - python functions. By necessity I think this would be a different thread, but not in a different process.</p> <p>To this end, I'm looking for the expressivity of the cron time expression, but in Python. </p> <p>Cron <em>has</em> been around for years, but I'm trying to be as portable as possible. I cannot rely on its presence.</p>
137
2008-12-17T00:56:31Z
373,410
<p>One thing that in my searches I've seen is python's <a href="http://docs.python.org/library/sched.html"><code>sched</code></a> module which might be the kind of thing you're looking for.</p>
10
2008-12-17T01:45:17Z
[ "python", "cron" ]