title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Are there any good 3rd party GUI products for Python?
449,168
<p>In .Net you have companies like DevEpxress, and Infragistics that offer a range of GUI widgets. Is there any market like that for Python GUI widgets? I'm thinking specifically about widgets like the DevExpress xtraGrid Suite.</p> <p>Edit 01-16-09: For Example:</p> <p><a href="http://www.devexpress.com/Downloads/NET/OnlineDemos.xml" rel="nofollow">http://www.devexpress.com/Downloads/NET/OnlineDemos.xml</a> <a href="http://demos.devexpress.com/ASPxGridViewDemos/" rel="nofollow">http://demos.devexpress.com/ASPxGridViewDemos/</a></p> <p><a href="http://www.infragistics.com/products/default.aspx" rel="nofollow">http://www.infragistics.com/products/default.aspx</a></p>
5
2009-01-16T01:11:49Z
23,121,183
<p>I don't see any commercial packages for GUI in Python but as I know Kivy is a good option for creating fast and beautiful GUI <a href="https://github.com/kivy/kivy" rel="nofollow">https://github.com/kivy/kivy</a></p>
0
2014-04-16T22:20:01Z
[ "python", "user-interface" ]
How do I determine the size of an object in Python?
449,560
<p>In C, we can find the size of an <code>int</code>, <code>char</code>, etc. I want to know how to get size of objects like a string, integer, etc. in Python.</p> <p>Related question: <a href="http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple">How many bytes per element are there in a Python list (tuple)?</a></p> <p>I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused.</p>
271
2009-01-16T05:07:12Z
449,707
<p>First: an answer.</p> <pre><code>import sys try: print sys.getsizeof(object) except AttributeError: print "sys.getsizeof exists in Python ≥2.6" </code></pre> <p>Discussion:<br /> In Python, you cannot ever access "direct" memory addresses. Why, then, would you need or want to know how many such addresses are occupied by a given object?? It's a question that's entirely inappropriate at that level of abstraction. When you're painting your house, you don't ask what frequencies of light are absorbed or reflected by each of the constituent atoms within the paint, you just ask what color it is -- the details of the physical characteristics that create that color are beside the point. Similarly, the number of bytes of memory that a given Python object occupies is beside the point.</p> <p>So, why are you trying to use Python to write C code? :)</p>
2
2009-01-16T06:58:40Z
[ "python", "object", "memory", "memory-management", "sizeof" ]
How do I determine the size of an object in Python?
449,560
<p>In C, we can find the size of an <code>int</code>, <code>char</code>, etc. I want to know how to get size of objects like a string, integer, etc. in Python.</p> <p>Related question: <a href="http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple">How many bytes per element are there in a Python list (tuple)?</a></p> <p>I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused.</p>
271
2009-01-16T05:07:12Z
450,034
<p>Just use the <a href="http://docs.python.org/library/sys.html#sys.getsizeof">sys.getsizeof</a> function defined in the <code>sys</code> module.</p> <blockquote> <p><code>sys.getsizeof(object[, default])</code>:</p> <p>Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.</p> <p>The <code>default</code> argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause a <code>TypeError</code>.</p> <p><code>getsizeof</code> calls the object’s <code>__sizeof__</code> method and adds an additional garbage collector overhead if the object is managed by the garbage collector.</p> </blockquote> <p>Usage example, in python 3.0:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; x = 2 &gt;&gt;&gt; sys.getsizeof(x) 14 &gt;&gt;&gt; sys.getsizeof(sys.getsizeof) 32 &gt;&gt;&gt; sys.getsizeof('this') 38 &gt;&gt;&gt; sys.getsizeof('this also') 48 </code></pre> <p>If you are in python &lt; 2.6 and don't have <code>sys.getsizeof</code> you can use <a href="http://code.activestate.com/recipes/546530/">this extensive module</a> instead. Never used it though.</p>
316
2009-01-16T10:42:37Z
[ "python", "object", "memory", "memory-management", "sizeof" ]
How do I determine the size of an object in Python?
449,560
<p>In C, we can find the size of an <code>int</code>, <code>char</code>, etc. I want to know how to get size of objects like a string, integer, etc. in Python.</p> <p>Related question: <a href="http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple">How many bytes per element are there in a Python list (tuple)?</a></p> <p>I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused.</p>
271
2009-01-16T05:07:12Z
450,351
<p>This can be more complicated than it looks depending on how you want to count things. For instance, if you have a list of ints, do you want the size of the list containing the <em>references</em> to the ints? (ie. list only, not what is contained in it), or do you want to include the actual data pointed to, in which case you need to deal with duplicate references, and how to prevent double-counting when two objects contain references to the same object. </p> <p>You may want to take a look at one of the python memory profilers, such as <a href="http://pysizer.8325.org/">pysizer</a> to see if they meet your needs.</p>
11
2009-01-16T13:00:14Z
[ "python", "object", "memory", "memory-management", "sizeof" ]
How do I determine the size of an object in Python?
449,560
<p>In C, we can find the size of an <code>int</code>, <code>char</code>, etc. I want to know how to get size of objects like a string, integer, etc. in Python.</p> <p>Related question: <a href="http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple">How many bytes per element are there in a Python list (tuple)?</a></p> <p>I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused.</p>
271
2009-01-16T05:07:12Z
3,373,511
<p>For numpy arrays, <code>getsizeof</code> doesn't work - for me it always returns 40 for some reason:</p> <pre><code>from pylab import * from sys import getsizeof A = rand(10) B = rand(10000) </code></pre> <p>Then (in ipython):</p> <pre><code>In [64]: getsizeof(A) Out[64]: 40 In [65]: getsizeof(B) Out[65]: 40 </code></pre> <p>Happily, though:</p> <pre><code>In [66]: A.nbytes Out[66]: 80 In [67]: B.nbytes Out[67]: 80000 </code></pre>
60
2010-07-30T16:33:00Z
[ "python", "object", "memory", "memory-management", "sizeof" ]
How do I determine the size of an object in Python?
449,560
<p>In C, we can find the size of an <code>int</code>, <code>char</code>, etc. I want to know how to get size of objects like a string, integer, etc. in Python.</p> <p>Related question: <a href="http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple">How many bytes per element are there in a Python list (tuple)?</a></p> <p>I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused.</p>
271
2009-01-16T05:07:12Z
15,207,478
<p>Here is a quick script I wrote based on the previous answers to list sizes of all variables</p> <pre><code>for i in dir(): try: print (i, eval(i).nbytes ) except: print (i, sys.getsizeof(eval(i)) ) </code></pre>
4
2013-03-04T17:34:04Z
[ "python", "object", "memory", "memory-management", "sizeof" ]
How do I determine the size of an object in Python?
449,560
<p>In C, we can find the size of an <code>int</code>, <code>char</code>, etc. I want to know how to get size of objects like a string, integer, etc. in Python.</p> <p>Related question: <a href="http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple">How many bytes per element are there in a Python list (tuple)?</a></p> <p>I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused.</p>
271
2009-01-16T05:07:12Z
30,316,760
<blockquote> <h1>How do I determine the size of an object in Python?</h1> </blockquote> <p>The answer, "Just use sys.getsizeof" is not a complete answer. </p> <p>That answer <em>does</em> work for builtin objects directly, but it does not account for what those objects may contain, specifically, what types, such as tuples, lists, dicts, and sets contain. They can contain instances each other, as well as numbers, strings and other objects.</p> <h1>A More Complete Answer</h1> <p>Using 64 bit Python 2.7 from the Anaconda distribution and <code>guppy.hpy</code> along with <code>sys.getsizeof</code>, I have determined the minimum size of the following objects, and note that sets and dicts preallocate space so empty ones don't grow again until after a set amount (which may vary by implementation of the language):</p> <pre><code>Bytes type empty + scaling notes 24 int NA 28 long NA 37 str + 1 byte per additional character 52 unicode + 4 bytes per additional character 56 tuple + 8 bytes per additional item 72 list + 32 for first, 8 for each additional 232 set sixth item increases to 744; 22nd, 2280; 86th, 8424 280 dict sixth item increases to 1048; 22nd, 3352; 86th, 12568 64 class inst has a __dict__ attr, same scaling as dict above 16 __slots__ class with slots has no dict, seems to store in mutable tuple-like structure. 120 func def doesn't include default args and other attrs 904 class def has a proxy __dict__ structure for class attrs 104 old class makes sense, less stuff, has real dict though. </code></pre> <p>I think 8 bytes per additional item to reference makes a lot of sense on a 64 bit machine. Those 8 bytes point to the place in memory the contained item is at. The 4 bytes are fixed width for unicode in Python 2, if I recall correctly, but in Python 3, str becomes a unicode of width equal to the max width of the characters.</p> <p>(And for more on slots, <a href="http://stackoverflow.com/a/28059785/541136">see this answer</a> )</p> <h1>Recursive Visitor for a More Complete Function</h1> <p>To cover most of these types, I wrote this recursive function to try to estimate the size of most Python objects, including most builtins, types in the collections module, and custom types (slotted and otherwise):</p> <pre><code>import sys from numbers import Number from collections import Set, Mapping, deque try: # Python 2 zero_depth_bases = (basestring, Number, xrange, bytearray) iteritems = 'iteritems' except NameError: # Python 3 zero_depth_bases = (str, bytes, Number, range, bytearray) iteritems = 'items' def getsize(obj_0): """Recursively iterate to sum size of object &amp; members.""" def inner(obj, _seen_ids = set()): obj_id = id(obj) if obj_id in _seen_ids: return 0 _seen_ids.add(obj_id) size = sys.getsizeof(obj) if isinstance(obj, zero_depth_bases): pass # bypass remaining control flow and return elif isinstance(obj, (tuple, list, Set, deque)): size += sum(inner(i) for i in obj) elif isinstance(obj, Mapping) or hasattr(obj, iteritems): size += sum(inner(k) + inner(v) for k, v in getattr(obj, iteritems)()) # Check for custom object instances - may subclass above too if hasattr(obj, '__dict__'): size += inner(vars(obj)) if hasattr(obj, '__slots__'): # can have __slots__ with __dict__ size += sum(inner(getattr(obj, s)) for s in obj.__slots__ if hasattr(obj, s)) return size return inner(obj_0) </code></pre> <p>And I tested it rather casually (I should unittest it):</p> <pre><code>&gt;&gt;&gt; getsize(['a', tuple('bcd'), Foo()]) 344 &gt;&gt;&gt; getsize(Foo()) 16 &gt;&gt;&gt; getsize(tuple('bcd')) 194 &gt;&gt;&gt; getsize(['a', tuple('bcd'), Foo(), {'foo': 'bar', 'baz': 'bar'}]) 752 &gt;&gt;&gt; getsize({'foo': 'bar', 'baz': 'bar'}) 400 &gt;&gt;&gt; getsize({}) 280 &gt;&gt;&gt; getsize({'foo':'bar'}) 360 &gt;&gt;&gt; getsize('foo') 40 &gt;&gt;&gt; class Bar(): ... def baz(): ... pass &gt;&gt;&gt; getsize(Bar()) 352 &gt;&gt;&gt; getsize(Bar().__dict__) 280 &gt;&gt;&gt; sys.getsizeof(Bar()) 72 &gt;&gt;&gt; getsize(Bar.__dict__) 872 &gt;&gt;&gt; sys.getsizeof(Bar.__dict__) 280 </code></pre> <p>It kind of breaks down on class definitions and function definitions because I don't go after all of their attributes, but since they should only exist once in memory for the process, their size really doesn't matter too much.</p>
88
2015-05-19T04:26:33Z
[ "python", "object", "memory", "memory-management", "sizeof" ]
How do I determine the size of an object in Python?
449,560
<p>In C, we can find the size of an <code>int</code>, <code>char</code>, etc. I want to know how to get size of objects like a string, integer, etc. in Python.</p> <p>Related question: <a href="http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple">How many bytes per element are there in a Python list (tuple)?</a></p> <p>I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused.</p>
271
2009-01-16T05:07:12Z
31,388,142
<p>In case anyone comes across this question and needs a more "bulletproof" solution than sys.getsizeof or the procedure provided by Aaron Hall, there is a recipe <a href="http://code.activestate.com/recipes/546530-size-of-python-objects-revised/" rel="nofollow">here</a> that attempts to deal with issues such as classes and bytecode objects in a principled and flexible way (it is far too long to replicate or meaningfully summarize here unfortunately). </p>
3
2015-07-13T16:02:05Z
[ "python", "object", "memory", "memory-management", "sizeof" ]
How do I determine the size of an object in Python?
449,560
<p>In C, we can find the size of an <code>int</code>, <code>char</code>, etc. I want to know how to get size of objects like a string, integer, etc. in Python.</p> <p>Related question: <a href="http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple">How many bytes per element are there in a Python list (tuple)?</a></p> <p>I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused.</p>
271
2009-01-16T05:07:12Z
33,631,772
<p>There is a module called <a href="https://pypi.python.org/pypi/Pympler" rel="nofollow">Pympler</a> which contains the <code>asizeof</code> module.</p> <p>Use as follows:</p> <pre><code>from pympler import asizeof asizeof.asizeof(my_object) </code></pre> <p>Unlike <code>sys.getsizeof</code>, it <strong>works for your self-created objects</strong>. It does not work with numpy objects, as described by <a href="http://stackoverflow.com/a/3373511/1587329">@Mike Dewar's answer</a>.</p> <pre><code>&gt;&gt;&gt; asizeof.asizeof(tuple('bcd')) 200 &gt;&gt;&gt; asizeof.asizeof({'foo': 'bar', 'baz': 'bar'}) 400 &gt;&gt;&gt; asizeof.asizeof({}) 280 &gt;&gt;&gt; asizeof.asizeof({'foo':'bar'}) 360 &gt;&gt;&gt; asizeof.asizeof('foo') 40 &gt;&gt;&gt; asizeof.asizeof(Bar()) 352 &gt;&gt;&gt; asizeof.asizeof(Bar().__dict__) 280 </code></pre>
4
2015-11-10T14:01:35Z
[ "python", "object", "memory", "memory-management", "sizeof" ]
How do I determine the size of an object in Python?
449,560
<p>In C, we can find the size of an <code>int</code>, <code>char</code>, etc. I want to know how to get size of objects like a string, integer, etc. in Python.</p> <p>Related question: <a href="http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple">How many bytes per element are there in a Python list (tuple)?</a></p> <p>I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused.</p>
271
2009-01-16T05:07:12Z
38,515,297
<p>Having run into this problem many times myself, I wrote up a small function (inspired by @aaron-hall's answer) &amp; tests that does what I would have expected sys.getsizeof to do:</p> <p><a href="https://github.com/bosswissam/pysize" rel="nofollow">https://github.com/bosswissam/pysize</a></p> <p>If you're interested in the backstory, <a href="https://goshippo.com/blog/measure-real-size-any-python-object/" rel="nofollow">here it is</a></p> <p>EDIT: Attaching the code below for easy reference. To see the most up-to-date code, please check the github link.</p> <pre><code> import sys def get_size(obj, seen=None): """Recursively finds size of objects""" size = sys.getsizeof(obj) if seen is None: seen = set() obj_id = id(obj) if obj_id in seen: return 0 # Important mark as seen *before* entering recursion to gracefully handle # self-referential objects seen.add(obj_id) if isinstance(obj, dict): size += sum([get_size(v, seen) for v in obj.values()]) size += sum([get_size(k, seen) for k in obj.keys()]) elif hasattr(obj, '__dict__'): size += get_size(obj.__dict__, seen) elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)): size += sum([get_size(i, seen) for i in obj]) return size </code></pre>
3
2016-07-21T22:21:07Z
[ "python", "object", "memory", "memory-management", "sizeof" ]
Is there a tool for converting VB to a scripting language, e.g. Python or Ruby?
449,734
<p>I've discovered <a href="http://vb2py.sourceforge.net/" rel="nofollow">VB2Py</a>, but it's been silent for almost 5 years. Are there any other tools out there which could be used to convert VB6 projects to Python, Ruby, Tcl, whatever?</p>
2
2009-01-16T07:09:38Z
449,779
<p>I doubt there would be a good solution for that since VB6 relies too much on the windows API and VBRun libraries though you could translate code that does something else besides GUI operations</p> <p>Is there something special you need to do with that code? You could compile your VB6 functionality and expose it as a COM object and connect it to python with <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython" rel="nofollow">IronPython</a> or <a href="http://www.ironruby.net/" rel="nofollow">IronRuby</a> which are Python and Ruby implementations in .Net thus, allowing you to access .Net functionality although im not quite sure if COM exposed objects are easily pluggable to those interpreters.</p> <p>Maybe if you explain a bit more what you want to do you would get a wiser response.</p>
3
2009-01-16T07:47:53Z
[ "python", "vb6" ]
Is there a tool for converting VB to a scripting language, e.g. Python or Ruby?
449,734
<p>I've discovered <a href="http://vb2py.sourceforge.net/" rel="nofollow">VB2Py</a>, but it's been silent for almost 5 years. Are there any other tools out there which could be used to convert VB6 projects to Python, Ruby, Tcl, whatever?</p>
2
2009-01-16T07:09:38Z
449,789
<p>Compile the VB code either into a normal DLL or a COM DLL. All Pythons on Windows, including the vanilla ActivePython distribution (IronPython isn't required) can connect to both types of DLLs.</p> <p>I think this is your best option. As Gustavo said, finding something that will compile arbitrary VB6 code into Python sounds like an unachievable dream.</p>
3
2009-01-16T07:56:30Z
[ "python", "vb6" ]
Is there a tool for converting VB to a scripting language, e.g. Python or Ruby?
449,734
<p>I've discovered <a href="http://vb2py.sourceforge.net/" rel="nofollow">VB2Py</a>, but it's been silent for almost 5 years. Are there any other tools out there which could be used to convert VB6 projects to Python, Ruby, Tcl, whatever?</p>
2
2009-01-16T07:09:38Z
450,198
<p>Generally, Python is much, much more expressive than VB. Things which took many lines of code in VB can be represented more simply in Python.</p> <p>If the VB is truly epic in scale, a manual rewrite may be hard. But maintaining VB6 may be just as hard. </p> <p>If the VB is intimately tied to Windows GUI presentation, any rewrite may be hard. Some VB programs can have a cryptic organization where critical features are buried in the VB code attached to GUI controls.</p> <p>If the VB is not very big and doesn't use mystery features of the GUI controls, it will probably be much simpler to rewrite the program and do a good job of refactoring the legacy code into something leaner and cleaner.</p>
1
2009-01-16T11:57:25Z
[ "python", "vb6" ]
How can I split a url string up into separate parts in Python?
449,775
<p>I decided that I'll learn python tonight :) I know C pretty well (wrote an OS in it) so I'm not a noob in programming so everything in python seems pretty easy, but I don't know how to solve this problem : let's say I have this address:</p> <p><a href="http://example.com/random/folder/path.html">http://example.com/random/folder/path.html</a> Now how can I create two strings from this, one containing the "base" name of the server, so in this example it would be <a href="http://example.com/">http://example.com/</a> and another containing the thing without the last filename, so in this example it would be <a href="http://example.com/random/folder/">http://example.com/random/folder/</a> . Also I of course know the possibility to just find the 3rd and last slash respectively but maybe you know a better way :] Also it would be cool to have the trailing slash in both cases but I don't care since it can be added easily. So anyone has a good, fast, effective solution for this? Or is there only "my" solution, finding the slashes?</p> <p>Thanks!</p>
9
2009-01-16T07:43:22Z
449,782
<p>I have no experience with python, but I found the urlparse module, which should do the job:</p> <p><a href="http://docs.python.org/library/urlparse.html">http://docs.python.org/library/urlparse.html</a></p>
8
2009-01-16T07:49:55Z
[ "python", "url", "parsing" ]
How can I split a url string up into separate parts in Python?
449,775
<p>I decided that I'll learn python tonight :) I know C pretty well (wrote an OS in it) so I'm not a noob in programming so everything in python seems pretty easy, but I don't know how to solve this problem : let's say I have this address:</p> <p><a href="http://example.com/random/folder/path.html">http://example.com/random/folder/path.html</a> Now how can I create two strings from this, one containing the "base" name of the server, so in this example it would be <a href="http://example.com/">http://example.com/</a> and another containing the thing without the last filename, so in this example it would be <a href="http://example.com/random/folder/">http://example.com/random/folder/</a> . Also I of course know the possibility to just find the 3rd and last slash respectively but maybe you know a better way :] Also it would be cool to have the trailing slash in both cases but I don't care since it can be added easily. So anyone has a good, fast, effective solution for this? Or is there only "my" solution, finding the slashes?</p> <p>Thanks!</p>
9
2009-01-16T07:43:22Z
449,800
<p>In Python a lot of operations are done using lists. The urlparse module mentioned by Sebasian Dietz may well solve your specific problem, but if you're generally interested in Pythonic ways to find slashes in strings, for example, try something like this:</p> <pre><code>url = 'http://example.com/random/folder/path.html' # Create a list of each bit between slashes slashparts = url.split('/') # Now join back the first three sections 'http:', '' and 'example.com' basename = '/'.join(slashparts[:3]) + '/' # All except the last one dirname = '/'.join(slashparts[:-1]) + '/' print 'slashparts = %s' % slashparts print 'basename = %s' % basename print 'dirname = %s' % dirname </code></pre> <p>The output of this program is this:</p> <pre> slashparts = ['http:', '', 'example.com', 'random', 'folder', 'path.html'] basename = http://example.com/ dirname = http://example.com/random/folder/ </pre> <p>The interesting bits are <code>split</code>, <code>join</code>, the slice notation array[A:B] (including negatives for offsets-from-the-end) and, as a bonus, the <code>%</code> operator on strings to give printf-style formatting.</p>
5
2009-01-16T08:08:32Z
[ "python", "url", "parsing" ]
How can I split a url string up into separate parts in Python?
449,775
<p>I decided that I'll learn python tonight :) I know C pretty well (wrote an OS in it) so I'm not a noob in programming so everything in python seems pretty easy, but I don't know how to solve this problem : let's say I have this address:</p> <p><a href="http://example.com/random/folder/path.html">http://example.com/random/folder/path.html</a> Now how can I create two strings from this, one containing the "base" name of the server, so in this example it would be <a href="http://example.com/">http://example.com/</a> and another containing the thing without the last filename, so in this example it would be <a href="http://example.com/random/folder/">http://example.com/random/folder/</a> . Also I of course know the possibility to just find the 3rd and last slash respectively but maybe you know a better way :] Also it would be cool to have the trailing slash in both cases but I don't care since it can be added easily. So anyone has a good, fast, effective solution for this? Or is there only "my" solution, finding the slashes?</p> <p>Thanks!</p>
9
2009-01-16T07:43:22Z
449,805
<p>If this is the extent of your URL parsing, Python's inbuilt rpartition will do the job:</p> <pre><code>&gt;&gt;&gt; URL = "http://example.com/random/folder/path.html" &gt;&gt;&gt; Segments = URL.rpartition('/') &gt;&gt;&gt; Segments[0] 'http://example.com/random/folder' &gt;&gt;&gt; Segments[2] 'path.html' </code></pre> <p>From <a href="http://www.python.org/doc/3.0/library/stdtypes.html?highlight=rpartition#str.rpartition">Pydoc</a>, str.rpartition:</p> <p><code>Splits the string at the last occurrence of sep, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself</code></p> <p>What this means is that rpartition does the searching for you, and splits the string at the last (right most) occurrence of the character you specify (in this case / ). It returns a tuple containing:</p> <pre><code>(everything to the left of char , the character itself , everything to the right of char) </code></pre>
8
2009-01-16T08:11:11Z
[ "python", "url", "parsing" ]
How can I split a url string up into separate parts in Python?
449,775
<p>I decided that I'll learn python tonight :) I know C pretty well (wrote an OS in it) so I'm not a noob in programming so everything in python seems pretty easy, but I don't know how to solve this problem : let's say I have this address:</p> <p><a href="http://example.com/random/folder/path.html">http://example.com/random/folder/path.html</a> Now how can I create two strings from this, one containing the "base" name of the server, so in this example it would be <a href="http://example.com/">http://example.com/</a> and another containing the thing without the last filename, so in this example it would be <a href="http://example.com/random/folder/">http://example.com/random/folder/</a> . Also I of course know the possibility to just find the 3rd and last slash respectively but maybe you know a better way :] Also it would be cool to have the trailing slash in both cases but I don't care since it can be added easily. So anyone has a good, fast, effective solution for this? Or is there only "my" solution, finding the slashes?</p> <p>Thanks!</p>
9
2009-01-16T07:43:22Z
449,811
<p>The urlparse module in python 2.x (or urllib.parse in python 3.x) would be the way to do it.</p> <pre><code>&gt;&gt;&gt; from urllib.parse import urlparse &gt;&gt;&gt; url = 'http://example.com/random/folder/path.html' &gt;&gt;&gt; parse_object = urlparse(url) &gt;&gt;&gt; parse_object.netloc 'example.com' &gt;&gt;&gt; parse_object.path '/random/folder/path.html' &gt;&gt;&gt; parse_object.scheme 'http' &gt;&gt;&gt; </code></pre> <p>If you wanted to do more work on the path of the file under the url, you can use the posixpath module :</p> <pre><code>&gt;&gt;&gt; from posixpath import basename, dirname &gt;&gt;&gt; basename(parse_object.path) 'path.html' &gt;&gt;&gt; dirname(parse_object.path) '/random/folder' </code></pre> <p>After that, you can use posixpath.join to glue the parts together.</p> <p>EDIT: I totally forgot that windows users will choke on the path separator in os.path. I read the posixpath module docs, and it has a special reference to URL manipulation, so all's good.</p>
36
2009-01-16T08:14:36Z
[ "python", "url", "parsing" ]
How can I split a url string up into separate parts in Python?
449,775
<p>I decided that I'll learn python tonight :) I know C pretty well (wrote an OS in it) so I'm not a noob in programming so everything in python seems pretty easy, but I don't know how to solve this problem : let's say I have this address:</p> <p><a href="http://example.com/random/folder/path.html">http://example.com/random/folder/path.html</a> Now how can I create two strings from this, one containing the "base" name of the server, so in this example it would be <a href="http://example.com/">http://example.com/</a> and another containing the thing without the last filename, so in this example it would be <a href="http://example.com/random/folder/">http://example.com/random/folder/</a> . Also I of course know the possibility to just find the 3rd and last slash respectively but maybe you know a better way :] Also it would be cool to have the trailing slash in both cases but I don't care since it can be added easily. So anyone has a good, fast, effective solution for this? Or is there only "my" solution, finding the slashes?</p> <p>Thanks!</p>
9
2009-01-16T07:43:22Z
14,722,294
<p>Thank you very much to the other answerers here, who pointed me in the right direction via the answers they have given!</p> <p>It seems like the posixpath module mentioned by <code>sykora</code>'s answer is not available in my Python setup (python 2.7.3).</p> <p>As per <a href="http://www.doughellmann.com/PyMOTW/urllib/#paths-vs-urls" rel="nofollow">this article</a> it seems that the "proper" way to do this would be using...</p> <ul> <li><code>urlparse.urlparse</code> and <code>urlparse.urlunparse</code> can be used to detach and reattach the base of the URL</li> <li>The functions of <code>os.path</code> can be used to manipulate the path</li> <li><code>urllib.url2pathname</code> and <code>urllib.pathname2url</code> (to make path name manipulation portable, so it can work on Windows and the like)</li> </ul> <p>So for example (not including reattaching the base URL)...</p> <pre><code>&gt;&gt;&gt; import urlparse, urllib, os.path &gt;&gt;&gt; os.path.dirname(urllib.url2pathname(urlparse.urlparse("http://example.com/random/folder/path.html").path)) '/random/folder' </code></pre>
2
2013-02-06T05:35:32Z
[ "python", "url", "parsing" ]
How to check if a file can be created inside given directory on MS XP/Vista?
450,210
<p>I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it.</p> <p>I have created directory for test purposes, let's call it <code>C:\foo</code>. </p> <p>I have following permissions to <code>C:\foo</code>: </p> <ul> <li>Traversing directory/Execute file </li> <li>Removing subfolders and files</li> <li>Removing</li> <li>Read permissions</li> <li>Change permissions</li> <li>Take ownership</li> </ul> <p>I don't have any of the following permissions to <code>C:\foo</code>: </p> <ul> <li>Full Control </li> <li>File creation </li> <li>Folder creation </li> </ul> <p>I have tried following approaches, so far:</p> <p><code><br /> os.access('C:\foo', os.W_OK) == True </p> <p>st = os.stat('C:\foo')<br /> mode = st[stat.ST_MODE]<br /> mode &amp; stat.S_IWRITE == True </code> </p> <p>I believe that this is caused by the fact that I can rename folder, so it is changeable for me. But it's content - not. </p> <p>Does anyone know how can I write code that will check for a given directory if current user has permissions to create file in that directory?</p> <p>In brief - I want to check if current user has <strong>File creation</strong> and <strong>Folder creation</strong> permissions for given folder name.</p> <p>EDIT: The need for such code arisen from the Test case no 3 from 'Certified for Windows Vista' program, which states: </p> <blockquote> <ol> <li>The application must not allow the Least-Privileged user to save any files to Windows System directory in order to pass this test case. </li> </ol> </blockquote> <p>Should this be understood as 'Application may try to save file in Windows System directory, but shouldn't crash on failure?' or rather 'Application has to perform security checks before trying to save file?' </p> <p>Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%? </p>
5
2009-01-16T12:01:24Z
450,259
<p>I wouldn't waste time and LOCs on checking for permissions. Ultimate test of file creation in Windows is the creation itself. Other factors may come into play (such as existing files (or worse, folders) with the same name, disk space, background processes. These conditions can even change between the time you make the initial check and the time you actually try to create your file.</p> <p>So, if I had a scenario like that, I would just design my method to not lose any data in case of failure, to go ahead and try to create my file, and offer the user an option to change the selected directory and try again if creation fails.</p>
3
2009-01-16T12:18:28Z
[ "python", "windows", "winapi", "windows-vista", "permissions" ]
How to check if a file can be created inside given directory on MS XP/Vista?
450,210
<p>I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it.</p> <p>I have created directory for test purposes, let's call it <code>C:\foo</code>. </p> <p>I have following permissions to <code>C:\foo</code>: </p> <ul> <li>Traversing directory/Execute file </li> <li>Removing subfolders and files</li> <li>Removing</li> <li>Read permissions</li> <li>Change permissions</li> <li>Take ownership</li> </ul> <p>I don't have any of the following permissions to <code>C:\foo</code>: </p> <ul> <li>Full Control </li> <li>File creation </li> <li>Folder creation </li> </ul> <p>I have tried following approaches, so far:</p> <p><code><br /> os.access('C:\foo', os.W_OK) == True </p> <p>st = os.stat('C:\foo')<br /> mode = st[stat.ST_MODE]<br /> mode &amp; stat.S_IWRITE == True </code> </p> <p>I believe that this is caused by the fact that I can rename folder, so it is changeable for me. But it's content - not. </p> <p>Does anyone know how can I write code that will check for a given directory if current user has permissions to create file in that directory?</p> <p>In brief - I want to check if current user has <strong>File creation</strong> and <strong>Folder creation</strong> permissions for given folder name.</p> <p>EDIT: The need for such code arisen from the Test case no 3 from 'Certified for Windows Vista' program, which states: </p> <blockquote> <ol> <li>The application must not allow the Least-Privileged user to save any files to Windows System directory in order to pass this test case. </li> </ol> </blockquote> <p>Should this be understood as 'Application may try to save file in Windows System directory, but shouldn't crash on failure?' or rather 'Application has to perform security checks before trying to save file?' </p> <p>Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%? </p>
5
2009-01-16T12:01:24Z
450,297
<p>I recently wrote a App to pass a set of test to obtain the ISV status from Microsoft and I also add that condition. The way I understood it was that if the user is Least Priveledge then he won't have permission to write in the system folders. So I approached the problem the the way Ishmaeel described. I try to create the file and catch the exception then inform the user that he doesn't have permission to write files to that directory.</p> <p>In my understanding an Least-Priviledged user will not have the necessary permissions to write to those folders, if he has then he is not a Least-Priveledge user.</p> <blockquote> <p>Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%?</p> </blockquote> <p>In my opinion? Yes.</p>
3
2009-01-16T12:36:05Z
[ "python", "windows", "winapi", "windows-vista", "permissions" ]
How to check if a file can be created inside given directory on MS XP/Vista?
450,210
<p>I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it.</p> <p>I have created directory for test purposes, let's call it <code>C:\foo</code>. </p> <p>I have following permissions to <code>C:\foo</code>: </p> <ul> <li>Traversing directory/Execute file </li> <li>Removing subfolders and files</li> <li>Removing</li> <li>Read permissions</li> <li>Change permissions</li> <li>Take ownership</li> </ul> <p>I don't have any of the following permissions to <code>C:\foo</code>: </p> <ul> <li>Full Control </li> <li>File creation </li> <li>Folder creation </li> </ul> <p>I have tried following approaches, so far:</p> <p><code><br /> os.access('C:\foo', os.W_OK) == True </p> <p>st = os.stat('C:\foo')<br /> mode = st[stat.ST_MODE]<br /> mode &amp; stat.S_IWRITE == True </code> </p> <p>I believe that this is caused by the fact that I can rename folder, so it is changeable for me. But it's content - not. </p> <p>Does anyone know how can I write code that will check for a given directory if current user has permissions to create file in that directory?</p> <p>In brief - I want to check if current user has <strong>File creation</strong> and <strong>Folder creation</strong> permissions for given folder name.</p> <p>EDIT: The need for such code arisen from the Test case no 3 from 'Certified for Windows Vista' program, which states: </p> <blockquote> <ol> <li>The application must not allow the Least-Privileged user to save any files to Windows System directory in order to pass this test case. </li> </ol> </blockquote> <p>Should this be understood as 'Application may try to save file in Windows System directory, but shouldn't crash on failure?' or rather 'Application has to perform security checks before trying to save file?' </p> <p>Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%? </p>
5
2009-01-16T12:01:24Z
450,344
<p>I agree with the other answers that the way to do this is to try to create the file and catch the exception. </p> <p><em>However</em>, on Vista beware of UAC! See for example <a href="http://stackoverflow.com/questions/370837/why-does-my-application-allow-me-to-save-files-to-the-windows-and-system32-folder">"Why does my application allow me to save files to the Windows and System32 folders in Vista?"</a>: To support old applications, Vista will "pretend" to create the file while in reality it creates it in the so-called Virtual Store under the current user's profile. </p> <p>To avoid this you have to specifically tell Vista that you don't want administrative privileges, by including the appropriate commands in the .exe's manifest, see the question linked above.</p>
2
2009-01-16T12:56:30Z
[ "python", "windows", "winapi", "windows-vista", "permissions" ]
How to check if a file can be created inside given directory on MS XP/Vista?
450,210
<p>I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it.</p> <p>I have created directory for test purposes, let's call it <code>C:\foo</code>. </p> <p>I have following permissions to <code>C:\foo</code>: </p> <ul> <li>Traversing directory/Execute file </li> <li>Removing subfolders and files</li> <li>Removing</li> <li>Read permissions</li> <li>Change permissions</li> <li>Take ownership</li> </ul> <p>I don't have any of the following permissions to <code>C:\foo</code>: </p> <ul> <li>Full Control </li> <li>File creation </li> <li>Folder creation </li> </ul> <p>I have tried following approaches, so far:</p> <p><code><br /> os.access('C:\foo', os.W_OK) == True </p> <p>st = os.stat('C:\foo')<br /> mode = st[stat.ST_MODE]<br /> mode &amp; stat.S_IWRITE == True </code> </p> <p>I believe that this is caused by the fact that I can rename folder, so it is changeable for me. But it's content - not. </p> <p>Does anyone know how can I write code that will check for a given directory if current user has permissions to create file in that directory?</p> <p>In brief - I want to check if current user has <strong>File creation</strong> and <strong>Folder creation</strong> permissions for given folder name.</p> <p>EDIT: The need for such code arisen from the Test case no 3 from 'Certified for Windows Vista' program, which states: </p> <blockquote> <ol> <li>The application must not allow the Least-Privileged user to save any files to Windows System directory in order to pass this test case. </li> </ol> </blockquote> <p>Should this be understood as 'Application may try to save file in Windows System directory, but shouldn't crash on failure?' or rather 'Application has to perform security checks before trying to save file?' </p> <p>Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%? </p>
5
2009-01-16T12:01:24Z
451,131
<pre><code>import os import tempfile def can_create_file(folder_path): try: tempfile.TemporaryFile(dir=folder_path) return True except OSError: return False def can_create_folder(folder_path): try: name = tempfile.mkdtemp(dir=folder_path) os.rmdir(name) return True except OSError: return False </code></pre>
1
2009-01-16T16:52:23Z
[ "python", "windows", "winapi", "windows-vista", "permissions" ]
Python Path
450,290
<p>I am installing active python, django. I really dont know how to set the python path in vista environment system. first of all will it work in vista.</p>
1
2009-01-16T12:33:20Z
450,304
<p>Perhaps this helps: It's a <a href="http://www.neuralwiki.org/index.php?title=Guide_to_installing_Python_in_Windows_Vista" rel="nofollow">Guide to installing Python in Windows Vista</a>.</p>
1
2009-01-16T12:37:56Z
[ "python" ]
Python Path
450,290
<p>I am installing active python, django. I really dont know how to set the python path in vista environment system. first of all will it work in vista.</p>
1
2009-01-16T12:33:20Z
450,545
<p>Remember that in addition to setting <code>PYTHONPATH</code> in your system environment, you'll also want to assign <code>DJANGO_SETTINGS_MODULE</code>.</p>
0
2009-01-16T14:28:41Z
[ "python" ]
Python Path
450,290
<p>I am installing active python, django. I really dont know how to set the python path in vista environment system. first of all will it work in vista.</p>
1
2009-01-16T12:33:20Z
10,585,779
<h1>Temporary Change</h1> <p>To change the python path temporarily (i.e., for one interactive session), just append to <code>sys.path</code> like this:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', 'C:\\Program Files\\PyScripter\\Lib\\rpyc.zip', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages'] &gt;&gt;&gt; sys.path.append(directory_to_be_added) </code></pre> <h1>Permanent (More or Less) Change</h1> <p>Go to <code>Computer -&gt; System Properties (Either by the big button near the title bar or in the context-menu by right-clicking) -&gt; Advanced Settings (in the right-hand nav bar) -&gt; Environment Variables</code>. In the <code>System Variables</code>, either add a variable called <code>PYTHONPATH</code> (if it's not already there, i.e., if you haven't done this before) or edit the existing variable.</p> <p>You should enter the directories normally (take care to use backslashes, not the normal ones) separated by a semicolon (<code>;</code>) w/o a space. Be careful not to end with a semicolon. </p> <p>The directories that you just entered now will be <em>added</em> to <code>sys.path</code> whenever you open a interpreter, they won't replace it. Also, the changes will take place only after you've restarted the interpreter.</p> <p><hr> <sup>Source: <a href="http://greeennotebook.com/2010/06/how-to-change-pythonpath-in-windows-and-ubuntu/" rel="nofollow">http://greeennotebook.com/2010/06/how-to-change-pythonpath-in-windows-and-ubuntu/</a></sup></p>
2
2012-05-14T14:54:43Z
[ "python" ]
Deleting lines from wx.TextCtrl
450,306
<p>I am using a wx.TextCtrl to output text from a network daemon.<br /> As the output is quite verbose, the size of text in the TextCtrl can become huge (BTW is there any limitation on the size of the contents of a TextCtrl?)<br /> I would like to delete the top N lines from the TextCtrl when TextCtrl.GetNumberOfLines() exceeds a predefined treshold. What is the best way to accomplish this?</p>
2
2009-01-16T12:38:18Z
450,315
<p>How about the Remove method of wx.TextCtrl?</p> <p>Whenever you're about to add new text, you can check if the current text appears too long and remove some from the start.</p>
0
2009-01-16T12:43:31Z
[ "python", "wxpython", "wx.textctrl" ]
Deleting lines from wx.TextCtrl
450,306
<p>I am using a wx.TextCtrl to output text from a network daemon.<br /> As the output is quite verbose, the size of text in the TextCtrl can become huge (BTW is there any limitation on the size of the contents of a TextCtrl?)<br /> I would like to delete the top N lines from the TextCtrl when TextCtrl.GetNumberOfLines() exceeds a predefined treshold. What is the best way to accomplish this?</p>
2
2009-01-16T12:38:18Z
450,317
<p>The <a href="http://docs.wxwidgets.org/2.6/wx_wxtextctrl.html#wxtextctrlsetmaxlength" rel="nofollow">SetMaxLength reference</a> says that the limitation depends on the underlying native text control,but should be 32KB at least.</p> <p>About deleting the top N lines, you could try to call <a href="http://docs.wxwidgets.org/2.6/wx_wxtextctrl.html#wxtextctrlgetlinelength" rel="nofollow">GetLineLength</a> for 0..N-1, calculate the sum S and then call <a href="http://docs.wxwidgets.org/2.6/wx_wxtextctrl.html#wxtextctrlremove" rel="nofollow">Remove</a>(0,S)</p>
1
2009-01-16T12:44:11Z
[ "python", "wxpython", "wx.textctrl" ]
Deleting lines from wx.TextCtrl
450,306
<p>I am using a wx.TextCtrl to output text from a network daemon.<br /> As the output is quite verbose, the size of text in the TextCtrl can become huge (BTW is there any limitation on the size of the contents of a TextCtrl?)<br /> I would like to delete the top N lines from the TextCtrl when TextCtrl.GetNumberOfLines() exceeds a predefined treshold. What is the best way to accomplish this?</p>
2
2009-01-16T12:38:18Z
450,324
<p>Remove() should do the trick.</p> <p>TextCtrl without wx.TE_RICH flag can't have more than 64 KB on Windows.</p>
0
2009-01-16T12:46:25Z
[ "python", "wxpython", "wx.textctrl" ]
Deleting lines from wx.TextCtrl
450,306
<p>I am using a wx.TextCtrl to output text from a network daemon.<br /> As the output is quite verbose, the size of text in the TextCtrl can become huge (BTW is there any limitation on the size of the contents of a TextCtrl?)<br /> I would like to delete the top N lines from the TextCtrl when TextCtrl.GetNumberOfLines() exceeds a predefined treshold. What is the best way to accomplish this?</p>
2
2009-01-16T12:38:18Z
38,823,051
<p>You should be able to use <a href="https://wxpython.org/Phoenix/docs/html/wx.TextCtrl.html#wx.TextCtrl.PositionToXY" rel="nofollow"><code>wx.TextCtrl.PositionToXY()</code></a> and <a href="https://wxpython.org/Phoenix/docs/html/wx.TextCtrl.html#wx.TextCtrl.XYToPosition" rel="nofollow"><code>wx.TextCtrl.XYToPosition()</code></a> to convert position (measured in characters from start) to and from a <code>(column, line_num)</code> pair.</p> <p>Figure out the position <code>i</code> of the <em>n</em>'th line, then call <a href="https://wxpython.org/Phoenix/docs/html/wx.TextEntry.html#wx.TextEntry.Remove" rel="nofollow"><code>wx.TextCtrl.Remove(0, i)</code></a> to remove the first <em>n-1</em> lines.</p>
0
2016-08-08T07:02:59Z
[ "python", "wxpython", "wx.textctrl" ]
Cookie Problem in Python
450,787
<p>I'm working on a simple HTML scraper for Hulu in python 2.6 and am having problems with logging on to my account. Here's my code so far:</p> <pre><code>import urllib import urllib2 from cookielib import CookieJar #make a cookie and redirect handlers cookies = CookieJar() cookie_handler= urllib2.HTTPCookieProcessor(cookies) redirect_handler= urllib2.HTTPRedirectHandler() opener = urllib2.build_opener(redirect_handler,cookie_handler)#make opener w/ handlers #build the url login_info = {'username':USER,'password':PASS}#USER and PASS are defined data = urllib.urlencode(login_info) req = urllib2.Request("http://www.hulu.com/account/authenticate",data)#make the request test = opener.open(req) #open the page print test.read() #print html results </code></pre> <p>The code compiles and runs, but all that prints is:</p> <pre><code>Login.onError("Please \074a href=\"/support/login_faq#cant_login\"\076enable cookies\074/a\076 and try again."); </code></pre> <p>I assume there is some error in how I'm handling cookies, but just can't seem to spot it. I've heard Mechanize is a very useful module for this type of program, but as this seems to be the only speed bump left, I was hoping to find my bug. </p>
2
2009-01-16T15:39:35Z
451,306
<p>What you're seeing is a ajax return. It is probably using javascript to set the cookie, and screwing up your attempts to authenticate.</p>
4
2009-01-16T17:33:52Z
[ "python", "cookies", "urllib2" ]
Cookie Problem in Python
450,787
<p>I'm working on a simple HTML scraper for Hulu in python 2.6 and am having problems with logging on to my account. Here's my code so far:</p> <pre><code>import urllib import urllib2 from cookielib import CookieJar #make a cookie and redirect handlers cookies = CookieJar() cookie_handler= urllib2.HTTPCookieProcessor(cookies) redirect_handler= urllib2.HTTPRedirectHandler() opener = urllib2.build_opener(redirect_handler,cookie_handler)#make opener w/ handlers #build the url login_info = {'username':USER,'password':PASS}#USER and PASS are defined data = urllib.urlencode(login_info) req = urllib2.Request("http://www.hulu.com/account/authenticate",data)#make the request test = opener.open(req) #open the page print test.read() #print html results </code></pre> <p>The code compiles and runs, but all that prints is:</p> <pre><code>Login.onError("Please \074a href=\"/support/login_faq#cant_login\"\076enable cookies\074/a\076 and try again."); </code></pre> <p>I assume there is some error in how I'm handling cookies, but just can't seem to spot it. I've heard Mechanize is a very useful module for this type of program, but as this seems to be the only speed bump left, I was hoping to find my bug. </p>
2
2009-01-16T15:39:35Z
451,605
<p>The error message you are getting back could be misleading. For example the server might be looking at <em>user-agent</em> and seeing that say it's not one of the supported browsers, or looking at <i>HTTP_REFERER</i> expecting it to be coming from hulu domain. My point is there are two many variables coming in the request to keep guessing them one by one</p> <p>I recommend using an http analyzer tool, e.g. <a href="http://www.charlesproxy.com/" rel="nofollow">Charles</a> or the one in <a href="https://addons.mozilla.org/en-US/firefox/addon/1843" rel="nofollow">Firebug</a> to figure out what (header fields, cookies, parameters) the client sends to server when you doing hulu login via a browser. This will give you the <b>exact</b> request that you need to construct in your python code.</p>
2
2009-01-16T19:21:48Z
[ "python", "cookies", "urllib2" ]
ImportError when using Google App Engine
450,883
<p>When I add the following line to Google's helloworld example:</p> <pre><code> from reportlab.pdfgen import canvas </code></pre> <p>I get the following error:</p> <pre><code> &lt;type 'exceptions.ImportError'&gt;: No module named reportlab.pdfgen </code></pre> <p>I can get at the reportlab.pdfgen library from the python console. Why can't I get at it from google's dev_appserver?</p>
0
2009-01-16T15:59:54Z
450,944
<p>Copying the module locally worked.</p> <p>From </p> <pre><code>Python\Lib\site-packages\reportlab </code></pre> <p>to </p> <pre><code>helloworld\reportlab </code></pre>
3
2009-01-16T16:12:15Z
[ "python", "google-app-engine", "import" ]
ImportError when using Google App Engine
450,883
<p>When I add the following line to Google's helloworld example:</p> <pre><code> from reportlab.pdfgen import canvas </code></pre> <p>I get the following error:</p> <pre><code> &lt;type 'exceptions.ImportError'&gt;: No module named reportlab.pdfgen </code></pre> <p>I can get at the reportlab.pdfgen library from the python console. Why can't I get at it from google's dev_appserver?</p>
0
2009-01-16T15:59:54Z
450,951
<p>I believe the google app engine does not include all the standard python modules. I know that anything that works with sockes is disabled, such as urllib.urlopen().</p>
0
2009-01-16T16:12:56Z
[ "python", "google-app-engine", "import" ]
What's the most efficient way to access sibling dictionary value in a Python dict?
451,690
<p>In Python, I've got a list of dictionaries that looks like this:</p> <pre><code>matchings = [ {'id': 'someid1', 'domain': 'somedomain1.com'}, {'id': 'someid2', 'domain': 'somedomain2.com'}, {'id': 'someid3', 'domain': 'somedomain3.com'} ] </code></pre> <p>and, I have a variable:</p> <pre><code>the_id = 'someid3' </code></pre> <p>What's the most efficient way to retrieve the domain value of the item?</p>
3
2009-01-16T19:45:51Z
451,700
<p>You can use a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p> <pre><code>domains = [matching['domain'] for matching in matchings if matching['id'] == the_id] </code></pre> <p>Which follows the format standard format of:</p> <pre><code>resulting_list = [item_to_return for item in items if condition] </code></pre> <p>And basically encapsulates all the following functionality:</p> <pre><code>domains = [] for matching in matchings: if matching['id'] == the_id: domains.append(matching['domain']) </code></pre> <p>All that functionality is represented in a single line using list comprehensions.</p>
5
2009-01-16T19:47:57Z
[ "python", "loops", "dictionary", "list-comprehension" ]
What's the most efficient way to access sibling dictionary value in a Python dict?
451,690
<p>In Python, I've got a list of dictionaries that looks like this:</p> <pre><code>matchings = [ {'id': 'someid1', 'domain': 'somedomain1.com'}, {'id': 'someid2', 'domain': 'somedomain2.com'}, {'id': 'someid3', 'domain': 'somedomain3.com'} ] </code></pre> <p>and, I have a variable:</p> <pre><code>the_id = 'someid3' </code></pre> <p>What's the most efficient way to retrieve the domain value of the item?</p>
3
2009-01-16T19:45:51Z
451,710
<p>The fact that there are dictionaries in the list doesn't really matter - the problem reduces to finding an item in a list where some property is true. To that end, some variation on @<a href="#451700" rel="nofollow">Soviut</a>'s answer is the way to go: loop or list comprehension, examining each of the items until a match is found. There's no inherent ordering of the items, so you couldn't even rely on something as helpful as <a href="http://docs.python.org/library/bisect.html" rel="nofollow">bisect</a>.</p>
0
2009-01-16T19:49:47Z
[ "python", "loops", "dictionary", "list-comprehension" ]
What's the most efficient way to access sibling dictionary value in a Python dict?
451,690
<p>In Python, I've got a list of dictionaries that looks like this:</p> <pre><code>matchings = [ {'id': 'someid1', 'domain': 'somedomain1.com'}, {'id': 'someid2', 'domain': 'somedomain2.com'}, {'id': 'someid3', 'domain': 'somedomain3.com'} ] </code></pre> <p>and, I have a variable:</p> <pre><code>the_id = 'someid3' </code></pre> <p>What's the most efficient way to retrieve the domain value of the item?</p>
3
2009-01-16T19:45:51Z
451,722
<p>The best I can figure is to do an explicit search. This is one area where I get disappointed in Python is that it doesn't give you a strong set of decoupled building blocks like in the C++ STL algorithms</p> <pre><code>[d["domain"] for d in matchings if d["id"] == "someid3"] </code></pre>
1
2009-01-16T19:52:12Z
[ "python", "loops", "dictionary", "list-comprehension" ]
What's the most efficient way to access sibling dictionary value in a Python dict?
451,690
<p>In Python, I've got a list of dictionaries that looks like this:</p> <pre><code>matchings = [ {'id': 'someid1', 'domain': 'somedomain1.com'}, {'id': 'someid2', 'domain': 'somedomain2.com'}, {'id': 'someid3', 'domain': 'somedomain3.com'} ] </code></pre> <p>and, I have a variable:</p> <pre><code>the_id = 'someid3' </code></pre> <p>What's the most efficient way to retrieve the domain value of the item?</p>
3
2009-01-16T19:45:51Z
451,819
<p>I'd restructure <code>matchings</code>.</p> <pre><code>from collections import defaultdict matchings_ix= defaultdict(list) for m in matchings: matchings_ix[m['id']].append( m ) </code></pre> <p>Now the most efficient lookup is</p> <pre><code>matchings_ix[ d ] </code></pre>
2
2009-01-16T20:16:04Z
[ "python", "loops", "dictionary", "list-comprehension" ]
What's the most efficient way to access sibling dictionary value in a Python dict?
451,690
<p>In Python, I've got a list of dictionaries that looks like this:</p> <pre><code>matchings = [ {'id': 'someid1', 'domain': 'somedomain1.com'}, {'id': 'someid2', 'domain': 'somedomain2.com'}, {'id': 'someid3', 'domain': 'somedomain3.com'} ] </code></pre> <p>and, I have a variable:</p> <pre><code>the_id = 'someid3' </code></pre> <p>What's the most efficient way to retrieve the domain value of the item?</p>
3
2009-01-16T19:45:51Z
5,503,404
<p>I really like to use <a href="http://docs.python.org/library/functions.html#filter" rel="nofollow">filter</a> in this sort of situation. It takes a function and an iterable and returns the list of elements where the function returns True (in Python 3.x it returns an iterator).</p> <pre><code>&gt;&gt;&gt; filter(lambda x: x['id'] == 'someid3', matchings) &lt;&lt;&lt; [{'domain': 'somedomain3.com', 'id': 'someid3'}] </code></pre> <p>You could get a list of all domains by using a list comprehension:</p> <pre><code>&gt;&gt;&gt; [x['domain'] for x in filter(lambda x: x['id'] == 'someid3', matchings)] &lt;&lt;&lt; ['somedomain3.com'] </code></pre>
0
2011-03-31T16:52:26Z
[ "python", "loops", "dictionary", "list-comprehension" ]
What is the correct way to backup ZODB blobs?
451,952
<p>I am using plone.app.blob to store large ZODB objects in a blobstorage directory. This reduces size pressure on Data.fs but I have not been able to find any advice on backing up this data.</p> <p>I am already backing up Data.fs by pointing a network backup tool at a directory of repozo backups. Should I simply point that tool at the blobstorage directory to backup my blobs? </p> <p>What if the database is being repacked or blobs are being added and deleted while the copy is taking place? Are there files in the blobstorage directory that must be copied over in a certain order?</p>
6
2009-01-16T20:51:01Z
453,942
<p>Backing up "blobstorage" will do it. No need for a special order or anything else, it's very simple.</p> <p>All operations in Plone are fully transactional, so hitting the backup in the middle of a transaction should work just fine. This is why you can do live backups of the ZODB. Without knowing what file system you're on, I'd guess that it should work as intended.</p>
3
2009-01-17T20:16:28Z
[ "python", "plone", "zope", "zodb", "blobstorage" ]
What is the correct way to backup ZODB blobs?
451,952
<p>I am using plone.app.blob to store large ZODB objects in a blobstorage directory. This reduces size pressure on Data.fs but I have not been able to find any advice on backing up this data.</p> <p>I am already backing up Data.fs by pointing a network backup tool at a directory of repozo backups. Should I simply point that tool at the blobstorage directory to backup my blobs? </p> <p>What if the database is being repacked or blobs are being added and deleted while the copy is taking place? Are there files in the blobstorage directory that must be copied over in a certain order?</p>
6
2009-01-16T20:51:01Z
676,364
<p>Your backup strategy for the FileStorage is fine. However, making a backup of any database that stores data in multiple files never is easy as your copy has to happen with no writes to the various files. For the FileStorage a blind stupid copy is fine as it's just a single file. (Using repozo is even better.)</p> <p>In this case (with BlobStorage combined with FileStorage) I have to point to the regular backup advice:</p> <ul> <li>take the db offline while making a file-system copy</li> <li>use snapshot tools like LVM to freeze the disk at a given point</li> <li>do a transactional export (not feasable in practice)</li> </ul>
1
2009-03-24T06:51:57Z
[ "python", "plone", "zope", "zodb", "blobstorage" ]
What is the correct way to backup ZODB blobs?
451,952
<p>I am using plone.app.blob to store large ZODB objects in a blobstorage directory. This reduces size pressure on Data.fs but I have not been able to find any advice on backing up this data.</p> <p>I am already backing up Data.fs by pointing a network backup tool at a directory of repozo backups. Should I simply point that tool at the blobstorage directory to backup my blobs? </p> <p>What if the database is being repacked or blobs are being added and deleted while the copy is taking place? Are there files in the blobstorage directory that must be copied over in a certain order?</p>
6
2009-01-16T20:51:01Z
2,664,479
<p>It should be safe to do a repozo backup of the Data.fs followed by an rsync of the blobstorage directory, as long as the database doesn't get packed while those two operations are happening.</p> <p>This is because, at least when using blobs with FileStorage, modifications to a blob always results in the creation of a new file named based on the object id and transaction id. So if new or updated blobs are written after the Data.fs is backed up, it shouldn't be a problem, as the files that are referenced by the Data.fs should still be around. Deletion of a blob doesn't result in the file being removed until the database is packed, so that should be okay too.</p> <p>Performing a backup in a different order, or with packing during the backup, may result in a backup Data.fs that references blobs that are not included in the backup.</p>
12
2010-04-18T23:51:13Z
[ "python", "plone", "zope", "zodb", "blobstorage" ]
What is the correct way to backup ZODB blobs?
451,952
<p>I am using plone.app.blob to store large ZODB objects in a blobstorage directory. This reduces size pressure on Data.fs but I have not been able to find any advice on backing up this data.</p> <p>I am already backing up Data.fs by pointing a network backup tool at a directory of repozo backups. Should I simply point that tool at the blobstorage directory to backup my blobs? </p> <p>What if the database is being repacked or blobs are being added and deleted while the copy is taking place? Are there files in the blobstorage directory that must be copied over in a certain order?</p>
6
2009-01-16T20:51:01Z
5,263,021
<p>I have an script that copies for a month the blobs using hard links ( so you have and historial of the blobs as the Data.fs ):</p> <p>backup.sh </p> <pre><code>#!/bin/sh # per a fer un full : ./cron_nocturn.sh full ZEO_FOLDER=/var/plone/ZEO # Zeo port ZEO_PORT = 8023 # Name of the DB ZEO_DB = zodb1 BACKUP_FOLDER=/backup/plone LOGBACKUP=/var/plone/ZEO/backup.log BACKUPDIR=`date +%d` echo "INICI BACKUP" &gt;&gt; $LOGBACKUP echo `date` &gt;&gt; $LOGBACKUP # Fem el packing if [ "$1" = "full" ]; then $ZEO_FOLDER/bin/zeopack -S $ZEO_DB -p $ZEO_PORT -h 127.0.0.1 echo " Comprovant folders" #mirem si existeix el folder de backup if ! [ -x $BACKUP_FOLDER/$ZEO_DB ]; then mkdir $BACKUP_FOLDER/$ZEO_DB fi #mirem si existeix el backup folder del dia if ! [ -x $BACKUP_FOLDER/blobs/$BACKUPDIR/ ] ; then mkdir $BACKUP_FOLDER/blobs/$BACKUPDIR/ fi echo " Backup Data.fs" # backup de Data.fs if [ "$1" = "full" ]; then echo " Copiant Data.fs" $ZEO_FOLDER/bin/repozo -B -F -r $BACKUP_FOLDER/$ZEO_DB/ -f $ZEO_FOLDER/var/filestorage/Data_$ZEO_DB.fs echo " Purgant backups antics" $ZEO_FOLDER/neteja.py -l $BACKUP_FOLDER/$ZEO_DB -k 2 else $ZEO_FOLDER/bin/repozo -B -r $BACKUP_FOLDER/$ZEO_DB/ -f $ZEO_FOLDER/var/filestorage/Data_$ZEO_DB.fs fi echo " Copiant blobs" # backup blobs rm -rf $BACKUP_FOLDER/blobs/$BACKUPDIR cd $BACKUP_FOLDER/current-blobs &amp;&amp; find . -print | cpio -dplm $BACKUP_FOLDER/blobs/$BACKUPDIR rsync --force --ignore-errors --delete --update -a $ZEO_FOLDER/var/blobs/ $BACKUP_FOLDER/current-blobs/ echo "FI BACKUP" &gt;&gt; $LOGBACKUP echo `date` &gt;&gt; $LOGBACKUP </code></pre> <p>neteja.py</p> <pre><code>#!/usr/bin/python2.4 # neteja.py -l [directori_desti] -k [numero_fulls_a_mantenir] # Script que neteja un directori amb backups i guarda nomes els ultims fulls que li especifiquis # Es basa en la utilitzacio de collective.recipe.backup # Author: Victor Fernandez de Alba &lt;[email protected]&gt; import sys, getopt sys.path[0:0] = [ '/var/plone/genwebupcZEO/produccio/eggs/collective.recipe.backup-1.3-py2.4.egg', '/var/plone/genwebupcZEO/produccio/eggs/zc.buildout-1.4.2-py2.4.egg', '/var/plone/genwebupcZEO/produccio/eggs/zc.recipe.egg-1.2.2-py2.4.egg', '/var/plone/genwebupcZEO/produccio/eggs/setuptools-0.6c11-py2.4.egg', ] import collective.recipe.backup.repozorunner argv = sys.argv[1:] try: opts, args = getopt.getopt(argv, "l:k:", ["location=", "keep="]) except getopt.GetoptError: print "neteja.py -l [directori_desti] -k [numero_fulls_a_mantenir]" sys.exit(2) for opt, arg in opts: if opt in ("-l", "--location"): location = arg elif opt in ("-k", "--keep"): keep = arg if len(opts)&lt;2: print "neteja.py -l [directori_desti] -k [numero_fulls_a_mantenir]" sys.exit(2) collective.recipe.backup.repozorunner.cleanup(location, keep) </code></pre>
2
2011-03-10T16:54:01Z
[ "python", "plone", "zope", "zodb", "blobstorage" ]
Making a method private in a python subclass
451,963
<p>Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :</p> <pre><code>class A: def __init__(self): #do something here def method(self): #some code here class B(A): def __init__(self): A.__init__(self) #additional initialization goes here def method(self): #this overrides the method ( and possibly make it private here ) </code></pre> <p>from this point forward , I don't want any class that extends from B to be able to call <code>method</code> . Is this possible ?</p> <p>EDIT : a "logical" reason for this is that I don't want users to call methods in wrong order.</p>
24
2009-01-16T20:53:50Z
451,969
<p>To make a method sort of private, you can name-mangle a method like so:</p> <pre><code>class Foo: def __blah(): pass class Bar(Foo): def callBlah(): self.__blah() # will throw an exception </code></pre> <p>But subclasses can still find your methods through introspection if they really want to. </p> <p>But Python (by deliberate design and choice) has no notion of private members.</p>
5
2009-01-16T20:56:31Z
[ "python", "oop", "inheritance" ]
Making a method private in a python subclass
451,963
<p>Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :</p> <pre><code>class A: def __init__(self): #do something here def method(self): #some code here class B(A): def __init__(self): A.__init__(self) #additional initialization goes here def method(self): #this overrides the method ( and possibly make it private here ) </code></pre> <p>from this point forward , I don't want any class that extends from B to be able to call <code>method</code> . Is this possible ?</p> <p>EDIT : a "logical" reason for this is that I don't want users to call methods in wrong order.</p>
24
2009-01-16T20:53:50Z
452,023
<p>There's no way to truly do this in Python. Rather unpythonic, it is. </p> <p>As Guido would say, we're all consenting adults here.</p> <p>Here's a good <a href="http://mail.python.org/pipermail/tutor/2003-October/025932.html">summary of the philosophy behind everything in Python being public</a>.</p>
26
2009-01-16T21:09:56Z
[ "python", "oop", "inheritance" ]
Making a method private in a python subclass
451,963
<p>Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :</p> <pre><code>class A: def __init__(self): #do something here def method(self): #some code here class B(A): def __init__(self): A.__init__(self) #additional initialization goes here def method(self): #this overrides the method ( and possibly make it private here ) </code></pre> <p>from this point forward , I don't want any class that extends from B to be able to call <code>method</code> . Is this possible ?</p> <p>EDIT : a "logical" reason for this is that I don't want users to call methods in wrong order.</p>
24
2009-01-16T20:53:50Z
452,028
<p>Python is distributed as source. The very idea of a private method makes very little sense.</p> <p>The programmer who wants to extend <code>B</code>, frustrated by a privacy issue, looks at the source for <code>B</code>, copies and pastes the source code for <code>method</code> into the subclass <code>C</code>. </p> <p>What have you gained through "privacy"? The best you can hope for is to frustrate your potential customers into copying and pasting.</p> <p>At worst, they discard your package because they can't extend it.</p> <p>And yes, all open source is extended in one way or another. You can't foresee everything and every use to which you code will be put. Preventing some future use is hard to do when the code is distributed as source.</p> <p>See <a href="http://stackoverflow.com/questions/261638/how-do-i-protect-python-code">http://stackoverflow.com/questions/261638/how-do-i-protect-python-code</a></p> <p><hr /></p> <p><strong>Edit</strong> On "idiot-proof" code.</p> <p>First, python is distributed as source 90% of the time. So, any idiot who downloads, installs, and then refuses to read the API guide and calls the methods out of order still has the source to figure out what went wrong.</p> <p>We have three classes of idiots.</p> <ul> <li><p>People who refuse to read the API guide (or skim it and ignore the relevant parts) and call the methods out of order in spite of the documentation. You can try to make something private, but it won't help because they'll do something else wrong -- and complain about it. [I won't name names, but I've worked with folks who seem to spend a lot of time calling the API's improperly. Also, you'll see questions like this on SO.]</p> <p>You can only help them with a working code sample they can cut and paste.</p></li> <li><p>People who are confused by API's and call the methods every different way you can imagine (and some you can't.) You can try to make something private, but they'll never get the API.</p> <p>You can only help them by providing the working code sample; even then, they'll cut and paste it incorrectly.</p></li> <li><p>People who reject your API and want to rewrite it to make it "idiot proof".</p> <p>You can provide them a working code sample, but they don't like your API and will insist on rewriting it. They'll tell you that your API is crazy and they've improved on it.</p> <p>You can engage these folks in an escalating arms race of "idiot-proofing". Everything you put together they take apart.</p></li> </ul> <p>At this point, what has privacy done for you? Some people will refuse to understand it; some people are confused by it; and some people want to work around it.</p> <p>How about public, and let the folks you're calling "idiots" learn from your code?</p>
15
2009-01-16T21:11:46Z
[ "python", "oop", "inheritance" ]
Making a method private in a python subclass
451,963
<p>Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :</p> <pre><code>class A: def __init__(self): #do something here def method(self): #some code here class B(A): def __init__(self): A.__init__(self) #additional initialization goes here def method(self): #this overrides the method ( and possibly make it private here ) </code></pre> <p>from this point forward , I don't want any class that extends from B to be able to call <code>method</code> . Is this possible ?</p> <p>EDIT : a "logical" reason for this is that I don't want users to call methods in wrong order.</p>
24
2009-01-16T20:53:50Z
452,049
<p>This may be a fair approximation. Lexical scoping to the "rescue":</p> <pre><code>#!/usr/bin/env python class Foo(object): def __init__(self, name): self.name = name self.bar() def bar(self): def baz(): print "I'm private" print self.name def quux(): baz() self.quux = quux if __name__ == "__main__": f = Foo("f") f.quux() g = Foo("g") g.quux() f.quux() </code></pre> <p>Prints:</p> <pre><code>I'm private f I'm private g I'm private f </code></pre>
7
2009-01-16T21:16:58Z
[ "python", "oop", "inheritance" ]
Making a method private in a python subclass
451,963
<p>Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :</p> <pre><code>class A: def __init__(self): #do something here def method(self): #some code here class B(A): def __init__(self): A.__init__(self) #additional initialization goes here def method(self): #this overrides the method ( and possibly make it private here ) </code></pre> <p>from this point forward , I don't want any class that extends from B to be able to call <code>method</code> . Is this possible ?</p> <p>EDIT : a "logical" reason for this is that I don't want users to call methods in wrong order.</p>
24
2009-01-16T20:53:50Z
452,240
<p>I am surprised that no one has mentioned this, but prefixing the method name with a single underscore is the correct way of labelling it as "private". It's not really <em>private</em> of course, (as explained in other answers), but there you go.</p> <pre><code>def _i_am_private(self): """If you call me from a subclass you are a naughty person!""" </code></pre>
11
2009-01-16T22:09:27Z
[ "python", "oop", "inheritance" ]
Making a method private in a python subclass
451,963
<p>Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :</p> <pre><code>class A: def __init__(self): #do something here def method(self): #some code here class B(A): def __init__(self): A.__init__(self) #additional initialization goes here def method(self): #this overrides the method ( and possibly make it private here ) </code></pre> <p>from this point forward , I don't want any class that extends from B to be able to call <code>method</code> . Is this possible ?</p> <p>EDIT : a "logical" reason for this is that I don't want users to call methods in wrong order.</p>
24
2009-01-16T20:53:50Z
452,316
<p>You can prefix methods and members with a single or double underscore. A single underscore implies "please don't use me, I'm supposed to be used only by this class", and a double underscore instructs the Python compiler to mangle the method/member name with the class name; as long as the class and its subclasses don't have the same name, the methods/members can be considered "private".</p> <p>However, the solution to your requirements so far is to write clear documentation. If you don't want your users to call methods in the wrong order, then say so in the documentation.</p> <p>After all, even C++ privates aren't that private. For example think the old trick:</p> <pre><code>#define private public #include &lt;module&gt; </code></pre>
12
2009-01-16T22:42:42Z
[ "python", "oop", "inheritance" ]
Making a method private in a python subclass
451,963
<p>Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :</p> <pre><code>class A: def __init__(self): #do something here def method(self): #some code here class B(A): def __init__(self): A.__init__(self) #additional initialization goes here def method(self): #this overrides the method ( and possibly make it private here ) </code></pre> <p>from this point forward , I don't want any class that extends from B to be able to call <code>method</code> . Is this possible ?</p> <p>EDIT : a "logical" reason for this is that I don't want users to call methods in wrong order.</p>
24
2009-01-16T20:53:50Z
453,521
<p>Changing an inherited method from public to private <em>breaks inheritance</em>. Specifically, it breaks the is-a relationship.</p> <p>Imagine a Restaurant class with a open-doors public method (i.e. it's dinnertime and we want to flip the front door sign from closed to open). Now we want a Catering class that would share many of the implementation details of Restaurant (they both need cooks, kitchens, dishes, food suppliers, and maybe even waitstaff), but not have a dining area, front doors, or the open-doors method. Inheritance from Restaurant is a mistake! It might appear that all you need to do is change the open-doors method to private so no one can use it, but then "any Catering object is-a Restaurant" is false, since part of Restaurant's public interface is open-doors. It's better to refactor Restaurant by adding a new base class and then both Restaurant and Catering derive from it.</p> <p>Languages with a notion of protected or private inheritance support this idea of inheritance for implementation only, but Python is not one of those. (Nor is it useful in those languages, except rarely.) Usually when non-public inheritance is sought, containment (aka "has-a relationship") is the better path, you can even make the attribute protected or private.</p> <p>Python spells protected with a single leading underscore and private with double leading underscores, with the modification of the "consenting adults" philosophy mentioned in <a href="#452023">Triptych's answer</a>. "Dangerous" attributes and methods of your class, e.g. ones that might cause data loss, should be non-public (whether to make them protected or private is influenced by other factors), with public methods used to provide a simpler, safer interface.</p>
5
2009-01-17T16:19:59Z
[ "python", "oop", "inheritance" ]
Making a method private in a python subclass
451,963
<p>Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :</p> <pre><code>class A: def __init__(self): #do something here def method(self): #some code here class B(A): def __init__(self): A.__init__(self) #additional initialization goes here def method(self): #this overrides the method ( and possibly make it private here ) </code></pre> <p>from this point forward , I don't want any class that extends from B to be able to call <code>method</code> . Is this possible ?</p> <p>EDIT : a "logical" reason for this is that I don't want users to call methods in wrong order.</p>
24
2009-01-16T20:53:50Z
458,101
<p>"Everything must be public" proponents think the author is trying to hide a useful API from the users. This guy doesn't want to violate an unquestionable law of Python. He wants to use some methods to define a useful API, and he wants to use other methods to organize the implementation of that API. If there's no separation between the two it doesn't mean the author is not an idiot. It means the author was too lazy to actually define an API.</p> <p>In Python, instead of marking properties or methods as private, they may be prefixed with <code>_</code> as a weak "internal use" indicator, or with <code>__</code> as a slightly stronger one. In a module, names may be prefixed with <code>_</code> in the same way, and you may also put a sequence of strings that constitute the modules' public API in a variable called <code>__all__</code>.</p> <p>A foolish consistency is the hobgoblin of little minds.</p>
7
2009-01-19T16:03:19Z
[ "python", "oop", "inheritance" ]
Making a method private in a python subclass
451,963
<p>Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :</p> <pre><code>class A: def __init__(self): #do something here def method(self): #some code here class B(A): def __init__(self): A.__init__(self) #additional initialization goes here def method(self): #this overrides the method ( and possibly make it private here ) </code></pre> <p>from this point forward , I don't want any class that extends from B to be able to call <code>method</code> . Is this possible ?</p> <p>EDIT : a "logical" reason for this is that I don't want users to call methods in wrong order.</p>
24
2009-01-16T20:53:50Z
5,851,875
<p>Contrary to popular fashion on this subject, there <strong>are</strong> legitimate reasons to have a distinction between public, private, and protected members, whether you work in Python or a more traditional OOP environment. Many times, it comes to be that you develop auxiliary methods for a particularly long-winded task at some level of object specialization. Needless to say, you really don't want these methods inherited by any subclass because they make no sense in the specialized context and shouldn't even be visible; and yet they are visible, and they diminish the utility of things like tab completion, object navigators, and other system software, because everything at all different levels of abstraction get flattened and thrown together. These programming aids are not trivial, mind you. They are only trivial if you're a student and enjoy doing the same thing a million times just because you're learning how.</p> <p>Python historically developed in such a way that to implement the public/private distinction became increasingly difficult due to ideological inertia and compatibility concerns. That's the plain truth. It would be a real headache for everyone to change what they've been doing. Consequently, we now have a million Python fans out there, all of whom have read the same one or two original articles deciding unequivocally that the public/private distinction is "unpythonic". These people, for lack of critical thought or fairness to wide-spread, common practices, instantly use this occasion to accrete a predictable slew of appologetics -- <em>De Defensione Serpentis</em> -- which I suspect arises not from a rational selection of the <em>via pythonis</em> (the pythonic way) but from neglect of other languages, which they either choose not to use, are not skilled at using, or are not able to use because of work.</p> <p>As someone already said, the best you can do in Python to produce an effect similar to private methods is to prepend the method name with <code>__</code> (two underscores). On the other hand, the only thing this accomplishes, practically speaking, is the insertion of a transmogrified attribute name in the object's <code>__dict__</code>. For instance, say you have the following class definition:</p> <pre><code>class Dog(object): def __bark(self): print 'woof' </code></pre> <p>If you run <code>dir(Dog())</code>, you'll see a strange member, called <code>_Dog__bark</code>. Indeed, the only reason this trick exists is to circumvent the problem I described before: namely, preventing inheritance, overloading, and replacement of super methods.</p> <p>Hopefully there will be some standardized implementation of private methods in the future, when people realize that tissue need not have access to the methods by which the individual cell replicates DNA, and the conscious mind need constantly figure out how to repair its tissues and internal organs.</p>
27
2011-05-01T22:26:19Z
[ "python", "oop", "inheritance" ]
Making a method private in a python subclass
451,963
<p>Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :</p> <pre><code>class A: def __init__(self): #do something here def method(self): #some code here class B(A): def __init__(self): A.__init__(self) #additional initialization goes here def method(self): #this overrides the method ( and possibly make it private here ) </code></pre> <p>from this point forward , I don't want any class that extends from B to be able to call <code>method</code> . Is this possible ?</p> <p>EDIT : a "logical" reason for this is that I don't want users to call methods in wrong order.</p>
24
2009-01-16T20:53:50Z
9,198,380
<p>Even among consenting adults, there are reasons why you do not want to expose methods to a derived class. The question is, can I have a hierarchy like Parent > Child, where a user can derive from either Parent or Child but not be exposed any private or protected methods. In the following example, Child explicitly overloads Parent.__private without exposing it.</p> <pre><code>class Parent(object): def __private(self): print 'Parent' def go(self): self.__private() class Child(Parent): def __init__(self): Parent.__init__(self) self._Parent__private = self.__private def __private(self): print 'Child' </code></pre>
1
2012-02-08T17:27:58Z
[ "python", "oop", "inheritance" ]
Making a method private in a python subclass
451,963
<p>Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :</p> <pre><code>class A: def __init__(self): #do something here def method(self): #some code here class B(A): def __init__(self): A.__init__(self) #additional initialization goes here def method(self): #this overrides the method ( and possibly make it private here ) </code></pre> <p>from this point forward , I don't want any class that extends from B to be able to call <code>method</code> . Is this possible ?</p> <p>EDIT : a "logical" reason for this is that I don't want users to call methods in wrong order.</p>
24
2009-01-16T20:53:50Z
19,740,244
<pre><code>class MyClass(object): def _prtectedfunc(self): pass # with one undersocre def __privatefunc(self): pass # with two undersocre </code></pre> <p><a href="http://linuxwell.com/2011/07/21/private-protected-and-public-in-python/" rel="nofollow">http://linuxwell.com/2011/07/21/private-protected-and-public-in-python/</a></p>
0
2013-11-02T08:32:17Z
[ "python", "oop", "inheritance" ]
Python and Bluetooth/OBEX
452,018
<p>Is there any Python libraries that will let me send files with OBEX (OBject EXchange) and that works cross-platform (Windows, OS X, Linux)? I have found Lightblue, which works for Linux and OS X, but not for Windows.</p> <p>If none such lib exists, are there any decent ones that only works in Windows?</p>
2
2009-01-16T21:08:16Z
473,676
<p><a href="http://org.csail.mit.edu/pybluez/" rel="nofollow">PyBluez - Windows</a> </p>
1
2009-01-23T16:59:45Z
[ "python", "bluetooth" ]
Python and Bluetooth/OBEX
452,018
<p>Is there any Python libraries that will let me send files with OBEX (OBject EXchange) and that works cross-platform (Windows, OS X, Linux)? I have found Lightblue, which works for Linux and OS X, but not for Windows.</p> <p>If none such lib exists, are there any decent ones that only works in Windows?</p>
2
2009-01-16T21:08:16Z
499,460
<p>PyOBEX might work, but it has only been tested with a Linux Bluetooth stack:</p> <p><a href="http://pypi.python.org/pypi/PyOBEX/0.10" rel="nofollow">http://pypi.python.org/pypi/PyOBEX/0.10</a></p> <p>It would be good to know if it works correctly on Windows and Mac OS X.</p>
2
2009-01-31T20:12:45Z
[ "python", "bluetooth" ]
Python and Bluetooth/OBEX
452,018
<p>Is there any Python libraries that will let me send files with OBEX (OBject EXchange) and that works cross-platform (Windows, OS X, Linux)? I have found Lightblue, which works for Linux and OS X, but not for Windows.</p> <p>If none such lib exists, are there any decent ones that only works in Windows?</p>
2
2009-01-16T21:08:16Z
1,701,376
<p>pyobex on xp have problem with import MSG_WAITALL from socket</p>
0
2009-11-09T14:37:20Z
[ "python", "bluetooth" ]
Creating a gradient fill in a PDF file using reportlab
452,074
<p>Is it possible to create a gradient fill in a PDF using <a href="http://www.reportlab.org/">ReportLab</a> (python)?</p>
10
2009-01-16T21:24:12Z
2,799,222
<p><strong>[My answer is no longer correct, gradients are now available in Reportlab, see the other answer on this page for details.]</strong></p> <p>Sorry to ressurect this question, but I stumbled across it and it hadn't been correctly answered.</p> <p>The answer is no, as of today, the current version of ReportLab does not support gradients. Gradients are supported by PDF, however. If you look in ReportLab's Canvas class you'll see that many of its methods are relatively small wrappers around the underlying PDF code generation. To access gradients in RL you'd need to extend the Canvas class and add additional methods to generate the correct PDF code. This is doable, but obviously not trivial, and it means you'd have to read up on the PDF spec.</p> <p>There are two alternatives. Firstly generate the gradient as a raster image and use that, secondly generate the gradient by drawing a whole series of rectangles in different colors.</p> <pre><code>start_color = (1,0,0) end_color = (0,1,0) for i in range(100): p = i * 0.01 canvas.setFillColorRGB(*[start_color[i]*(1.0-p)+end_color[i]*p for i in range(3)]) canvas.rect(i, 0, 2, 100) </code></pre> <p>For example. Unfortunately getting the gradient smooth takes a lot of rectangles, and this can cause the PDF to be large and render slowly. You're better off with the raster approach.</p> <p>Finally, you might consider using PyCairo. This has better support for lots of graphical elements, and can render to a PDF or PNG. It lacks reportlabs higher lever constructs (such as page layout), however.</p>
3
2010-05-09T21:21:49Z
[ "python", "pdf", "gradient", "reportlab" ]
Creating a gradient fill in a PDF file using reportlab
452,074
<p>Is it possible to create a gradient fill in a PDF using <a href="http://www.reportlab.org/">ReportLab</a> (python)?</p>
10
2009-01-16T21:24:12Z
15,988,441
<p>ReportLab now supports PDF gradients.</p> <p>A patch for gradient support was <a href="http://two.pairlist.net/pipermail/reportlab-users/2012-August/010465.html">posted to the ReportLab mailing list</a> by Peter Johnson on 6 August 2012 and was <a href="https://bitbucket.org/rptlab/reportlab/commits/494980a689ff55a8457f30b6ca4fbdf80aa2828e">added to the source</a> the next day. I cannot spot anything in <a href="http://www.reportlab.com/software/documentation/relnotes/26/">the release notes for ReportLab 2.6</a> but since that was released on the 1st of October 2012 presumably it is in there. It is definitely present in 2.7.</p> <p>Both linear and radial gradients with multiple stops can be specified. Searching the documentation for the term <em>gradient</em> doesn't turn up anything. However, the <a href="http://two.pairlist.net/pipermail/reportlab-users/2012-August/010459.html">message with the first version of the patch</a> has a couple of examples which are the basis of <a href="https://bitbucket.org/rptlab/reportlab/src/0a60388157ba061f3ef37436b0b60bb545bd5589/tests/test_pdfgen_general.py?at=default#cl-876">some tests in the ReportLab source</a>. Based on this I've worked up a quick demo script:</p> <pre><code>from reportlab.pdfgen.canvas import Canvas from reportlab.lib.colors import red, yellow, green from reportlab.lib.units import mm c = Canvas("gradient.pdf") # Linear gradient with the endpoints extending over the page. c.linearGradient(105*mm, 200*mm, 180*mm, 100*mm, (red, yellow)) c.drawString(5*mm, 290*mm, "c.linearGradient(105*mm, 200*mm, 180*mm, 100*mm, (red, yellow))") c.line(105*mm, 200*mm, 180*mm, 100*mm) c.showPage() # Linear gradient constrained within the endpoints. c.linearGradient(105*mm, 200*mm, 180*mm, 100*mm, (red, yellow), extend=False) c.drawString(5*mm, 290*mm, "c.linearGradient(105*mm, 200*mm, 180*mm, 100*mm, (red, yellow), extend=False)") c.line(105*mm, 200*mm, 180*mm, 100*mm) c.showPage() # Linear gradient with multiple stops. c.linearGradient(105*mm, 200*mm, 180*mm, 100*mm, (red, yellow, green), (0, 0.8, 1), extend=False) c.drawString(5*mm, 290*mm, "c.linearGradient(105*mm, 200*mm, 180*mm, 100*mm, (red, yellow, green), (0, 0.8, 1), extend=False)") c.line(105*mm, 200*mm, 180*mm, 100*mm) c.line(141*mm, 102*mm, 189*mm, 138*mm) c.showPage() # Radial gradient with the endpoint extending over the page. c.radialGradient(105*mm, 200*mm, 60*mm, (red, yellow)) c.drawString(5*mm, 290*mm, "c.radialGradient(105*mm, 200*mm, 60*mm, (red, yellow))") c.circle(105*mm, 200*mm, 60*mm) c.showPage() # Radial gradient constrained within the circle. c.radialGradient(105*mm, 200*mm, 60*mm, (red, yellow), extend=False) c.drawString(5*mm, 290*mm, "c.radialGradient(105*mm, 200*mm, 60*mm, (red, yellow), extend=False)") c.circle(105*mm, 200*mm, 60*mm) c.showPage() # Radial gradient with multiple stops. c.radialGradient(105*mm, 200*mm, 60*mm, (red, yellow, green), (0, 0.8, 1)) c.drawString(5*mm, 290*mm, "c.radialGradient(105*mm, 200*mm, 60*mm, (red, yellow, green), (0, 0.8, 1))") c.circle(105*mm, 200*mm, 48*mm) c.circle(105*mm, 200*mm, 60*mm) c.showPage() c.save() </code></pre> <p>This outputs six pages with various gradients plus the gradient method call and lines/circles showing where the endpoints and stops are:</p> <p><img src="http://i.stack.imgur.com/35oABm.png" alt="Basic linear gradient extending over page"> <img src="http://i.stack.imgur.com/HZTSRm.png" alt="Linear gradient constrained within endpoints"> <img src="http://i.stack.imgur.com/J7xcam.png" alt="Linear gradient with multiple stops"> <img src="http://i.stack.imgur.com/HyoL4m.png" alt="Basic radial gradient extending over page"> <img src="http://i.stack.imgur.com/Nn2zqm.png" alt="Radial gradient constrained within radius"> <img src="http://i.stack.imgur.com/nwIIIm.png" alt="Radial gradient with multiple stops"></p>
5
2013-04-13T13:43:04Z
[ "python", "pdf", "gradient", "reportlab" ]
Creating a gradient fill in a PDF file using reportlab
452,074
<p>Is it possible to create a gradient fill in a PDF using <a href="http://www.reportlab.org/">ReportLab</a> (python)?</p>
10
2009-01-16T21:24:12Z
20,546,843
<p>You want to fill a rectangle (or other path) with a gradient instead of a solid color?</p> <p>No problem. Use clipping to bound/limit the gradient to a path. Just remember to set the clip path <em>before</em> setting the gradient. (And wrap it inside <code>saveState()</code>/<code>restoreState()</code> to reset the clip and gradient afterwards.)</p> <pre><code>c = canvas.Canvas (filename) #c.translate (8*cm, 8*cm) # use this to move the rectangle p = c.beginPath() p.rect (0,0 , 5*cm,5*cm) c.clipPath (p, stroke=0) c.linearGradient (0,0 , 5*cm, 5*cm , (red, yellow)) </code></pre> <p>For radial gradients it might be enough to set the <code>extend</code> keyword parameter to <code>False</code>.</p>
0
2013-12-12T14:58:32Z
[ "python", "pdf", "gradient", "reportlab" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
452,116
<p>Regular Expressions are compiled before being used when using the second version. If you are going to executing it many times it is definatly better to compile it first. If not compiling every time you match for one off's is fine.</p>
0
2009-01-16T21:36:28Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
452,126
<p>My understanding is that those two examples are effectively equivalent. The only difference is that in the first, you can reuse the compiled regular expression elsewhere without causing it to be compiled again.</p> <p>Here's a reference for you: <a href="http://diveintopython3.ep.io/refactoring.html" rel="nofollow">http://diveintopython3.ep.io/refactoring.html</a></p> <blockquote> <p>Calling the compiled pattern object's search function with the string 'M' accomplishes the same thing as calling re.search with both the regular expression and the string 'M'. Only much, much faster. (In fact, the re.search function simply compiles the regular expression and calls the resulting pattern object's search method for you.) </p> </blockquote>
-2
2009-01-16T21:38:12Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
452,142
<p>FWIW:</p> <pre><code>$ python -m timeit -s "import re" "re.match('hello', 'hello world')" 100000 loops, best of 3: 3.82 usec per loop $ python -m timeit -s "import re; h=re.compile('hello')" "h.match('hello world')" 1000000 loops, best of 3: 1.26 usec per loop </code></pre> <p>so, if you're going to be using the <em>same</em> regex a lot, it may be worth it to do <code>re.compile</code> (especially for more complex regexes).</p> <p>The standard arguments against premature optimization apply, but I don't think you really lose much clarity/straightforwardness by using <code>re.compile</code> if you suspect that your regexps may become a performance bottleneck.</p>
34
2009-01-16T21:42:37Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
452,143
<p>I've had a lot of experience running a compiled regex 1000s of times versus compiling on-the-fly, and have not noticed any perceivable difference. Obviously, this is anecdotal, and certainly not a great argument <em>against</em> compiling, but I've found the difference to be negligible.</p> <p>EDIT: After a quick glance at the actual Python 2.5 library code, I see that Python internally compiles AND CACHES regexes whenever you use them anyway (including calls to <code>re.match()</code>), so you're really only changing WHEN the regex gets compiled, and shouldn't be saving much time at all - only the time it takes to check the cache (a key lookup on an internal <code>dict</code> type).</p> <p>From module re.py (comments are mine):</p> <pre><code>def match(pattern, string, flags=0): return _compile(pattern, flags).match(string) def _compile(*key): # Does cache check at top of function cachekey = (type(key[0]),) + key p = _cache.get(cachekey) if p is not None: return p # ... # Does actual compilation on cache miss # ... # Caches compiled regex if len(_cache) &gt;= _MAXCACHE: _cache.clear() _cache[cachekey] = p return p </code></pre> <p>I still often pre-compile regular expressions, but only to bind them to a nice, reusable name, not for any expected performance gain.</p>
258
2009-01-16T21:42:57Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
452,153
<p>This is a good question. You often see people use re.compile without reason. It lessens readability. But sure there are lots of times when pre-compiling the expression is called for. Like when you use it repeated times in a loop or some such.</p> <p>It's like everything about programming (everything in life actually). Apply common sense.</p>
1
2009-01-16T21:44:59Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
453,568
<p>For me, the biggest benefit to <code>re.compile</code> isn't any kind of premature optimization (which is the <a href="http://programmers.stackexchange.com/questions/39/whats-your-favourite-quote-about-programming/816#816">root of all evil</a>, <a href="http://en.wikipedia.org/wiki/Optimization_%28computer_science%29#When_to_optimize" rel="nofollow" title="read the full two paragraphs, which is available in the original paper and much more useful than the popular quip">anyway</a>). It's being able to separate definition of the regex from its use.</p> <p>Even a simple expression such as <code>0|[1-9][0-9]*</code> (integer in base 10 without leading zeros) can be complex enough that you'd rather not have to retype it, check if you made any typos, and later have to recheck if there are typos when you start debugging. Plus, it's nicer to use a variable name such as num or num_b10 than <code>0|[1-9][0-9]*</code>.</p> <p>It's certainly possible to store strings and pass them to re.match; however, that's <em>less</em> readable:</p> <pre><code>num = "..." # then, much later: m = re.match(num, input) </code></pre> <p>Versus compiling:</p> <pre><code>num = re.compile("...") # then, much later: m = num.match(input) </code></pre> <p>Though it is fairly close, the last line of the second feels more natural and simpler when used repeatedly.</p>
71
2009-01-17T16:49:07Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
462,399
<p>Interestingly, compiling does prove more efficient for me (Python 2.5.2 on Win XP):</p> <pre><code>import re import time rgx = re.compile('(\w+)\s+[0-9_]?\s+\w*') str = "average 2 never" a = 0 t = time.time() for i in xrange(1000000): if re.match('(\w+)\s+[0-9_]?\s+\w*', str): #~ if rgx.match(str): a += 1 print time.time() - t </code></pre> <p>Running the above code once as is, and once with the two <code>if</code> lines commented the other way around, the compiled regex is twice as fast</p>
2
2009-01-20T18:06:57Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
660,315
<p>In general, I find it is easier to use flags (at least easier to remember how), like <code>re.I</code> when compiling patterns than to use flags inline.</p> <pre><code>&gt;&gt;&gt; foo_pat = re.compile('foo',re.I) &gt;&gt;&gt; foo_pat.findall('some string FoO bar') ['FoO'] </code></pre> <p>vs </p> <pre><code>&gt;&gt;&gt; re.findall('(?i)foo','some string FoO bar') ['FoO'] </code></pre>
4
2009-03-18T22:13:45Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
1,086,330
<p>(months later) it's easy to add your own cache around re.match, or anything else for that matter --</p> <pre><code>""" Re.py: Re.match = re.match + cache efficiency: re.py does this already (but what's _MAXCACHE ?) readability, inline / separate: matter of taste """ import re cache = {} _re_type = type( re.compile( "" )) def match( pattern, str, *opt ): """ Re.match = re.match + cache re.compile( pattern ) """ if type(pattern) == _re_type: cpat = pattern elif pattern in cache: cpat = cache[pattern] else: cpat = cache[pattern] = re.compile( pattern, *opt ) return cpat.match( str ) # def search ... </code></pre> <p>A wibni, wouldn't it be nice if: cachehint( size= ), cacheinfo() -> size, hits, nclear ...</p>
0
2009-07-06T10:13:44Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
2,082,709
<p>I ran this test before stumbling upon the discussion here. However, having run it I thought I'd at least post my results.</p> <p>I stole and bastardized the example in Jeff Friedl's "Mastering Regular Expressions". This is on a macbook running OSX 10.6 (2Ghz intel core 2 duo, 4GB ram). Python version is 2.6.1.</p> <p><strong>Run 1 - using re.compile</strong></p> <pre><code>import re import time import fpformat Regex1 = re.compile('^(a|b|c|d|e|f|g)+$') Regex2 = re.compile('^[a-g]+$') TimesToDo = 1000 TestString = "" for i in range(1000): TestString += "abababdedfg" StartTime = time.time() for i in range(TimesToDo): Regex1.search(TestString) Seconds = time.time() - StartTime print "Alternation takes " + fpformat.fix(Seconds,3) + " seconds" StartTime = time.time() for i in range(TimesToDo): Regex2.search(TestString) Seconds = time.time() - StartTime print "Character Class takes " + fpformat.fix(Seconds,3) + " seconds" Alternation takes 2.299 seconds Character Class takes 0.107 seconds </code></pre> <p><strong>Run 2 - Not using re.compile</strong></p> <pre><code>import re import time import fpformat TimesToDo = 1000 TestString = "" for i in range(1000): TestString += "abababdedfg" StartTime = time.time() for i in range(TimesToDo): re.search('^(a|b|c|d|e|f|g)+$',TestString) Seconds = time.time() - StartTime print "Alternation takes " + fpformat.fix(Seconds,3) + " seconds" StartTime = time.time() for i in range(TimesToDo): re.search('^[a-g]+$',TestString) Seconds = time.time() - StartTime print "Character Class takes " + fpformat.fix(Seconds,3) + " seconds" Alternation takes 2.508 seconds Character Class takes 0.109 seconds </code></pre>
2
2010-01-17T21:22:18Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
2,634,933
<p>I just tried this myself. For the simple case of parsing a number out of a string and summing it, using a compiled regular expression object is about twice as fast as using the <code>re</code> methods.</p> <p>As others have pointed out, the <code>re</code> methods (including <code>re.compile</code>) look up the regular expression string in a cache of previously compiled expressions. Therefore, in the normal case, the extra cost of using the <code>re</code> methods is simply the cost of the cache lookup.</p> <p>However, examination of the <a href="http://www.google.com/codesearch/p?hl=en#1IKf2ZWr9OM/tools/third_party/python_26/Lib/re.py&amp;q=lang%3apython%20re.py&amp;sa=N&amp;cd=4&amp;ct=rc">code</a>, shows the cache is limited to 100 expressions. This begs the question, how painful is it to overflow the cache? The code contains an internal interface to the regular expression compiler, <code>re.sre_compile.compile</code>. If we call it, we bypass the cache. It turns out to be about two orders of magnitude slower for a basic regular expression, such as <code>r'\w+\s+([0-9_]+)\s+\w*'</code>.</p> <p>Here's my test:</p> <pre> #!/usr/bin/env python import re import time def timed(func): def wrapper(*args): t = time.time() result = func(*args) t = time.time() - t print '%s took %.3f seconds.' % (func.func_name, t) return result return wrapper regularExpression = r'\w+\s+([0-9_]+)\s+\w*' testString = "average 2 never" @timed def noncompiled(): a = 0 for x in xrange(1000000): m = re.match(regularExpression, testString) a += int(m.group(1)) return a @timed def compiled(): a = 0 rgx = re.compile(regularExpression) for x in xrange(1000000): m = rgx.match(testString) a += int(m.group(1)) return a @timed def reallyCompiled(): a = 0 rgx = re.sre_compile.compile(regularExpression) for x in xrange(1000000): m = rgx.match(testString) a += int(m.group(1)) return a @timed def compiledInLoop(): a = 0 for x in xrange(1000000): rgx = re.compile(regularExpression) m = rgx.match(testString) a += int(m.group(1)) return a @timed def reallyCompiledInLoop(): a = 0 for x in xrange(10000): rgx = re.sre_compile.compile(regularExpression) m = rgx.match(testString) a += int(m.group(1)) return a r1 = noncompiled() r2 = compiled() r3 = reallyCompiled() r4 = compiledInLoop() r5 = reallyCompiledInLoop() print "r1 = ", r1 print "r2 = ", r2 print "r3 = ", r3 print "r4 = ", r4 print "r5 = ", r5 </pre> <p>And here is the output on my machine:</p> <pre> $ regexTest.py noncompiled took 4.555 seconds. compiled took 2.323 seconds. reallyCompiled took 2.325 seconds. compiledInLoop took 4.620 seconds. reallyCompiledInLoop took 4.074 seconds. r1 = 2000000 r2 = 2000000 r3 = 2000000 r4 = 2000000 r5 = 20000 </pre> <p>The 'reallyCompiled' methods use the internal interface, which bypasses the cache. Note the one that compiles on each loop iteration is only iterated 10,000 times, not one million.</p>
6
2010-04-14T04:40:24Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
4,114,923
<p>i'd like to motivate that pre-compiling is both conceptually and 'literately' (as in 'literate programming') advantageous. have a look at this code snippet:</p> <pre><code>from re import compile as _Re class TYPO: def text_has_foobar( self, text ): return self._text_has_foobar_re_search( text ) is not None _text_has_foobar_re_search = _Re( r"""(?i)foobar""" ).search TYPO = TYPO() </code></pre> <p>in your application, you'd write:</p> <pre><code>from TYPO import TYPO print( TYPO.text_has_foobar( 'FOObar ) ) </code></pre> <p>this is about as simple in terms of functionality as it can get. because this is example is so short, i conflated the way to get <code>_text_has_foobar_re_search</code> all in one line. the disadvantage of this code is that it occupies a little memory for whatever the lifetime of the <code>TYPO</code> library object is; the advantage is that when doing a foobar search, you'll get away with two function calls and two class dictionary lookups. how many regexes are cached by <code>re</code> and the overhead of that cache are irrelevant here. </p> <p>compare this with the more usual style, below:</p> <pre><code>import re class Typo: def text_has_foobar( self, text ): return re.compile( r"""(?i)foobar""" ).search( text ) is not None </code></pre> <p>In the application:</p> <pre><code>typo = Typo() print( typo.text_has_foobar( 'FOObar ) ) </code></pre> <p>I readily admit that my style is highly unusual for python, maybe even debatable. however, in the example that more closely matches how python is mostly used, in order to do a single match, we must instantiate an object, do three instance dictionary lookups, and perform three function calls; additionally, we might get into <code>re</code> caching troubles when using more than 100 regexes. also, the regular expression gets hidden inside the method body, which most of the time is not such a good idea. </p> <p>be it said that every subset of measures---targeted, aliased import statements; aliased methods where applicable; reduction of function calls and object dictionary lookups---can help reduce computational and conceptual complexity. </p>
0
2010-11-06T20:03:49Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
13,640,709
<p>Here's a simple test case:</p> <pre><code>~$ for x in 1 10 100 1000 10000 100000 1000000; do python -m timeit -n $x -s 'import re' 're.match("[0-9]{3}-[0-9]{3}-[0-9]{4}", "123-123-1234")'; done 1 loops, best of 3: 3.1 usec per loop 10 loops, best of 3: 2.41 usec per loop 100 loops, best of 3: 2.24 usec per loop 1000 loops, best of 3: 2.21 usec per loop 10000 loops, best of 3: 2.23 usec per loop 100000 loops, best of 3: 2.24 usec per loop 1000000 loops, best of 3: 2.31 usec per loop </code></pre> <p>with re.compile: </p> <pre><code>~$ for x in 1 10 100 1000 10000 100000 1000000; do python -m timeit -n $x -s 'import re' 'r = re.compile("[0-9]{3}-[0-9]{3}-[0-9]{4}")' 'r.match("123-123-1234")'; done 1 loops, best of 3: 1.91 usec per loop 10 loops, best of 3: 0.691 usec per loop 100 loops, best of 3: 0.701 usec per loop 1000 loops, best of 3: 0.684 usec per loop 10000 loops, best of 3: 0.682 usec per loop 100000 loops, best of 3: 0.694 usec per loop 1000000 loops, best of 3: 0.702 usec per loop </code></pre> <p>So, it would seem to compiling is faster with this simple case, <em>even if you only match once</em>.</p>
27
2012-11-30T07:24:30Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
15,328,835
<p>Using the given examples:</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>The <em>match</em> method in the example above is not the same as the one used below:</p> <pre><code>re.match('hello', 'hello world') </code></pre> <p><a href="http://docs.python.org/3.3/library/re.html?highlight=re.sub#re.compile" rel="nofollow">re.compile()</a> returns a <a href="http://docs.python.org/3.3/library/re.html?highlight=re.sub#regular-expression-objects" rel="nofollow">regular expression object</a>, which means <code>h</code> is a regex object.</p> <p>The regex object has its own <a href="http://docs.python.org/3.3/library/re.html?highlight=re.sub#re.regex.match" rel="nofollow"><em>match</em></a> method with the optional <em>pos</em> and <em>endpos</em> parameters:</p> <p><a href="http://docs.python.org/3.3/library/re.html?highlight=re.sub#re.regex.match" rel="nofollow"><code>regex.match(string[, pos[, endpos]])</code></a> </p> <p><strong>pos</strong></p> <blockquote> <p>The optional second parameter <em>pos</em> gives an index in the string where the search is to start; it defaults to 0. This is not completely equivalent to slicing the string; the <code>'^'</code> pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start.</p> </blockquote> <p><strong>endpos</strong></p> <blockquote> <p>The optional parameter <em>endpos</em> limits how far the string will be searched; it will be as if the string is <em>endpos</em> characters long, so only the characters from <em>pos</em> to <code>endpos - 1</code> will be searched for a match. If <em>endpos</em> is less than <em>pos</em>, no match will be found; otherwise, if <em>rx</em> is a compiled regular expression object, <code>rx.search(string, 0, 50)</code> is equivalent to <code>rx.search(string[:50], 0)</code>.</p> </blockquote> <p>The regex object's <em>search</em>, <em>findall</em>, and <em>finditer</em> methods also support these parameters.</p> <p><a href="http://docs.python.org/3.3/library/re.html?highlight=re.sub#re.match" rel="nofollow"><code>re.match(pattern, string, flags=0)</code></a> does not support them as you can see,<br> nor does its <em>search</em>, <em>findall</em>, and <em>finditer</em> counterparts.</p> <p>A <a href="http://docs.python.org/3.3/library/re.html?highlight=re.sub#match-objects" rel="nofollow">match object</a> has attributes that complement these parameters:</p> <p><strong>match.pos</strong></p> <blockquote> <p>The value of pos which was passed to the search() or match() method of a regex object. This is the index into the string at which the RE engine started looking for a match.</p> </blockquote> <p><strong>match.endpos</strong></p> <blockquote> <p>The value of endpos which was passed to the search() or match() method of a regex object. This is the index into the string beyond which the RE engine will not go.</p> </blockquote> <hr> <p>A <a href="http://docs.python.org/3.3/library/re.html?highlight=re.sub#regular-expression-objects" rel="nofollow">regex object</a> has two unique, possibly useful, attributes:</p> <p><strong>regex.groups</strong></p> <blockquote> <p>The number of capturing groups in the pattern.</p> </blockquote> <p><strong>regex.groupindex</strong></p> <blockquote> <p>A dictionary mapping any symbolic group names defined by (?P) to group numbers. The dictionary is empty if no symbolic groups were used in the pattern.</p> </blockquote> <hr> <p>And finally, a <a href="http://docs.python.org/3.3/library/re.html?highlight=re.sub#match-objects" rel="nofollow">match object</a> has this attribute:</p> <p><strong>match.re</strong></p> <blockquote> <p>The regular expression object whose match() or search() method produced this match instance.</p> </blockquote>
2
2013-03-10T23:03:59Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
17,598,179
<p>Performance difference aside, using re.compile and using the compiled regular expression object to do match (whatever regular expression related operations) makes the semantics clearer to Python run-time.</p> <p>I had some painful experience of debugging some simple code:</p> <pre><code>compare = lambda s, p: re.match(p, s) </code></pre> <p>and later I'd use compare in </p> <pre><code>[x for x in data if compare(patternPhrases, x[columnIndex])] </code></pre> <p>where <code>patternPhrases</code> is supposed to be a variable containing regular expression string, <code>x[columnIndex]</code> is a variable containing string.</p> <p>I had trouble that <code>patternPhrases</code> did not match some expected string!</p> <p>But if I used the re.compile form:</p> <pre><code>compare = lambda s, p: p.match(s) </code></pre> <p>then in </p> <pre><code>[x for x in data if compare(patternPhrases, x[columnIndex])] </code></pre> <p>Python would have complained that "string does not have attribute of match", as by positional argument mapping in <code>compare</code>, <code>x[columnIndex]</code> is used as regular expression!, when I actually meant</p> <pre><code>compare = lambda p, s: p.match(s) </code></pre> <p>In my case, using re.compile is more explicit of the purpose of regular expression, when it's value is hidden to naked eyes, thus I could get more help from Python run-time checking. </p> <p>So the moral of my lesson is that when the regular expression is not just literal string, then I should use re.compile to let Python to help me to assert my assumption.</p>
1
2013-07-11T16:00:03Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
25,020,854
<p>I agree with Honest Abe that the <code>match(...)</code> in the given examples are different. They are not a one-to-one comparisons and thus, outcomes are vary. To simplify my reply, I use A, B, C, D for those functions in question. Oh yes, we are dealing with 4 functions in <code>re.py</code> instead of 3.</p> <p>Running this piece of code:</p> <pre><code>h = re.compile('hello') # (A) h.match('hello world') # (B) </code></pre> <p>is same as running this code:</p> <pre><code>re.match('hello', 'hello world') # (C) </code></pre> <p>Because, when looked into the source <code>re.py</code>, (A + B) means:</p> <pre><code>h = re._compile('hello') # (D) h.match('hello world') </code></pre> <p>and (C) is actually:</p> <pre><code>re._compile('hello').match('hello world') </code></pre> <p>So, (C) is not the same as (B). In fact, (C) calls (B) after calling (D) which is also called by (A). In other words, <code>(C) = (A) + (B)</code>. Therefore, comparing (A + B) inside a loop has same result as (C) inside a loop. </p> <p>George's <code>regexTest.py</code> proved this for us.</p> <pre><code>noncompiled took 4.555 seconds. # (C) in a loop compiledInLoop took 4.620 seconds. # (A + B) in a loop compiled took 2.323 seconds. # (A) once + (B) in a loop </code></pre> <p>Everyone's interest is, how to get the result of 2.323 seconds. In order to make sure <code>compile(...)</code> only get called once, we need to store the compiled regex object in memory. If we are using a class, we could store the object and reuse when every time our function get called.</p> <pre><code>class Foo: regex = re.compile('hello') def my_function(text) return regex.match(text) </code></pre> <p>If we are not using class (which is my request today), then I have no comment. I'm still learning to use global variable in Python, and I know global variable is a bad thing.</p> <p>One more point, I believe that using <code>(A) + (B)</code> approach has an upper hand. Here are some facts as I observed (please correct me if I'm wrong):</p> <ol> <li><p>Calls A once, it will do one search in the <code>_cache</code> followed by one <code>sre_compile.compile()</code> to create a regex object. Calls A twice, it will do two searches and one compile (because the regex object is cached).</p></li> <li><p>If the <code>_cache</code> get flushed in between, then the regex object is released from memory and Python need to compile again. (someone suggest that Python won't recompile.)</p></li> <li><p>If we keep the regex object by using (A), the regex object will still get into _cache and get flushed somehow. But our code keep a reference on it and the regex object will not be released from memory. Those, Python need not to compile again.</p></li> <li><p>The 2 seconds differences in George's test compiledInLoop vs compiled is mainly the time required to build the key and search the _cache. It doesn't mean the compile time of regex.</p></li> <li><p>George's reallycompile test show what happen if it really re-do the compile every time: it will be 100x slower (he reduced the loop from 1,000,000 to 10,000).</p></li> </ol> <p>Here are the only cases that (A + B) is better than (C):</p> <ol> <li>If we can cache a reference of the regex object inside a class.</li> <li>If we need to calls (B) repeatedly (inside a loop or multiple times), we must cache the reference to regex object outside the loop.</li> </ol> <p>Case that (C) is good enough:</p> <ol> <li>We cannot cache a reference.</li> <li>We only use it once in a while.</li> <li>In overall, we don't have too many regex (assume the compiled one never get flushed)</li> </ol> <p>Just a recap, here are the A B C:</p> <pre><code>h = re.compile('hello') # (A) h.match('hello world') # (B) re.match('hello', 'hello world') # (C) </code></pre> <p>Thanks for reading.</p>
5
2014-07-29T16:55:09Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
29,159,014
<p>There is one addition perk of using re.compile(), in the form of adding comments to my regex patterns using re.VERBOSE</p> <pre><code>pattern = ''' hello[ ]world # Some info on my pattern logic. [ ] to recognize space ''' re.search(pattern, 'hello world', re.VERBOSE) </code></pre> <p>Although this does not affect the speed of running your code, I like to do it this way as it is part of my commenting habit. I throughly dislike spending time trying to remember the logic that went behind my code 2 months down the line when I want to make modifications.</p>
2
2015-03-20T03:39:09Z
[ "python", "regex" ]
Is it worth using Python's re.compile?
452,104
<p>Is there any benefit in using compile for regular expressions in Python?</p> <pre><code>h = re.compile('hello') h.match('hello world') </code></pre> <p>vs</p> <pre><code>re.match('hello', 'hello world') </code></pre>
238
2009-01-16T21:31:57Z
39,446,619
<p>This answer might be arriving late but is an interesting find. Using compile can really save you time if you are planning on using the regex multiple times (this is also mentioned in the docs). Below you can see that using a compiled regex is the fastest when the match method is directly called on it. passing a compiled regex to re.match makes it even slower and passing re.match with the patter string is somewhere in the middle. </p> <pre><code>&gt;&gt;&gt; ipr = r'\D+((([0-2][0-5]?[0-5]?)\.){3}([0-2][0-5]?[0-5]?))\D+' &gt;&gt;&gt; average(*timeit.repeat("re.match(ipr, 'abcd100.10.255.255 ')", globals={'ipr': ipr, 're': re})) 1.5077415757028423 &gt;&gt;&gt; ipr = re.compile(ipr) &gt;&gt;&gt; average(*timeit.repeat("re.match(ipr, 'abcd100.10.255.255 ')", globals={'ipr': ipr, 're': re})) 1.8324008992184038 &gt;&gt;&gt; average(*timeit.repeat("ipr.match('abcd100.10.255.255 ')", globals={'ipr': ipr, 're': re})) 0.9187896518778871 </code></pre>
0
2016-09-12T08:57:31Z
[ "python", "regex" ]
How can I install the Beautiful Soup module on the Mac?
452,283
<p>I read this without finding the solution: <a href="http://docs.python.org/install/index.html">http://docs.python.org/install/index.html</a></p>
38
2009-01-16T22:26:45Z
452,302
<p>The "normal" way is to:</p> <ul> <li>Go to the Beautiful Soup web site, <a href="http://www.crummy.com/software/BeautifulSoup/">http://www.crummy.com/software/BeautifulSoup/</a></li> <li>Download the package</li> <li>Unpack it</li> <li>In a Terminal window, <code>cd</code> to the resulting directory</li> <li>Type <code>python setup.py install</code></li> </ul> <p>Another solution is to use <code>easy_install</code>. Go to <a href="http://peak.telecommunity.com/DevCenter/EasyInstall">http://peak.telecommunity.com/DevCenter/EasyInstall</a>), install the package using the instructions on that page, and then type, in a Terminal window:</p> <pre><code>easy_install BeautifulSoup4 # for older v3: # easy_install BeautifulSoup </code></pre> <p><code>easy_install</code> will take care of downloading, unpacking, building, and installing the package. The advantage to using <code>easy_install</code> is that it knows how to search for many different Python packages, because it queries the <a href="http://pypi.python.org/">PyPI</a> registry. Thus, once you have <code>easy_install</code> on your machine, you install many, many different third-party packages simply by one command at a shell.</p>
69
2009-01-16T22:37:30Z
[ "python", "osx", "module", "installation" ]
How can I install the Beautiful Soup module on the Mac?
452,283
<p>I read this without finding the solution: <a href="http://docs.python.org/install/index.html">http://docs.python.org/install/index.html</a></p>
38
2009-01-16T22:26:45Z
452,311
<p>Brian beat me too it, but since I already have the transcript:</p> <p><a href="http://peak.telecommunity.com/DevCenter/EasyInstall">easy_install</a></p> <pre><code>aaron@ares ~$ sudo easy_install BeautifulSoup Searching for BeautifulSoup Best match: BeautifulSoup 3.0.7a Processing BeautifulSoup-3.0.7a-py2.5.egg BeautifulSoup 3.0.7a is already the active version in easy-install.pth Using /Library/Python/2.5/site-packages/BeautifulSoup-3.0.7a-py2.5.egg Processing dependencies for BeautifulSoup Finished processing dependencies for BeautifulSoup </code></pre> <p>.. or the normal boring way:</p> <pre><code>aaron@ares ~/Downloads$ curl http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup.tar.gz &gt; bs.tar.gz % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 71460 100 71460 0 0 84034 0 --:--:-- --:--:-- --:--:-- 111k aaron@ares ~/Downloads$ tar -xzvf bs.tar.gz BeautifulSoup-3.1.0.1/ BeautifulSoup-3.1.0.1/BeautifulSoup.py BeautifulSoup-3.1.0.1/BeautifulSoup.py.3.diff BeautifulSoup-3.1.0.1/BeautifulSoupTests.py BeautifulSoup-3.1.0.1/BeautifulSoupTests.py.3.diff BeautifulSoup-3.1.0.1/CHANGELOG BeautifulSoup-3.1.0.1/README BeautifulSoup-3.1.0.1/setup.py BeautifulSoup-3.1.0.1/testall.sh BeautifulSoup-3.1.0.1/to3.sh BeautifulSoup-3.1.0.1/PKG-INFO BeautifulSoup-3.1.0.1/BeautifulSoup.pyc BeautifulSoup-3.1.0.1/BeautifulSoupTests.pyc aaron@ares ~/Downloads$ cd BeautifulSoup-3.1.0.1/ aaron@ares ~/Downloads/BeautifulSoup-3.1.0.1$ sudo python setup.py install running install &lt;... snip ...&gt; </code></pre>
14
2009-01-16T22:41:46Z
[ "python", "osx", "module", "installation" ]
How can I install the Beautiful Soup module on the Mac?
452,283
<p>I read this without finding the solution: <a href="http://docs.python.org/install/index.html">http://docs.python.org/install/index.html</a></p>
38
2009-01-16T22:26:45Z
6,045,148
<p>Download the package and unpack it. In Terminal, go to the package's directory and type</p> <pre><code>python setup.py install </code></pre>
2
2011-05-18T13:05:00Z
[ "python", "osx", "module", "installation" ]
How can I install the Beautiful Soup module on the Mac?
452,283
<p>I read this without finding the solution: <a href="http://docs.python.org/install/index.html">http://docs.python.org/install/index.html</a></p>
38
2009-01-16T22:26:45Z
15,520,403
<pre><code>sudo yum remove python-beautifulsoup </code></pre> <p>OR</p> <pre><code>sudo easy_install -m BeautifulSoup </code></pre> <p>can remove old version 3</p>
0
2013-03-20T10:02:07Z
[ "python", "osx", "module", "installation" ]
How can I install the Beautiful Soup module on the Mac?
452,283
<p>I read this without finding the solution: <a href="http://docs.python.org/install/index.html">http://docs.python.org/install/index.html</a></p>
38
2009-01-16T22:26:45Z
19,257,356
<p>On advice from <a href="http://for-ref-only.blogspot.de/2012/08/installing-beautifulsoup-for-python-3.html" rel="nofollow">http://for-ref-only.blogspot.de/2012/08/installing-beautifulsoup-for-python-3.html</a>, I used the Windows command prompt with:</p> <pre><code>C:\Python\Scripts\easy_install c:\Python\BeautifulSoup\beautifulsoup4-4.3.1 </code></pre> <p>where BeautifulSoup\beautifulsoup4-4.3.1 is the downloaded and extracted beautifulsoup4-4.3.1.tar file. It works. </p>
0
2013-10-08T20:09:28Z
[ "python", "osx", "module", "installation" ]
How can I install the Beautiful Soup module on the Mac?
452,283
<p>I read this without finding the solution: <a href="http://docs.python.org/install/index.html">http://docs.python.org/install/index.html</a></p>
38
2009-01-16T22:26:45Z
24,178,431
<p>I think the current right way to do this is by <code>pip</code> like Pramod comments</p> <pre><code>pip install beautifulsoup4 </code></pre> <p>because of last changes in Python, see discussion <a href="http://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install">here</a>. This was not so in the past. </p>
12
2014-06-12T07:08:25Z
[ "python", "osx", "module", "installation" ]
Python object.__repr__(self) should be an expression?
452,300
<p>I was looking at the builtin object methods in the <a href="http://docs.python.org/reference/datamodel.html#objects-values-and-types">Python documentation</a>, and I was interested in the documentation for <code>object.__repr__(self)</code>. Here's what it says:</p> <blockquote> <p>Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form &lt;...some useful description...> should be returned. The return value must be a string object. If a class defines <strong>repr</strong>() but not <strong>str</strong>(), then <strong>repr</strong>() is also used when an “informal” string representation of instances of that class is required.</p> <p>This is typically used for debugging, so it is important that the representation is information-rich and unambiguous</p> </blockquote> <p>The most interesting part to me, was...</p> <blockquote> <p>If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value</p> </blockquote> <p>... but I'm not sure exactly what this means. It says it should <em>look</em> like an expression which can be used to recreate the object, but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?</p> <p>In general I'm a bit confused as to exactly what I should be putting here.</p>
51
2009-01-16T22:37:18Z
452,310
<pre><code>&gt;&gt;&gt; from datetime import date &gt;&gt;&gt; &gt;&gt;&gt; repr(date.today()) # calls date.today().__repr__() 'datetime.date(2009, 1, 16)' &gt;&gt;&gt; eval(_) # _ is the output of the last command datetime.date(2009, 1, 16) </code></pre> <p>The output is a string that can be parsed by the python interpreter and results in an equal object.</p> <p>If that's not possible, it should return a string in the form of <code>&lt;...some useful description...&gt;</code>.</p>
54
2009-01-16T22:41:37Z
[ "python" ]
Python object.__repr__(self) should be an expression?
452,300
<p>I was looking at the builtin object methods in the <a href="http://docs.python.org/reference/datamodel.html#objects-values-and-types">Python documentation</a>, and I was interested in the documentation for <code>object.__repr__(self)</code>. Here's what it says:</p> <blockquote> <p>Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form &lt;...some useful description...> should be returned. The return value must be a string object. If a class defines <strong>repr</strong>() but not <strong>str</strong>(), then <strong>repr</strong>() is also used when an “informal” string representation of instances of that class is required.</p> <p>This is typically used for debugging, so it is important that the representation is information-rich and unambiguous</p> </blockquote> <p>The most interesting part to me, was...</p> <blockquote> <p>If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value</p> </blockquote> <p>... but I'm not sure exactly what this means. It says it should <em>look</em> like an expression which can be used to recreate the object, but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?</p> <p>In general I'm a bit confused as to exactly what I should be putting here.</p>
51
2009-01-16T22:37:18Z
452,312
<p>It should be a Python expression that, when eval'd, creates an object with the exact same properties as this one. For example, if you have a <code>Fraction</code> class that contains two integers, a numerator and denominator, your <code>__repr__()</code> method would look like this:</p> <pre><code># in the definition of Fraction class def __repr__(self): return "Fraction(%d, %d)" % (self.numerator, self.denominator) </code></pre> <p>Assuming that the constructor takes those two values.</p>
24
2009-01-16T22:42:22Z
[ "python" ]
Python object.__repr__(self) should be an expression?
452,300
<p>I was looking at the builtin object methods in the <a href="http://docs.python.org/reference/datamodel.html#objects-values-and-types">Python documentation</a>, and I was interested in the documentation for <code>object.__repr__(self)</code>. Here's what it says:</p> <blockquote> <p>Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form &lt;...some useful description...> should be returned. The return value must be a string object. If a class defines <strong>repr</strong>() but not <strong>str</strong>(), then <strong>repr</strong>() is also used when an “informal” string representation of instances of that class is required.</p> <p>This is typically used for debugging, so it is important that the representation is information-rich and unambiguous</p> </blockquote> <p>The most interesting part to me, was...</p> <blockquote> <p>If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value</p> </blockquote> <p>... but I'm not sure exactly what this means. It says it should <em>look</em> like an expression which can be used to recreate the object, but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?</p> <p>In general I'm a bit confused as to exactly what I should be putting here.</p>
51
2009-01-16T22:37:18Z
452,733
<p>"but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?"</p> <p>Wow, that's a lot of hand-wringing.</p> <ol> <li><p>An "an example of the sort of expression you could use" would not be a representation of a specific object. That can't be useful or meaningful. </p></li> <li><p>What is the difference between "an actual expression, that can ... recreate the object" and "a rehasing of the actual expression which was used [to create the object]"? Both are an expression that creates the object. There's no practical distinction between these. A repr call could produce either a new expression or the original expression. In many cases, they're the same.</p></li> </ol> <p>Note that this isn't always possible, practical or desirable.</p> <p>In some cases, you'll notice that repr() presents a string which is clearly <em>not</em> an expression of any kind. The default repr() for any class you define isn't useful as an expression.</p> <p>In some cases, you might have mutual (or circular) references between objects. The repr() of that tangled hierarchy can't make sense.</p> <p>In many cases, an object is built incrementally via a parser. For example, from XML or JSON or something. What would the repr be? The original XML or JSON? Clearly not, since they're not Python. It could be some Python expression that generated the XML. However, for a gigantic XML document, it might not be possible to write a single Python expression that was the functional equivalent of parsing XML.</p>
3
2009-01-17T03:16:28Z
[ "python" ]
Python object.__repr__(self) should be an expression?
452,300
<p>I was looking at the builtin object methods in the <a href="http://docs.python.org/reference/datamodel.html#objects-values-and-types">Python documentation</a>, and I was interested in the documentation for <code>object.__repr__(self)</code>. Here's what it says:</p> <blockquote> <p>Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form &lt;...some useful description...> should be returned. The return value must be a string object. If a class defines <strong>repr</strong>() but not <strong>str</strong>(), then <strong>repr</strong>() is also used when an “informal” string representation of instances of that class is required.</p> <p>This is typically used for debugging, so it is important that the representation is information-rich and unambiguous</p> </blockquote> <p>The most interesting part to me, was...</p> <blockquote> <p>If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value</p> </blockquote> <p>... but I'm not sure exactly what this means. It says it should <em>look</em> like an expression which can be used to recreate the object, but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?</p> <p>In general I'm a bit confused as to exactly what I should be putting here.</p>
51
2009-01-16T22:37:18Z
453,381
<p><strong>Guideline:</strong> If you can succinctly provide an <em>exact representation</em>, <strong>format it as a Python expression</strong> (which implies that it can be both eval'd and copied directly into source code, in the right context). If providing an <em>inexact representation</em>, <strong>use <code>&lt;...&gt;</code> format</strong>.</p> <p>There are many possible representations for any value, but the one that's most interesting for Python programmers is an expression that recreates the value. Remember that <strong>those who understand Python are the target audience</strong>&mdash;and that's also why inexact representations should include relevant context. Even the default <code>&lt;XXX object at 0xNNN&gt;</code>, while almost entirely useless, still provides type, <code>id()</code> (to distinguish different objects), and indication that no better representation is available.</p>
9
2009-01-17T14:42:03Z
[ "python" ]
Python object.__repr__(self) should be an expression?
452,300
<p>I was looking at the builtin object methods in the <a href="http://docs.python.org/reference/datamodel.html#objects-values-and-types">Python documentation</a>, and I was interested in the documentation for <code>object.__repr__(self)</code>. Here's what it says:</p> <blockquote> <p>Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form &lt;...some useful description...> should be returned. The return value must be a string object. If a class defines <strong>repr</strong>() but not <strong>str</strong>(), then <strong>repr</strong>() is also used when an “informal” string representation of instances of that class is required.</p> <p>This is typically used for debugging, so it is important that the representation is information-rich and unambiguous</p> </blockquote> <p>The most interesting part to me, was...</p> <blockquote> <p>If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value</p> </blockquote> <p>... but I'm not sure exactly what this means. It says it should <em>look</em> like an expression which can be used to recreate the object, but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?</p> <p>In general I'm a bit confused as to exactly what I should be putting here.</p>
51
2009-01-16T22:37:18Z
28,759,968
<p>Peace :),</p> <p>This might be useful: <a href="http://www.rafekettler.com/magicmethods.html" rel="nofollow">http://www.rafekettler.com/magicmethods.html</a></p>
0
2015-02-27T07:48:14Z
[ "python" ]
Python object.__repr__(self) should be an expression?
452,300
<p>I was looking at the builtin object methods in the <a href="http://docs.python.org/reference/datamodel.html#objects-values-and-types">Python documentation</a>, and I was interested in the documentation for <code>object.__repr__(self)</code>. Here's what it says:</p> <blockquote> <p>Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form &lt;...some useful description...> should be returned. The return value must be a string object. If a class defines <strong>repr</strong>() but not <strong>str</strong>(), then <strong>repr</strong>() is also used when an “informal” string representation of instances of that class is required.</p> <p>This is typically used for debugging, so it is important that the representation is information-rich and unambiguous</p> </blockquote> <p>The most interesting part to me, was...</p> <blockquote> <p>If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value</p> </blockquote> <p>... but I'm not sure exactly what this means. It says it should <em>look</em> like an expression which can be used to recreate the object, but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?</p> <p>In general I'm a bit confused as to exactly what I should be putting here.</p>
51
2009-01-16T22:37:18Z
31,559,519
<p>I think the confusion over here roots from the english. I mean <code>__repr__()</code>; short for 'representation' of the value I'm guessing, like @S.Lott said </p> <blockquote> <p>"What is the difference between "an actual expression, that can ... recreate the object" and "a rehasing of the actual expression which was used [to create the object]"? Both are an expression that creates the object. There's no practical distinction between these. A repr call could produce either a new expression or the original expression. In many cases, they're the same."</p> </blockquote> <p>But in some cases they might be different. E.g; coordinate points, you might want <code>c.coordinate</code> to return: <code>3,5</code> but <code>c.__repr__</code> to return <code>Coordinate(3, 5)</code>. Hope that makes more sense... </p>
0
2015-07-22T09:44:21Z
[ "python" ]
What are the benefits of using Python for web programming?
452,305
<p>What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web?</p>
9
2009-01-16T22:38:56Z
452,317
<p>Certainly one successful use of Python on the web is <a href="http://code.google.com/appengine/" rel="nofollow">Google App Engine</a>. Site authors write code in (a slightly restricted subset of) Python, which is then executed by the App Engine servers in a distributed and scalable manner.</p>
5
2009-01-16T22:42:54Z
[ "python", "programming-languages" ]
What are the benefits of using Python for web programming?
452,305
<p>What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web?</p>
9
2009-01-16T22:38:56Z
452,324
<p><a href="http://www.djangoproject.com/">Django</a> is, IMHO, one of the major benefits of using Python. Model your domain, code your classes, and voila, your ORM is done, and you can focus on the UI. Add in the ease of templating with the built-in templating language (or one of many others you can use as well), and it becomes <em>very</em> easy to whip up effective web applications in no time. Throw in the built-in admin interface, and it's a no-brainer.</p>
13
2009-01-16T22:45:56Z
[ "python", "programming-languages" ]
What are the benefits of using Python for web programming?
452,305
<p>What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web?</p>
9
2009-01-16T22:38:56Z
452,328
<p><a href="http://trac.edgewall.org/" rel="nofollow">trac</a>(bug tracker) and <a href="http://moinmo.in/" rel="nofollow">moinmoin</a>(wiki) are too web based python tools that I find invaluable.</p>
1
2009-01-16T22:47:28Z
[ "python", "programming-languages" ]
What are the benefits of using Python for web programming?
452,305
<p>What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web?</p>
9
2009-01-16T22:38:56Z
452,352
<p>Dynamic languages are in general good for web apps because the speed of development. Python in particular has two advantages over most of them:</p> <ul> <li>"batteries included" means <em>lots</em> of available libraries</li> <li>Django. For me this is the only reason why i use Python instead of Lua (which i like a lot more).</li> </ul>
0
2009-01-16T22:59:19Z
[ "python", "programming-languages" ]
What are the benefits of using Python for web programming?
452,305
<p>What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web?</p>
9
2009-01-16T22:38:56Z
452,356
<p>GNU Mailman is another project written in python that is widely successful.</p>
1
2009-01-16T22:59:52Z
[ "python", "programming-languages" ]
What are the benefits of using Python for web programming?
452,305
<p>What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web?</p>
9
2009-01-16T22:38:56Z
452,384
<p>Besides the frameworks...</p> <ul> <li>Python's pervasive support for Unicode should make i18n much smoother.</li> <li>A sane namespace system makes debugging much nicer, because it's typically easier to find where things are defined.</li> <li>Python's inability to function as a standalone templating language should discourage the mixture of HTML with model code</li> <li>Great standard library</li> </ul>
0
2009-01-16T23:16:55Z
[ "python", "programming-languages" ]
What are the benefits of using Python for web programming?
452,305
<p>What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web?</p>
9
2009-01-16T22:38:56Z
452,392
<p>Other examples of Python sites are Reddit and YouTube.</p>
0
2009-01-16T23:22:47Z
[ "python", "programming-languages" ]
What are the benefits of using Python for web programming?
452,305
<p>What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web?</p>
9
2009-01-16T22:38:56Z
452,403
<p><a href="http://www.python.org/about/quotes/">Quotes about Python</a>:</p> <blockquote> <p>"Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers," said Cuong Do, Software Architect, <a href="http://youtube.com">YouTube.com</a>.</p> </blockquote>
5
2009-01-16T23:26:08Z
[ "python", "programming-languages" ]
What are the benefits of using Python for web programming?
452,305
<p>What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web?</p>
9
2009-01-16T22:38:56Z
452,462
<p>Short anwser: the diversity of tools readily available and freedom of choice.</p> <p>This sounds like a simple question but which it really isn't. While Python is very good for web development and this has been shown by the, oh so famous, <a href="http://code.google.com/appengine/" rel="nofollow">Google App Engine</a>, <a href="http://plone.org/" rel="nofollow">Plone</a> and <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>. One has to point out that the development way in Python requires a lot more from the developer than <a href="http://www.php.net/" rel="nofollow">PHP</a> but it gives a lot more to the mix as well. </p> <p>The entry level on actually producing something is higher. This is because there are bunch of different tools for doing web development with Python. Choosing the web development framework can be a hard decision for an inexperienced developer.</p> <p>Having a lot of different tools is a two edged sword. To some extent it brings you the freedom of choice to pick the one you might want but then again how do you really know which one is good for what you're doing. This brings me to my point. Python stands out from the mass by not having a standard or de facto web development library. While this is pretty much against the principle of having only one simple way of doing on thing it also brings us a wide variety of different tools with different kind of design choices. At first this might feel very frustrating because it would be so much easier if somebody had made the choice for you but now that you're left to make the choice you actually might have to think about what you're doing and what would fit. ...or you might just end up picking one and blowing your head off after you've realized that you made the wrong choice. Anyway you end up, you've made the choice and no one else.</p>
2
2009-01-16T23:52:11Z
[ "python", "programming-languages" ]
What are the benefits of using Python for web programming?
452,305
<p>What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web?</p>
9
2009-01-16T22:38:56Z
452,600
<p>As many have pointed out, Django is a great reason to use Python...so in order to figure out why Python is great for web development, the best bet is to look at why it is a good language to build a framework like Django.</p> <p>IMHO Python combines the cleanest, or at least one of the cleanest, metaprogramming models of any language with a very pure object orientation. This not only makes it possible to write extremely general abstractions that are easy to use, but also allows the abstractions to combine relatively cleanly with others. This is harder to do in languages that take a code-generation based approach to metaprogramming (e.g. Ruby).</p>
1
2009-01-17T01:12:28Z
[ "python", "programming-languages" ]
What are the benefits of using Python for web programming?
452,305
<p>What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web?</p>
9
2009-01-16T22:38:56Z
453,371
<p>YouTube uses a lot of Python and is probably the best example of a Python success story.</p> <p>A great example of a Django success story is the Washington Post, who recently shared a big list of applications they have developed:</p> <p><a href="http://push.cx/2009/washington-post-update" rel="nofollow">http://push.cx/2009/washington-post-update</a></p> <p><a href="http://www.lawrence.com/" rel="nofollow">www.lawrence.com</a> and <a href="http://www.ljworld.com/" rel="nofollow">www.ljworld.com</a> are two of the first sites to use Django (before it was even open source).</p> <p><a href="http://djangositeoftheweek.com/" rel="nofollow">djangositeoftheweek.com</a> has a bunch of good case studies.</p> <p><a href="http://www.everyblock.com/" rel="nofollow">www.everyblock.com</a> is another great example.</p> <p>Finally, <a href="http://www.djangosites.org/" rel="nofollow">http://www.djangosites.org/</a> links to nearly 2,000 other Django powered sites.</p>
3
2009-01-17T14:35:02Z
[ "python", "programming-languages" ]