title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
Which is more preferable to use in Python: lambda functions or nested functions ('def')? | 134,626 | <p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p>
<p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p>
<p><strong>Lambda function</strong></p>
<pre><code>>>> a = lambda x : 1 + x
>>> a(5)
6
</code></pre>
<p><strong>Nested function</strong></p>
<pre><code>>>> def b(x): return 1 + x
>>> b(5)
6
</code></pre>
<p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">âThere should be oneâand preferably only oneâobvious way to do itâ</a>.</p>
| 58 | 2008-09-25T17:15:03Z | 788,533 | <p>lambda is usefull for generating new functions:</p>
<pre><code>def somefunc(x): return lambda y: x+y
f = somefunc(10)
f(2)
>>> 12
f(4)
>>> 14
</code></pre>
| 1 | 2009-04-25T08:35:43Z | [
"python",
"syntax",
"function",
"lambda"
] |
Which is more preferable to use in Python: lambda functions or nested functions ('def')? | 134,626 | <p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p>
<p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p>
<p><strong>Lambda function</strong></p>
<pre><code>>>> a = lambda x : 1 + x
>>> a(5)
6
</code></pre>
<p><strong>Nested function</strong></p>
<pre><code>>>> def b(x): return 1 + x
>>> b(5)
6
</code></pre>
<p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">âThere should be oneâand preferably only oneâobvious way to do itâ</a>.</p>
| 58 | 2008-09-25T17:15:03Z | 1,004,492 | <p>An important limitation of lambdas is that they cannot contain anything besides an expression. It's nearly impossible for a lambda expression to produce anything besides trivial side effects, since it cannot have anywhere near as rich a body as a <code>def</code>'ed function.</p>
<p>That being said, Lua influenced my programming style toward the extensive use of anonymous functions, and I litter my code with them. On top of that, I tend to think about map/reduce as abstract operators in ways I don't consider list comprehensions or generators, almost as If I'm deferring an implementation decision explicitly by using those operators. </p>
<p><strong>Edit:</strong> This is a pretty old question, and my opinions on the matter have changed, somewhat.</p>
<p>First off, I am strongly biased against assigning a <code>lambda</code> expression to a variable; as python has a special syntax just for that (hint, <code>def</code>). In addition to that, many of the uses for lambda, even when they don't get a name, have predefined (and more efficient) implementations. For instance, the example in question can be abbreviated to just <code>(1).__add__</code>, without the need to wrap it in a <code>lambda</code> or <code>def</code>. Many other common uses can be satisfied with some combination of the <code>operator</code>, <code>itertools</code> and <code>functools</code> modules.</p>
| 2 | 2009-06-17T00:02:38Z | [
"python",
"syntax",
"function",
"lambda"
] |
Which is more preferable to use in Python: lambda functions or nested functions ('def')? | 134,626 | <p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p>
<p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p>
<p><strong>Lambda function</strong></p>
<pre><code>>>> a = lambda x : 1 + x
>>> a(5)
6
</code></pre>
<p><strong>Nested function</strong></p>
<pre><code>>>> def b(x): return 1 + x
>>> b(5)
6
</code></pre>
<p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">âThere should be oneâand preferably only oneâobvious way to do itâ</a>.</p>
| 58 | 2008-09-25T17:15:03Z | 11,988,012 | <p>For n=1000 here's some timeit's of calling a function vs a lambda:</p>
<pre><code>In [11]: def f(a, b):
return a * b
In [12]: g = lambda x, y: x * y
In [13]: %%timeit -n 100
for a in xrange(n):
for b in xrange(n):
f(a, b)
....:
100 loops, best of 3: 285 ms per loop
In [14]: %%timeit -n 100
for a in xrange(n):
for b in xrange(n):
g(a, b)
....:
100 loops, best of 3: 298 ms per loop
In [15]: %%timeit -n 100
for a in xrange(n):
for b in xrange(n):
(lambda x, y: x * y)(a, b)
....:
100 loops, best of 3: 462 ms per loop
</code></pre>
| 6 | 2012-08-16T13:16:40Z | [
"python",
"syntax",
"function",
"lambda"
] |
Which is more preferable to use in Python: lambda functions or nested functions ('def')? | 134,626 | <p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p>
<p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p>
<p><strong>Lambda function</strong></p>
<pre><code>>>> a = lambda x : 1 + x
>>> a(5)
6
</code></pre>
<p><strong>Nested function</strong></p>
<pre><code>>>> def b(x): return 1 + x
>>> b(5)
6
</code></pre>
<p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">âThere should be oneâand preferably only oneâobvious way to do itâ</a>.</p>
| 58 | 2008-09-25T17:15:03Z | 20,799,400 | <p>While agreeing with the other answers, sometimes it's more readable. Here's an example where <code>lambda</code> comes in handy, in a use case I keep encountering of an N dimensional <a href="http://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a>.<br>Here's an example:</p>
<pre><code>from collections import defaultdict
d = defaultdict(lambda: defaultdict(list))
d['Foo']['Bar'].append(something)
</code></pre>
<p>I find it more readable than creating a <code>def</code> for the second dimension. This is even more significant for higher dimensions.</p>
| 3 | 2013-12-27T10:54:37Z | [
"python",
"syntax",
"function",
"lambda"
] |
Which is more preferable to use in Python: lambda functions or nested functions ('def')? | 134,626 | <p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p>
<p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p>
<p><strong>Lambda function</strong></p>
<pre><code>>>> a = lambda x : 1 + x
>>> a(5)
6
</code></pre>
<p><strong>Nested function</strong></p>
<pre><code>>>> def b(x): return 1 + x
>>> b(5)
6
</code></pre>
<p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">âThere should be oneâand preferably only oneâobvious way to do itâ</a>.</p>
| 58 | 2008-09-25T17:15:03Z | 33,269,715 | <p>One use for lambdas I have found... is in debug messages.</p>
<p>Since lambdas can be lazily evaluated you can have code like this:</p>
<pre><code>log.debug(lambda: "this is my message: %r" % (some_data,))
</code></pre>
<p>instead of possibly expensive:</p>
<pre><code>log.debug("this is my message: %r" % (some_data,))
</code></pre>
<p>which processes the format string even if the debug call does not produce output because of current logging level.</p>
<p>Of course for it to work as described the logging module in use must support lambdas as "lazy parameters" (as my logging module does).</p>
<p>The same idea may be applied to any other case of lazy evaluation for on demand content value creation.</p>
<p>For example this custom ternary operator:</p>
<pre><code>def mif(condition, when_true, when_false):
if condition:
return when_true()
else:
return when_false()
mif(a < b, lambda: a + a, lambda: b + b)
</code></pre>
<p>instead of:</p>
<pre><code>def mif(condition, when_true, when_false):
if condition:
return when_true
else:
return when_false
mif(a < b, a + a, b + b)
</code></pre>
<p>with lambdas only the expression selected by the condition will be evaluated, without lambdas both will be evaluated.</p>
<p>Of course you could simply use functions instead of lambdas, but for short expressions lambdas are (c)leaner.</p>
| 2 | 2015-10-21T21:37:03Z | [
"python",
"syntax",
"function",
"lambda"
] |
Which is more preferable to use in Python: lambda functions or nested functions ('def')? | 134,626 | <p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. </p>
<p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p>
<p><strong>Lambda function</strong></p>
<pre><code>>>> a = lambda x : 1 + x
>>> a(5)
6
</code></pre>
<p><strong>Nested function</strong></p>
<pre><code>>>> def b(x): return 1 + x
>>> b(5)
6
</code></pre>
<p>Is there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If doesn't then does that violate the Pythonic principle: <a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Philosophy">âThere should be oneâand preferably only oneâobvious way to do itâ</a>.</p>
| 58 | 2008-09-25T17:15:03Z | 35,346,979 | <p><em>Performance:</em></p>
<p>Creating a function with <code>lambda</code> is <em>slightly faster</em> than creating it with <code>def</code>. The difference is due to <code>def</code> creating a name entry in the locals table. The resulting function has the same execution speed.</p>
<hr>
<p>Readability:</p>
<p>Lambda functions are somewhat less readable for most Python users, but also much more concise in some circumstances. Consider converting from using non-functional to functional routine:</p>
<pre><code># Using non-functional version.
heading(math.sqrt(v.x * v.x + v.y * v.y), math.atan(v.y / v.x))
# Using lambda with functional version.
fheading(v, lambda v: math.sqrt(v.x * v.x + v.y * v.y), lambda v: math.atan(v.y / v.x))
# Using def with functional version.
def size(v):
return math.sqrt(v.x * v.x + v.y * v.y)
def direction(v):
return math.atan(v.y / v.x)
deal_with_headings(v, size, direction)
</code></pre>
<p>As you can see, the <code>lambda</code> version is shorter and "easier" in the sense that you only need to add <code>lambda v:</code> to the original non-functional version to convert to the functional version. It's also a lot more concise. But remember, a lot of Python users will be confused by the lambda syntax, so what you lose in length and real complexity might be gained back in confusion from fellow coders.</p>
<hr>
<p>Limitations:</p>
<ul>
<li><code>lambda</code> functions can only be used once, unless assigned to a variable name.</li>
<li><code>lambda</code> functions assigned to variable names have no advantage over <code>def</code> functions.</li>
<li><code>lambda</code> functions can be difficult or impossible to pickle.</li>
<li><code>def</code> functions' names must be carefully chosen to be reasonably descriptive and unique or at least otherwise unused in scope.</li>
</ul>
<hr>
<p>Consistency:</p>
<p>Python mostly avoids functional programming conventions in favor of procedural and simpler objective semantics. The <code>lambda</code> operator stands in direct contrast to this bias. Moreover, as an alternative to the already prevalent <code>def</code>, the <code>lambda</code> function adds diversity to your syntax. Some would consider that less consistent.</p>
<hr>
<p>Pre-existing functions:</p>
<p>As noted by others, many uses of <code>lambda</code> in the field can be replaced by members of the <code>operator</code> or other modules. For instance:</p>
<pre><code>do_something(x, y, lambda x, y: x + y)
do_something(x, y, operator.add)
</code></pre>
<p>Using the pre-existing function can make code more readable in many cases.</p>
<hr>
<p>The Pythonic principle: âThere should be oneâand preferably only oneâobvious way to do itâ</p>
<p>That's similar to the <a href="https://en.wikipedia.org/wiki/Single_source_of_truth" rel="nofollow">single source of truth</a> doctrine. Unfortunately, the single-obvious-way-to-do-it principle has always been more an wistful aspiration for Python, rather than a true guiding principal. Consider the very-powerful array comprehensions in Python. They are functionally equivalent to the <code>map</code> and <code>filter</code> functions:</p>
<pre><code>[e for e in some_array if some_condition(e)]
filter(some_array, some_condition)
</code></pre>
<p><code>lambda</code> and <code>def</code> are the same.</p>
<p>It's a matter of opinion, but I would say that anything in the Python language intended for general use which doesn't obviously break anything is "Pythonic" enough.</p>
| 1 | 2016-02-11T18:14:36Z | [
"python",
"syntax",
"function",
"lambda"
] |
How do I use django.core.urlresolvers.reverse with a function reference instead of a named URL pattern? | 134,629 | <p>In my <code>urls.py</code> file, I have:</p>
<pre><code>from myapp import views
...
(r'^categories/$', views.categories)
</code></pre>
<p>Where <code>categories</code> is a view function inside <code>myapp/views.py</code>. No other URLconf lines reference <code>views.categories</code>.</p>
<p>In a unit test file, Iâm trying to grab this URL using <code>django.core.urlresolvers.reverse()</code>, instead of just copying '/categories/' (DRY and all that). So, I have:</p>
<pre><code>from django.core.urlresolvers import reverse
from myapp import views
...
url = reverse(views.categories)
</code></pre>
<p>When I run my tests, I get a <code>NoReverseMatch</code> error:</p>
<pre><code>NoReverseMatch: Reverse for '<function categories at 0x1082f30>' with arguments '()' and keyword arguments '{}' not found.
</code></pre>
<p>It matches just fine if I make the URL pattern a named pattern, like this:</p>
<pre><code>url(r'^categories/$', views.categories, 'myapp-categories')
</code></pre>
<p>And use the pattern name to match it:</p>
<pre><code>url = reverse('myapp-categories')
</code></pre>
<p>But as far as I can tell from <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse">the <code>reverse</code> documentation</a>, I shouldnât need to make it a named URL pattern just to use <code>reverse</code>.</p>
<p>Any ideas what Iâm doing wrong?</p>
| 7 | 2008-09-25T17:15:23Z | 134,651 | <p>The reverse function actually uses the "name" of the URL. This is defined like so:</p>
<pre><code>urlpatterns = patterns('',
(r'^no_monkeys/$', 'views.noMonkeys', {}, "no-monkeys"),
(r'^admin/(.*)', admin.site.root),
)
</code></pre>
<p>Now you would call reverse with the string "no-monkeys" to get the correct url.</p>
<p>Ninja Edit: <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#id2" rel="nofollow">Here is a link</a> to the django docs on the subject.</p>
| -1 | 2008-09-25T17:18:16Z | [
"python",
"django"
] |
How do I use django.core.urlresolvers.reverse with a function reference instead of a named URL pattern? | 134,629 | <p>In my <code>urls.py</code> file, I have:</p>
<pre><code>from myapp import views
...
(r'^categories/$', views.categories)
</code></pre>
<p>Where <code>categories</code> is a view function inside <code>myapp/views.py</code>. No other URLconf lines reference <code>views.categories</code>.</p>
<p>In a unit test file, Iâm trying to grab this URL using <code>django.core.urlresolvers.reverse()</code>, instead of just copying '/categories/' (DRY and all that). So, I have:</p>
<pre><code>from django.core.urlresolvers import reverse
from myapp import views
...
url = reverse(views.categories)
</code></pre>
<p>When I run my tests, I get a <code>NoReverseMatch</code> error:</p>
<pre><code>NoReverseMatch: Reverse for '<function categories at 0x1082f30>' with arguments '()' and keyword arguments '{}' not found.
</code></pre>
<p>It matches just fine if I make the URL pattern a named pattern, like this:</p>
<pre><code>url(r'^categories/$', views.categories, 'myapp-categories')
</code></pre>
<p>And use the pattern name to match it:</p>
<pre><code>url = reverse('myapp-categories')
</code></pre>
<p>But as far as I can tell from <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse">the <code>reverse</code> documentation</a>, I shouldnât need to make it a named URL pattern just to use <code>reverse</code>.</p>
<p>Any ideas what Iâm doing wrong?</p>
| 7 | 2008-09-25T17:15:23Z | 135,899 | <p>This does work, and all the code that you've pasted is correct and works fine (I just copied it into a clean test/project app and it reversed the URL without any problem). So there's something else going on here that you haven't showed us. Simplify down to the bare-bones basics until it works, then start adding complexity back in and see where it's breaking.</p>
<p>Also, you can do "./manage.py shell" and then interactively import the reverse function and your view function and try the reverse. That'll remove the test setup as a possible cause.</p>
| 0 | 2008-09-25T20:39:30Z | [
"python",
"django"
] |
How do I use django.core.urlresolvers.reverse with a function reference instead of a named URL pattern? | 134,629 | <p>In my <code>urls.py</code> file, I have:</p>
<pre><code>from myapp import views
...
(r'^categories/$', views.categories)
</code></pre>
<p>Where <code>categories</code> is a view function inside <code>myapp/views.py</code>. No other URLconf lines reference <code>views.categories</code>.</p>
<p>In a unit test file, Iâm trying to grab this URL using <code>django.core.urlresolvers.reverse()</code>, instead of just copying '/categories/' (DRY and all that). So, I have:</p>
<pre><code>from django.core.urlresolvers import reverse
from myapp import views
...
url = reverse(views.categories)
</code></pre>
<p>When I run my tests, I get a <code>NoReverseMatch</code> error:</p>
<pre><code>NoReverseMatch: Reverse for '<function categories at 0x1082f30>' with arguments '()' and keyword arguments '{}' not found.
</code></pre>
<p>It matches just fine if I make the URL pattern a named pattern, like this:</p>
<pre><code>url(r'^categories/$', views.categories, 'myapp-categories')
</code></pre>
<p>And use the pattern name to match it:</p>
<pre><code>url = reverse('myapp-categories')
</code></pre>
<p>But as far as I can tell from <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse">the <code>reverse</code> documentation</a>, I shouldnât need to make it a named URL pattern just to use <code>reverse</code>.</p>
<p>Any ideas what Iâm doing wrong?</p>
| 7 | 2008-09-25T17:15:23Z | 136,721 | <p>Jack M.'s example is nearly correct.</p>
<p>It needs to be a url function, not a tuple, if you want to use named urls.</p>
<pre><code>url(r'^no_monkeys/$', 'views.noMonkeys', {}, "no-monkeys"),
</code></pre>
| 2 | 2008-09-25T22:55:44Z | [
"python",
"django"
] |
How do I use django.core.urlresolvers.reverse with a function reference instead of a named URL pattern? | 134,629 | <p>In my <code>urls.py</code> file, I have:</p>
<pre><code>from myapp import views
...
(r'^categories/$', views.categories)
</code></pre>
<p>Where <code>categories</code> is a view function inside <code>myapp/views.py</code>. No other URLconf lines reference <code>views.categories</code>.</p>
<p>In a unit test file, Iâm trying to grab this URL using <code>django.core.urlresolvers.reverse()</code>, instead of just copying '/categories/' (DRY and all that). So, I have:</p>
<pre><code>from django.core.urlresolvers import reverse
from myapp import views
...
url = reverse(views.categories)
</code></pre>
<p>When I run my tests, I get a <code>NoReverseMatch</code> error:</p>
<pre><code>NoReverseMatch: Reverse for '<function categories at 0x1082f30>' with arguments '()' and keyword arguments '{}' not found.
</code></pre>
<p>It matches just fine if I make the URL pattern a named pattern, like this:</p>
<pre><code>url(r'^categories/$', views.categories, 'myapp-categories')
</code></pre>
<p>And use the pattern name to match it:</p>
<pre><code>url = reverse('myapp-categories')
</code></pre>
<p>But as far as I can tell from <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse">the <code>reverse</code> documentation</a>, I shouldnât need to make it a named URL pattern just to use <code>reverse</code>.</p>
<p>Any ideas what Iâm doing wrong?</p>
| 7 | 2008-09-25T17:15:23Z | 146,596 | <p>After futher investigation, turns out it was an issue with how I was importing the views module:</p>
<p><a href="http://stackoverflow.com/questions/146522/how-do-i-successfully-pass-a-function-reference-to-djangos-reverse-function">http://stackoverflow.com/questions/146522/how-do-i-successfully-pass-a-function-reference-to-djangos-reverse-function</a></p>
<p>Thanks for the help though, guys: you inspired me to look at it properly.</p>
| 2 | 2008-09-28T19:56:18Z | [
"python",
"django"
] |
Display number with leading zeros | 134,934 | <p>Given:</p>
<pre><code>a = 1
b = 10
c = 100
</code></pre>
<p>I want to display a leading zero for all numbers with less than 2 digits, i.e.:</p>
<pre><code>01
10
100
</code></pre>
| 356 | 2008-09-25T18:06:06Z | 134,942 | <pre><code>x = [1, 10, 100]
for i in x:
print '%02d' % i
</code></pre>
<p>results:</p>
<pre><code>01
10
100
</code></pre>
<p>Read <a href="https://pyformat.info/">more information about string formatting using %</a> in the documentation.</p>
| 46 | 2008-09-25T18:07:37Z | [
"python",
"string-formatting"
] |
Display number with leading zeros | 134,934 | <p>Given:</p>
<pre><code>a = 1
b = 10
c = 100
</code></pre>
<p>I want to display a leading zero for all numbers with less than 2 digits, i.e.:</p>
<pre><code>01
10
100
</code></pre>
| 356 | 2008-09-25T18:06:06Z | 134,951 | <p>Here you are:</p>
<pre><code>print "%02d" % (1,)
</code></pre>
<p>Basically <strong>%</strong> is like <code>printf</code> or <code>sprint</code>.</p>
| 405 | 2008-09-25T18:08:21Z | [
"python",
"string-formatting"
] |
Display number with leading zeros | 134,934 | <p>Given:</p>
<pre><code>a = 1
b = 10
c = 100
</code></pre>
<p>I want to display a leading zero for all numbers with less than 2 digits, i.e.:</p>
<pre><code>01
10
100
</code></pre>
| 356 | 2008-09-25T18:06:06Z | 134,961 | <p>Use a format string - <a href="http://docs.python.org/lib/typesseq-strings.html" rel="nofollow">http://docs.python.org/lib/typesseq-strings.html</a></p>
<p>For example:</p>
<pre><code>python -c 'print "%(num)02d" % {"num":5}'
</code></pre>
| 3 | 2008-09-25T18:10:01Z | [
"python",
"string-formatting"
] |
Display number with leading zeros | 134,934 | <p>Given:</p>
<pre><code>a = 1
b = 10
c = 100
</code></pre>
<p>I want to display a leading zero for all numbers with less than 2 digits, i.e.:</p>
<pre><code>01
10
100
</code></pre>
| 356 | 2008-09-25T18:06:06Z | 135,157 | <p>In Python 3, you would use the format() string method:</p>
<pre><code>for i in (1, 10, 100):
print('{num:02d}'.format(num=i))
</code></pre>
<p>or using the built-in (for a single number):</p>
<pre><code>print(format(i, '02d'))
</code></pre>
<p>See the <a href="http://www.python.org/dev/peps/pep-3101">PEP-3101</a> documentation for the new formatting functions.</p>
| 172 | 2008-09-25T18:43:06Z | [
"python",
"string-formatting"
] |
Display number with leading zeros | 134,934 | <p>Given:</p>
<pre><code>a = 1
b = 10
c = 100
</code></pre>
<p>I want to display a leading zero for all numbers with less than 2 digits, i.e.:</p>
<pre><code>01
10
100
</code></pre>
| 356 | 2008-09-25T18:06:06Z | 3,371,180 | <p>You can use zfill:</p>
<pre><code>print str(1).zfill(2)
print str(10).zfill(2)
print str(100).zfill(2)
</code></pre>
<p>prints:</p>
<pre><code>01
10
100
</code></pre>
| 392 | 2010-07-30T11:58:30Z | [
"python",
"string-formatting"
] |
Display number with leading zeros | 134,934 | <p>Given:</p>
<pre><code>a = 1
b = 10
c = 100
</code></pre>
<p>I want to display a leading zero for all numbers with less than 2 digits, i.e.:</p>
<pre><code>01
10
100
</code></pre>
| 356 | 2008-09-25T18:06:06Z | 4,143,246 | <p>Or this:</p>
<p><code>print '{0:02d}'.format(1)</code></p>
| 60 | 2010-11-10T10:03:43Z | [
"python",
"string-formatting"
] |
Display number with leading zeros | 134,934 | <p>Given:</p>
<pre><code>a = 1
b = 10
c = 100
</code></pre>
<p>I want to display a leading zero for all numbers with less than 2 digits, i.e.:</p>
<pre><code>01
10
100
</code></pre>
| 356 | 2008-09-25T18:06:06Z | 10,358,441 | <p>The pythonic way to do this:</p>
<pre><code>str(number).rjust(string_width, fill_char)
</code></pre>
<p>This way, the original string is returned unchanged if its length is greater than string_width. Example:</p>
<pre><code>a = [1, 10, 100]
for num in a:
print str(num).rjust(2, '0')
</code></pre>
<p>Results:</p>
<pre><code>01
10
100
</code></pre>
| 24 | 2012-04-27T22:02:37Z | [
"python",
"string-formatting"
] |
Display number with leading zeros | 134,934 | <p>Given:</p>
<pre><code>a = 1
b = 10
c = 100
</code></pre>
<p>I want to display a leading zero for all numbers with less than 2 digits, i.e.:</p>
<pre><code>01
10
100
</code></pre>
| 356 | 2008-09-25T18:06:06Z | 19,962,689 | <pre><code>print '{:02}'.format(a)
print '{:02}'.format(b)
print '{:02}'.format(c)
</code></pre>
<p>prints:</p>
<pre><code>01
10
100
</code></pre>
| 20 | 2013-11-13T19:30:23Z | [
"python",
"string-formatting"
] |
Display number with leading zeros | 134,934 | <p>Given:</p>
<pre><code>a = 1
b = 10
c = 100
</code></pre>
<p>I want to display a leading zero for all numbers with less than 2 digits, i.e.:</p>
<pre><code>01
10
100
</code></pre>
| 356 | 2008-09-25T18:06:06Z | 20,005,921 | <pre><code>width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted
</code></pre>
| 4 | 2013-11-15T16:33:33Z | [
"python",
"string-formatting"
] |
Display number with leading zeros | 134,934 | <p>Given:</p>
<pre><code>a = 1
b = 10
c = 100
</code></pre>
<p>I want to display a leading zero for all numbers with less than 2 digits, i.e.:</p>
<pre><code>01
10
100
</code></pre>
| 356 | 2008-09-25T18:06:06Z | 33,860,138 | <p>Or another solution. </p>
<pre><code>"{:0>2}".format(number)
</code></pre>
| 21 | 2015-11-22T21:01:27Z | [
"python",
"string-formatting"
] |
Display number with leading zeros | 134,934 | <p>Given:</p>
<pre><code>a = 1
b = 10
c = 100
</code></pre>
<p>I want to display a leading zero for all numbers with less than 2 digits, i.e.:</p>
<pre><code>01
10
100
</code></pre>
| 356 | 2008-09-25T18:06:06Z | 35,497,237 | <p>If dealing with numbers that are either one or two digits:</p>
<p><code>'0'+str(number)[-2:]</code> or <code>'0{0}'.format(number)[-2:]</code></p>
| -1 | 2016-02-19T04:20:45Z | [
"python",
"string-formatting"
] |
Python Library Path | 135,035 | <p>In ruby the library path is provided in $:, in perl it's in @INC - how do you get the list of paths that Python searches for modules when you do an import?</p>
| 30 | 2008-09-25T18:23:50Z | 135,050 | <pre><code>import sys
sys.path
</code></pre>
| 7 | 2008-09-25T18:25:07Z | [
"python"
] |
Python Library Path | 135,035 | <p>In ruby the library path is provided in $:, in perl it's in @INC - how do you get the list of paths that Python searches for modules when you do an import?</p>
| 30 | 2008-09-25T18:23:50Z | 135,051 | <p>I think you're looking for <a href="https://docs.python.org/3/library/sys.html#sys.path">sys.path</a></p>
<pre><code>import sys
print (sys.path)
</code></pre>
| 44 | 2008-09-25T18:25:18Z | [
"python"
] |
Python Library Path | 135,035 | <p>In ruby the library path is provided in $:, in perl it's in @INC - how do you get the list of paths that Python searches for modules when you do an import?</p>
| 30 | 2008-09-25T18:23:50Z | 135,273 | <p>You can also make additions to this path with the PYTHONPATH environment variable at runtime, in addition to:</p>
<pre><code>import sys
sys.path.append('/home/user/python-libs')
</code></pre>
| 40 | 2008-09-25T19:02:46Z | [
"python"
] |
Should you always favor xrange() over range()? | 135,041 | <p>Why or why not?</p>
| 375 | 2008-09-25T18:24:37Z | 135,070 | <p><code>xrange()</code> is more efficient because instead of generating a list of objects, it just generates one object at a time. Instead of 100 integers, and all of their overhead, and the list to put them in, you just have one integer at a time. Faster generation, better memory use, more efficient code.</p>
<p>Unless I specifically need a list for something, I always favor <code>xrange()</code></p>
| 11 | 2008-09-25T18:28:16Z | [
"python",
"range",
"xrange"
] |
Should you always favor xrange() over range()? | 135,041 | <p>Why or why not?</p>
| 375 | 2008-09-25T18:24:37Z | 135,074 | <p>You should favour <code>range()</code> over <code>xrange()</code> only when you need an actual list. For instance, when you want to modify the list returned by <code>range()</code>, or when you wish to slice it. For iteration or even just normal indexing, <code>xrange()</code> will work fine (and usually much more efficiently). There is a point where <code>range()</code> is a bit faster than <code>xrange()</code> for very small lists, but depending on your hardware and various other details, the break-even can be at a result of length 1 or 2; not something to worry about. Prefer <code>xrange()</code>.</p>
| 34 | 2008-09-25T18:28:49Z | [
"python",
"range",
"xrange"
] |
Should you always favor xrange() over range()? | 135,041 | <p>Why or why not?</p>
| 375 | 2008-09-25T18:24:37Z | 135,081 | <p>Go with range for these reasons:</p>
<p>1) xrange will be going away in newer Python versions. This gives you easy future compatibility.</p>
<p>2) range will take on the efficiencies associated with xrange.</p>
| 2 | 2008-09-25T18:29:50Z | [
"python",
"range",
"xrange"
] |
Should you always favor xrange() over range()? | 135,041 | <p>Why or why not?</p>
| 375 | 2008-09-25T18:24:37Z | 135,114 | <p>For performance, especially when you're iterating over a large range, <code>xrange()</code> is usually better. However, there are still a few cases why you might prefer <code>range()</code>:</p>
<ul>
<li><p>In python 3, <code>range()</code> does what <code>xrange()</code> used to do and <code>xrange()</code> does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use <code>xrange()</code>.</p></li>
<li><p><code>range()</code> can actually be faster in some cases - eg. if iterating over the same sequence multiple times. <code>xrange()</code> has to reconstruct the integer object every time, but <code>range()</code> will have real integer objects. (It will always perform worse in terms of memory however)</p></li>
<li><p><code>xrange()</code> isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.</p></li>
</ul>
<p>[Edit] There are a couple of posts mentioning how <code>range()</code> will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of <code>range()</code> and <code>xrange()</code></p>
<pre><code>RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: ws_comma
--- range_test.py (original)
+++ range_test.py (refactored)
@@ -1,7 +1,7 @@
for x in range(20):
- a=range(20)
+ a=list(range(20))
b=list(range(20))
c=[x for x in range(20)]
d=(x for x in range(20))
- e=xrange(20)
+ e=range(20)
</code></pre>
<p>As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged.</p>
| 370 | 2008-09-25T18:34:38Z | [
"python",
"range",
"xrange"
] |
Should you always favor xrange() over range()? | 135,041 | <p>Why or why not?</p>
| 375 | 2008-09-25T18:24:37Z | 135,228 | <p>range() returns a list, xrange() returns an xrange object.</p>
<p>xrange() is a bit faster, and a bit more memory efficient. But the gain is not very large.</p>
<p>The extra memory used by a list is of course not just wasted, lists have more functionality (slice, repeat, insert, ...). Exact differences can be found in the <a href="http://docs.python.org/typesseq.html">documentation</a>. There is no bonehard rule, use what is needed.</p>
<p>Python 3.0 is still in development, but IIRC range() will very similar to xrange() of 2.X and list(range()) can be used to generate lists.</p>
| 7 | 2008-09-25T18:55:58Z | [
"python",
"range",
"xrange"
] |
Should you always favor xrange() over range()? | 135,041 | <p>Why or why not?</p>
| 375 | 2008-09-25T18:24:37Z | 135,531 | <p>Okay, everyone here as a different opinion as to the tradeoffs and advantages of xrange versus range. They're mostly correct, xrange is an iterator, and range fleshes out and creates an actual list. For the majority of cases, you won't really notice a difference between the two. (You can use map with range but not with xrange, but it uses up more memory.)</p>
<p>What I think you rally want to hear, however, is that the preferred choice is xrange. Since range in Python 3 is an iterator, the code conversion tool 2to3 will correctly convert all uses of xrange to range, and will throw out an error or warning for uses of range. If you want to be sure to easily convert your code in the future, you'll use xrange only, and list(xrange) when you're sure that you want a list. I learned this during the CPython sprint at PyCon this year (2008) in Chicago.</p>
| 2 | 2008-09-25T19:42:30Z | [
"python",
"range",
"xrange"
] |
Should you always favor xrange() over range()? | 135,041 | <p>Why or why not?</p>
| 375 | 2008-09-25T18:24:37Z | 135,669 | <p>No, they both have their uses:</p>
<p>Use <code>xrange()</code> when iterating, as it saves memory. Say:</p>
<pre><code>for x in xrange(1, one_zillion):
</code></pre>
<p>rather than:</p>
<pre><code>for x in range(1, one_zillion):
</code></pre>
<p>On the other hand, use <code>range()</code> if you actually want a list of numbers.</p>
<pre><code>multiples_of_seven = range(7,100,7)
print "Multiples of seven < 100: ", multiples_of_seven
</code></pre>
| 112 | 2008-09-25T20:04:30Z | [
"python",
"range",
"xrange"
] |
Should you always favor xrange() over range()? | 135,041 | <p>Why or why not?</p>
| 375 | 2008-09-25T18:24:37Z | 9,641,194 | <p>I would just like to say that it REALLY isn't that difficult to get an xrange object with slice and indexing functionality. I have written some code that works pretty dang well and is just as fast as xrange for when it counts (iterations).</p>
<pre><code>from __future__ import division
def read_xrange(xrange_object):
# returns the xrange object's start, stop, and step
start = xrange_object[0]
if len(xrange_object) > 1:
step = xrange_object[1] - xrange_object[0]
else:
step = 1
stop = xrange_object[-1] + step
return start, stop, step
class Xrange(object):
''' creates an xrange-like object that supports slicing and indexing.
ex: a = Xrange(20)
a.index(10)
will work
Also a[:5]
will return another Xrange object with the specified attributes
Also allows for the conversion from an existing xrange object
'''
def __init__(self, *inputs):
# allow inputs of xrange objects
if len(inputs) == 1:
test, = inputs
if type(test) == xrange:
self.xrange = test
self.start, self.stop, self.step = read_xrange(test)
return
# or create one from start, stop, step
self.start, self.step = 0, None
if len(inputs) == 1:
self.stop, = inputs
elif len(inputs) == 2:
self.start, self.stop = inputs
elif len(inputs) == 3:
self.start, self.stop, self.step = inputs
else:
raise ValueError(inputs)
self.xrange = xrange(self.start, self.stop, self.step)
def __iter__(self):
return iter(self.xrange)
def __getitem__(self, item):
if type(item) is int:
if item < 0:
item += len(self)
return self.xrange[item]
if type(item) is slice:
# get the indexes, and then convert to the number
start, stop, step = item.start, item.stop, item.step
start = start if start != None else 0 # convert start = None to start = 0
if start < 0:
start += start
start = self[start]
if start < 0: raise IndexError(item)
step = (self.step if self.step != None else 1) * (step if step != None else 1)
stop = stop if stop is not None else self.xrange[-1]
if stop < 0:
stop += stop
stop = self[stop]
stop = stop
if stop > self.stop:
raise IndexError
if start < self.start:
raise IndexError
return Xrange(start, stop, step)
def index(self, value):
error = ValueError('object.index({0}): {0} not in object'.format(value))
index = (value - self.start)/self.step
if index % 1 != 0:
raise error
index = int(index)
try:
self.xrange[index]
except (IndexError, TypeError):
raise error
return index
def __len__(self):
return len(self.xrange)
</code></pre>
<p>Honestly, I think the whole issue is kind of silly and xrange should do all of this anyway...</p>
| 5 | 2012-03-09T21:23:18Z | [
"python",
"range",
"xrange"
] |
Should you always favor xrange() over range()? | 135,041 | <p>Why or why not?</p>
| 375 | 2008-09-25T18:24:37Z | 11,795,908 | <p>One other difference is that xrange() can't support numbers bigger than C ints, so if you want to have a range using python's built in large number support, you have to use range(). </p>
<pre><code>Python 2.7.3 (default, Jul 13 2012, 22:29:01)
[GCC 4.7.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> range(123456787676676767676676,123456787676676767676679)
[123456787676676767676676L, 123456787676676767676677L, 123456787676676767676678L]
>>> xrange(123456787676676767676676,123456787676676767676679)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long
</code></pre>
<p>Python 3 does not have this problem:</p>
<pre><code>Python 3.2.3 (default, Jul 14 2012, 01:01:48)
[GCC 4.7.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> range(123456787676676767676676,123456787676676767676679)
range(123456787676676767676676, 123456787676676767676679)
</code></pre>
| 23 | 2012-08-03T12:38:58Z | [
"python",
"range",
"xrange"
] |
Should you always favor xrange() over range()? | 135,041 | <p>Why or why not?</p>
| 375 | 2008-09-25T18:24:37Z | 18,288,537 | <p>A good example given in book: <a href="http://books.google.co.in/books?id=KmKoNJ2OoOYC&pg=PA114&lpg=PA114&dq=zip%28range%285%29,%20xrange%28100000000%29%29&source=bl&ots=-BxWZinKHq&sig=O9G4mskHmYDljCCQv8v7alVUy_M&hl=en&sa=X&ei=0mMPUoa9LsXJrAe7p4DABA&ved=0CD0Q6AEwAw#v=onepage&q=zip%28range%285%29,%20xrange%28100000000%29%29&f=false" rel="nofollow">Practical Python</a> By Magnus Lie Hetland </p>
<pre><code>>>> zip(range(5), xrange(100000000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
</code></pre>
<p>I wouldnât recommend using range instead of xrange in the preceding exampleâalthough
only the first five numbers are needed, range calculates all the numbers, and that may take a lot
of time. With xrange, this isnât a problem because it calculates only those numbers needed.</p>
<p>Yes I read @Brian's answer: In python 3, range() is a generator anyway and xrange() does not exist.</p>
| 3 | 2013-08-17T11:57:52Z | [
"python",
"range",
"xrange"
] |
Should you always favor xrange() over range()? | 135,041 | <p>Why or why not?</p>
| 375 | 2008-09-25T18:24:37Z | 39,428,467 | <ul>
<li><code>range()</code>: <code>range(1, 10)</code> returns a list from 1 to 10 numbers & hold whole list in memory.</li>
<li><code>xrange()</code>: Like <code>range()</code>, but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is lightly faster than <code>range()</code> and more memory efficient. <code>xrange()</code> object like an iterator and generates the numbers on demand (Lazy Evaluation).</li>
</ul>
<pre><code>In [1]: range(1,10)
Out[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In [2]: xrange(10)
Out[2]: xrange(10)
In [3]: print xrange.__doc__
Out[3]: xrange([start,] stop[, step]) -> xrange object
</code></pre>
<p><code>range()</code> does the same thing as <code>xrange()</code> used to do in Python 3 and there is not term <code>xrange()</code> exist in Python 3.
<code>range()</code> can actually be faster in some scenario if you iterating over the same sequence multiple times. <code>xrange()</code> has to reconstruct the integer object every time, but <code>range()</code> will have real integer objects.</p>
| 0 | 2016-09-10T16:57:49Z | [
"python",
"range",
"xrange"
] |
Reading 32bit Packed Binary Data On 64bit System | 135,246 | <p>I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way of doing this?</p>
<p><hr /></p>
<p>It would be a lot of code to post but as an example:</p>
<pre><code>struct
{
WORD version;
BOOL upgrade;
time_t time1;
time_t time2;
} apparms;
File *fp;
fp = fopen(filePath, "r+b");
fread(&apparms, sizeof(apparms), 1, fp);
return Py_BuildValue("{s:i,s:l,s:l}",
"sysVersion",apparms.version,
"powerFailTime", apparms.time1,
"normKitExpDate", apparms.time2
);
</code></pre>
<p>Now on a 32 bit system this works great, but on a 64 bit my time_t sizes are different (32bit vs 64 bit longs).</p>
<p><hr /></p>
<p>Damn, you people are fast. </p>
<p>Patrick, I originally started using the struct package but found it just way to slow for my needs. Plus I was looking for an excuse to write a Python Extension.</p>
<p>I know this is a stupid question but what types do I need to watch out for?</p>
<p>Thanks.</p>
| 2 | 2008-09-25T18:59:41Z | 135,267 | <p>What's your code for reading the binary data? Make sure you're copying the data into properly-sized types like <code>int32_t</code> instead of just <code>int</code>.</p>
| 1 | 2008-09-25T19:02:00Z | [
"python",
"c",
"64bit"
] |
Reading 32bit Packed Binary Data On 64bit System | 135,246 | <p>I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way of doing this?</p>
<p><hr /></p>
<p>It would be a lot of code to post but as an example:</p>
<pre><code>struct
{
WORD version;
BOOL upgrade;
time_t time1;
time_t time2;
} apparms;
File *fp;
fp = fopen(filePath, "r+b");
fread(&apparms, sizeof(apparms), 1, fp);
return Py_BuildValue("{s:i,s:l,s:l}",
"sysVersion",apparms.version,
"powerFailTime", apparms.time1,
"normKitExpDate", apparms.time2
);
</code></pre>
<p>Now on a 32 bit system this works great, but on a 64 bit my time_t sizes are different (32bit vs 64 bit longs).</p>
<p><hr /></p>
<p>Damn, you people are fast. </p>
<p>Patrick, I originally started using the struct package but found it just way to slow for my needs. Plus I was looking for an excuse to write a Python Extension.</p>
<p>I know this is a stupid question but what types do I need to watch out for?</p>
<p>Thanks.</p>
| 2 | 2008-09-25T18:59:41Z | 135,271 | <p>Why aren't you using the <a href="http://docs.python.org/lib/module-struct.html" rel="nofollow">struct</a> package?</p>
| 0 | 2008-09-25T19:02:20Z | [
"python",
"c",
"64bit"
] |
Reading 32bit Packed Binary Data On 64bit System | 135,246 | <p>I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way of doing this?</p>
<p><hr /></p>
<p>It would be a lot of code to post but as an example:</p>
<pre><code>struct
{
WORD version;
BOOL upgrade;
time_t time1;
time_t time2;
} apparms;
File *fp;
fp = fopen(filePath, "r+b");
fread(&apparms, sizeof(apparms), 1, fp);
return Py_BuildValue("{s:i,s:l,s:l}",
"sysVersion",apparms.version,
"powerFailTime", apparms.time1,
"normKitExpDate", apparms.time2
);
</code></pre>
<p>Now on a 32 bit system this works great, but on a 64 bit my time_t sizes are different (32bit vs 64 bit longs).</p>
<p><hr /></p>
<p>Damn, you people are fast. </p>
<p>Patrick, I originally started using the struct package but found it just way to slow for my needs. Plus I was looking for an excuse to write a Python Extension.</p>
<p>I know this is a stupid question but what types do I need to watch out for?</p>
<p>Thanks.</p>
| 2 | 2008-09-25T18:59:41Z | 135,276 | <p>The 'struct' module should be able to do this, although alignment of structs in the middle of the data is always an issue. It's not very hard to get it right, however: find out (once) what boundary the structs-in-structs align to, then pad (manually, with the 'x' specifier) to that boundary. You can doublecheck your padding by comparing struct.calcsize() with your actual data. It's certainly easier than writing a C extension for it.</p>
<p>In order to keep using Py_BuildValue() like that, you have two options. You can determine the size of time_t at compiletime (in terms of fundamental types, so 'an int' or 'a long' or 'an ssize_t') and then use the right format character to Py_BuildValue -- 'i' for an int, 'l' for a long, 'n' for an ssize_t. Or you can use PyInt_FromSsize_t() manually, in which case the compiler does the upcasting for you, and then use the 'O' format characters to pass the result to Py_BuildValue.</p>
| 2 | 2008-09-25T19:03:02Z | [
"python",
"c",
"64bit"
] |
Reading 32bit Packed Binary Data On 64bit System | 135,246 | <p>I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way of doing this?</p>
<p><hr /></p>
<p>It would be a lot of code to post but as an example:</p>
<pre><code>struct
{
WORD version;
BOOL upgrade;
time_t time1;
time_t time2;
} apparms;
File *fp;
fp = fopen(filePath, "r+b");
fread(&apparms, sizeof(apparms), 1, fp);
return Py_BuildValue("{s:i,s:l,s:l}",
"sysVersion",apparms.version,
"powerFailTime", apparms.time1,
"normKitExpDate", apparms.time2
);
</code></pre>
<p>Now on a 32 bit system this works great, but on a 64 bit my time_t sizes are different (32bit vs 64 bit longs).</p>
<p><hr /></p>
<p>Damn, you people are fast. </p>
<p>Patrick, I originally started using the struct package but found it just way to slow for my needs. Plus I was looking for an excuse to write a Python Extension.</p>
<p>I know this is a stupid question but what types do I need to watch out for?</p>
<p>Thanks.</p>
| 2 | 2008-09-25T18:59:41Z | 135,311 | <p>Explicitly specify that your data types (e.g. integers) are 32-bit. Otherwise if you have two integers next to each other when you read them they will be read as one 64-bit integer.</p>
<p>When you are dealing with cross-platform issues, the two main things to watch out for are:</p>
<ol>
<li>Bitness. If your packed data is written with 32-bit ints, then all of your code must explicitly specify 32-bit ints when reading <em>and</em> writing.</li>
<li>Byte order. If you move your code from Intel chips to PPC or SPARC, your byte order will be wrong. You will have to import your data and then byte-flip it so that it matches up with the current architecture. Otherwise 12 (<code>0x0000000C</code>) will be read as 201326592 (<code>0x0C000000</code>).</li>
</ol>
<p>Hopefully this helps.</p>
| 3 | 2008-09-25T19:07:22Z | [
"python",
"c",
"64bit"
] |
Reading 32bit Packed Binary Data On 64bit System | 135,246 | <p>I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way of doing this?</p>
<p><hr /></p>
<p>It would be a lot of code to post but as an example:</p>
<pre><code>struct
{
WORD version;
BOOL upgrade;
time_t time1;
time_t time2;
} apparms;
File *fp;
fp = fopen(filePath, "r+b");
fread(&apparms, sizeof(apparms), 1, fp);
return Py_BuildValue("{s:i,s:l,s:l}",
"sysVersion",apparms.version,
"powerFailTime", apparms.time1,
"normKitExpDate", apparms.time2
);
</code></pre>
<p>Now on a 32 bit system this works great, but on a 64 bit my time_t sizes are different (32bit vs 64 bit longs).</p>
<p><hr /></p>
<p>Damn, you people are fast. </p>
<p>Patrick, I originally started using the struct package but found it just way to slow for my needs. Plus I was looking for an excuse to write a Python Extension.</p>
<p>I know this is a stupid question but what types do I need to watch out for?</p>
<p>Thanks.</p>
| 2 | 2008-09-25T18:59:41Z | 135,360 | <p>You need to make sure you're using architecture independent members for your struct. For instance an int may be 32 bits on one architecture and 64 bits on another. As others have suggested, use the <code>int32_t</code> style types instead. If your struct contains unaligned members, you may need to deal with padding added by the compiler too.</p>
<p>Another common problem with cross architecture data is endianness. Intel i386 architecture is little-endian, but if you're reading on a completely different machine (e.g. an Alpha or Sparc), you'll have to worry about this too.</p>
<p>The Python struct module deals with both these situations, using the prefix passed as part of the format string.</p>
<ul>
<li>@ - Use native size, endianness and alignment. i= sizeof(int), l= sizeof(long)</li>
<li>= - Use native endianness, but standard sizes and alignment (i=32 bits, l=64 bits)</li>
<li>< - Little-endian standard sizes/alignment</li>
<li>> - Big-endian standard sizes/alignment</li>
</ul>
<p>In general, if the data passes off your machine, you should nail down the endianness and the size / padding format to something specific â ie. use "<" or ">" as your format. If you want to handle this in your C extension, you may need to add some code to handle it.</p>
| 2 | 2008-09-25T19:15:52Z | [
"python",
"c",
"64bit"
] |
How can I closely achieve ?: from C++/C# in Python? | 135,303 | <p>In C# I could easily write the following:</p>
<pre><code>string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
</code></pre>
<p>Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?</p>
| 8 | 2008-09-25T19:06:03Z | 135,318 | <p>In Python 2.5, there is</p>
<pre><code>A if C else B
</code></pre>
<p>which behaves a lot like ?: in C. However, it's frowned upon for two reasons: readability, and the fact that there's usually a simpler way to approach the problem. For instance, in your case:</p>
<pre><code>stringValue = otherString or defaultString
</code></pre>
| 22 | 2008-09-25T19:08:31Z | [
"python",
"syntax",
"ternary-operator",
"syntax-rules"
] |
How can I closely achieve ?: from C++/C# in Python? | 135,303 | <p>In C# I could easily write the following:</p>
<pre><code>string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
</code></pre>
<p>Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?</p>
| 8 | 2008-09-25T19:06:03Z | 135,342 | <p>It's never a bad thing to write readable, expressive code.</p>
<pre><code>if otherString:
stringValue = otherString
else:
stringValue = defaultString
</code></pre>
<p>This type of code is longer and more expressive, but also more readable and less likely to get tripped over or mis-edited down the road. Don't be afraid to write expressively - readable code should be a goal, not a byproduct.</p>
| 1 | 2008-09-25T19:11:18Z | [
"python",
"syntax",
"ternary-operator",
"syntax-rules"
] |
How can I closely achieve ?: from C++/C# in Python? | 135,303 | <p>In C# I could easily write the following:</p>
<pre><code>string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
</code></pre>
<p>Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?</p>
| 8 | 2008-09-25T19:06:03Z | 135,354 | <p>You can take advantage of the fact that logical expressions return their value, and not just true or false status. For example, you can always use:</p>
<pre><code>result = question and firstanswer or secondanswer
</code></pre>
<p>With the caveat that it doesn't work like the ternary operator if firstanswer is false. This is because question is evaluated first, assuming it's true firstanswer is returned unless firstanswer is false, so this usage fails to act like the ternary operator. If you know the values, however, there is usually no problem. An example would be:</p>
<pre><code>result = choice == 7 and "Seven" or "Another Choice"
</code></pre>
| -1 | 2008-09-25T19:14:05Z | [
"python",
"syntax",
"ternary-operator",
"syntax-rules"
] |
How can I closely achieve ?: from C++/C# in Python? | 135,303 | <p>In C# I could easily write the following:</p>
<pre><code>string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
</code></pre>
<p>Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?</p>
| 8 | 2008-09-25T19:06:03Z | 135,450 | <p>@<a href="#135342">Dan</a></p>
<blockquote>
<pre><code>if otherString:
stringValue = otherString
else:
stringValue = defaultString
</code></pre>
<p>This type of code is longer and more expressive, but also more readable</p>
</blockquote>
<p>Well yes, it's longer. Not so sure about âmore expressiveâ and âmore readableâ. At the very least, your claim is disputable. I would even go as far as saying it's downright wrong, for two reasons.</p>
<p>First, your code emphasizes the decision-making (rather extremely). Onthe other hand, the conditional operator emphasizes something else, namely the value (resp. the assignment of said value). And this is <em>exactly</em> what the writer of this code wants. The decision-making is really rather a by-product of the code. The important part here is the assignment operation. Your code hides this assignment in a lot of syntactic noise: the branching.</p>
<p>Your code is less expressive because it shifts the emphasis from the important part.</p>
<p>Even then your code would probably trump some obscure ASCII art like <code>?:</code>. An inline-<code>if</code> would be preferable. Personally, I don't like the variant introduced with Python 2.5 because it's backwards. I would prefer something that reads in the same flow (direction) as the C ternary operator but uses words instead of ASCII characters:</p>
<pre><code>C = if cond then A else B
</code></pre>
<p>This wins hands down.</p>
<p>C and C# unfortunately don't have such an expressive statement. But (and this is the second argument), the ternary conditional operator of C languages is so long established that it has become an idiom in itself. The ternary operator is as much part of the language as the âconventionalâ <code>if</code> statement. Because it's an idiom, anybody who knows the language immediately reads this code right. Furthermore, it's an extremely short, concise way of expressing these semantics. In fact, it's the shortest imaginable way. It's extremely expressive because it doesn't obscure the essence with needless noise.</p>
<p>Finally, Jeff Atwood has written the perfect conclusion to this: <a href="http://www.codinghorror.com/blog/archives/000878.html"><strong>The best code is no code at all</strong></a>.</p>
| 5 | 2008-09-25T19:27:21Z | [
"python",
"syntax",
"ternary-operator",
"syntax-rules"
] |
How can I closely achieve ?: from C++/C# in Python? | 135,303 | <p>In C# I could easily write the following:</p>
<pre><code>string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
</code></pre>
<p>Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?</p>
| 8 | 2008-09-25T19:06:03Z | 135,471 | <p>By the way, j0rd4n, you don't (<em>please</em> don't!) write code like this in C#. Apart from the fact that the <code>IsDefaultOrNull</code> is actually called <code>IsNullOrEmpty</code>, this is pure code bloat. C# offers the coalesce operator for situations like these:</p>
<pre><code>string stringValue = otherString ?? defaultString;
</code></pre>
<p>It's true that this only works if <code>otherString</code> is <code>null</code> (rather than empty) but if this can be ensured beforehand (and often it can) it makes the code much more readable.</p>
| 0 | 2008-09-25T19:32:01Z | [
"python",
"syntax",
"ternary-operator",
"syntax-rules"
] |
How can I closely achieve ?: from C++/C# in Python? | 135,303 | <p>In C# I could easily write the following:</p>
<pre><code>string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
</code></pre>
<p>Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?</p>
| 8 | 2008-09-25T19:06:03Z | 135,889 | <p>If you used ruby, you could write</p>
<pre><code>stringValue = otherString.blank? ? defaultString : otherString;
</code></pre>
<p>the built in <code>blank?</code> method means null or empty.<br />
Come over to the dark side...</p>
| -1 | 2008-09-25T20:37:53Z | [
"python",
"syntax",
"ternary-operator",
"syntax-rules"
] |
How can I closely achieve ?: from C++/C# in Python? | 135,303 | <p>In C# I could easily write the following:</p>
<pre><code>string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
</code></pre>
<p>Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?</p>
| 8 | 2008-09-25T19:06:03Z | 135,907 | <p>I also discovered that just using the "or" operator does pretty well. For instance:</p>
<pre><code>finalString = get_override() or defaultString
</code></pre>
<p>If *get_override()* returns "" or None, it will always use <em>defaultString</em>.</p>
| 0 | 2008-09-25T20:40:32Z | [
"python",
"syntax",
"ternary-operator",
"syntax-rules"
] |
How can I closely achieve ?: from C++/C# in Python? | 135,303 | <p>In C# I could easily write the following:</p>
<pre><code>string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
</code></pre>
<p>Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?</p>
| 8 | 2008-09-25T19:06:03Z | 812,425 | <p><a href="http://www.diveintopython.net/power_of_introspection/and_or.html#d0e9975" rel="nofollow">Chapter 4 of diveintopython.net</a> has the answer. It's called the and-or trick in Python.</p>
| 0 | 2009-05-01T17:44:59Z | [
"python",
"syntax",
"ternary-operator",
"syntax-rules"
] |
How can I closely achieve ?: from C++/C# in Python? | 135,303 | <p>In C# I could easily write the following:</p>
<pre><code>string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
</code></pre>
<p>Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?</p>
| 8 | 2008-09-25T19:06:03Z | 1,601,685 | <p>There are a few duplicates of this question, e.g.</p>
<ul>
<li><a href="http://stackoverflow.com/questions/394809/python-ternary-operator">http://stackoverflow.com/questions/394809/python-ternary-operator</a></li>
<li><a href="http://stackoverflow.com/questions/643983/whats-the-best-way-to-replace-the-ternary-operator-in-python">http://stackoverflow.com/questions/643983/whats-the-best-way-to-replace-the-ternary-operator-in-python</a></li>
</ul>
<p>In essence, in a general setting pre-2.5 code should use this:</p>
<pre><code> (condExp and [thenExp] or [elseExp])[0]
</code></pre>
<p>(given condExp, thenExp and elseExp are arbitrary expressions), as it avoids wrong results if thenExp evaluates to boolean False, while maintaining short-circuit evaluation.</p>
| 1 | 2009-10-21T15:37:05Z | [
"python",
"syntax",
"ternary-operator",
"syntax-rules"
] |
How many bytes per element are there in a Python list (tuple)? | 135,664 | <p>For example, how much memory is required to store a list of one million (32-bit) integers?</p>
<pre><code>alist = range(1000000) # or list(range(1000000)) in Python 3.0
</code></pre>
| 13 | 2008-09-25T20:04:09Z | 135,718 | <p>"It depends." Python allocates space for lists in such a way as to achieve <a href="http://effbot.org/zone/python-list.htm">amortized constant time</a> for appending elements to the list.</p>
<p>In practice, what this means with the current implementation is... the list always has space allocated for a power-of-two number of elements. So range(1000000) will actually allocate a list big enough to hold 2^20 elements (~ 1.045 million).</p>
<p>This is only the space required to store the list structure itself (which is an array of pointers to the Python objects for each element). A 32-bit system will require 4 bytes per element, a 64-bit system will use 8 bytes per element.</p>
<p>Furthermore, you need space to store the actual elements. This varies widely. For small integers (-5 to 256 currently), no additional space is needed, but for larger numbers Python allocates a new object for each integer, which takes 10-100 bytes and tends to fragment memory.</p>
<p>Bottom line: <b>it's complicated</b> and Python lists are <b>not</b> a good way to store large homogeneous data structures. For that, use the <code>array</code> module or, if you need to do vectorized math, use NumPy.</p>
<p>PS- Tuples, unlike lists, are <i>not designed</i> to have elements progressively appended to them. I don't know how the allocator works, but don't even think about using it for large data structures :-)</p>
| 23 | 2008-09-25T20:10:53Z | [
"python",
"memory-management"
] |
How many bytes per element are there in a Python list (tuple)? | 135,664 | <p>For example, how much memory is required to store a list of one million (32-bit) integers?</p>
<pre><code>alist = range(1000000) # or list(range(1000000)) in Python 3.0
</code></pre>
| 13 | 2008-09-25T20:04:09Z | 135,748 | <p>This is implementation specific, I'm pretty sure. Certainly it depends on the internal representation of integers - you can't assume they'll be stored as 32-bit since Python gives you arbitrarily large integers so perhaps small ints are stored more compactly. </p>
<p>On my Python (2.5.1 on Fedora 9 on core 2 duo) the VmSize before allocation is 6896kB, after is 22684kB. After one more million element assignment, VmSize goes to 38340kB. This very grossly indicates around 16000kB for 1000000 integers, which is around 16 bytes per integer. That suggests a <em>lot</em> of overhead for the list. I'd take these numbers with a large pinch of salt.</p>
| 2 | 2008-09-25T20:15:48Z | [
"python",
"memory-management"
] |
How many bytes per element are there in a Python list (tuple)? | 135,664 | <p>For example, how much memory is required to store a list of one million (32-bit) integers?</p>
<pre><code>alist = range(1000000) # or list(range(1000000)) in Python 3.0
</code></pre>
| 13 | 2008-09-25T20:04:09Z | 136,083 | <p>Useful links:</p>
<p><a href="http://bytes.com/forum/thread757255.html">How to get memory size/usage of python object</a></p>
<p><a href="http://mail.python.org/pipermail/python-list/2002-March/135223.html">Memory sizes of python objects?</a></p>
<p><a href="http://groups.google.com/group/comp.lang.python/msg/b9afcfc2e1de5b05">if you put data into dictionary, how do we calculate the data size?</a> </p>
<p>However they don't give a definitive answer. The way to go:</p>
<ol>
<li><p>Measure memory consumed by Python interpreter with/without the list (use OS tools).</p></li>
<li><p>Use a third-party extension module which defines some sort of sizeof(PyObject).</p></li>
</ol>
<p><strong>Update</strong>:</p>
<p><a href="http://code.activestate.com/recipes/546530/">Recipe 546530: Size of Python objects (revised)</a></p>
<pre><code>import asizeof
N = 1000000
print asizeof.asizeof(range(N)) / N
# -> 20 (python 2.5, WinXP, 32-bit Linux)
# -> 33 (64-bit Linux)
</code></pre>
| 13 | 2008-09-25T21:00:40Z | [
"python",
"memory-management"
] |
How many bytes per element are there in a Python list (tuple)? | 135,664 | <p>For example, how much memory is required to store a list of one million (32-bit) integers?</p>
<pre><code>alist = range(1000000) # or list(range(1000000)) in Python 3.0
</code></pre>
| 13 | 2008-09-25T20:04:09Z | 139,393 | <p><strong>Addressing "tuple" part of the question</strong></p>
<p>Declaration of CPython's PyTuple in a typical build configuration boils down to this:</p>
<pre><code>struct PyTuple {
size_t refcount; // tuple's reference count
typeobject *type; // tuple type object
size_t n_items; // number of items in tuple
PyObject *items[1]; // contains space for n_items elements
};
</code></pre>
<p>Size of PyTuple instance is fixed during it's construction and cannot be changed afterwards. The number of bytes occupied by PyTuple can be calculated as</p>
<blockquote>
<p><code>sizeof(size_t) x 2 + sizeof(void*) x (n_items + 1)</code>.</p>
</blockquote>
<p>This gives <em>shallow</em> size of tuple. To get <em>full</em> size you also need to add total number of bytes consumed by object graph rooted in <code>PyTuple::items[]</code> array. </p>
<p>It's worth noting that tuple construction routines make sure that only single instance of empty tuple is ever created (singleton).</p>
<p>References:
<a href="http://svn.python.org/view/python/tags/r252/Include/Python.h?rev=60915&view=markup">Python.h</a>,
<a href="http://svn.python.org/view/python/tags/r252/Include/object.h?rev=60915&view=markup">object.h</a>,
<a href="http://svn.python.org/view/python/tags/r252/Include/tupleobject.h?rev=60915&view=markup">tupleobject.h</a>,
<a href="http://svn.python.org/view/python/tags/r252/Objects/tupleobject.c?rev=60915&view=markup">tupleobject.c</a></p>
| 6 | 2008-09-26T13:08:27Z | [
"python",
"memory-management"
] |
How many bytes per element are there in a Python list (tuple)? | 135,664 | <p>For example, how much memory is required to store a list of one million (32-bit) integers?</p>
<pre><code>alist = range(1000000) # or list(range(1000000)) in Python 3.0
</code></pre>
| 13 | 2008-09-25T20:04:09Z | 159,844 | <blockquote>
<p>A new function, <code>getsizeof()</code>, takes a
Python object and returns the amount
of memory used by the object, measured
in bytes. Built-in objects return
correct results; third-party
extensions may not, but can define a
<code>__sizeof__()</code> method to return the objectâs size.</p>
</blockquote>
<pre><code>kveretennicov@nosignal:~/py/r26rc2$ ./python
Python 2.6rc2 (r26rc2:66712, Sep 2 2008, 13:11:55)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
>>> import sys
>>> sys.getsizeof(range(1000000))
4000032
>>> sys.getsizeof(tuple(range(1000000)))
4000024
</code></pre>
<p>Obviously returned numbers don't include memory consumed by contained objects (sys.getsizeof(1) == 12).</p>
| 3 | 2008-10-01T21:28:21Z | [
"python",
"memory-management"
] |
How many bytes per element are there in a Python list (tuple)? | 135,664 | <p>For example, how much memory is required to store a list of one million (32-bit) integers?</p>
<pre><code>alist = range(1000000) # or list(range(1000000)) in Python 3.0
</code></pre>
| 13 | 2008-09-25T20:04:09Z | 159,941 | <p>I'm wary of why you're asking. Are you trying to figure out how much memory you'll need for a given implementation? Say, you're going to read 10,000,000 widgets and want to know how much RAM it will suck?</p>
<p>If that's the case, rather than trying to figure out how much RAM each widget takes, figure out how much RAM, say, 10,000 widgets takes and multiply up to get your actual size.</p>
| 0 | 2008-10-01T21:55:37Z | [
"python",
"memory-management"
] |
Python: SWIG vs ctypes | 135,834 | <p>In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). <br><br>What are the performance metrics of the two?</p>
| 45 | 2008-09-25T20:29:27Z | 135,873 | <p>CTypes is very cool and much easier than SWIG, but it has the drawback that poorly or malevolently-written python code can actually crash the python process. You should also consider <a href="http://www.boost.org/doc/libs/release/libs/python/doc/">boost</a> python. IMHO it's actually easier than swig while giving you more control over the final python interface. If you are using C++ anyway, you also don't add any other languages to your mix.</p>
| 12 | 2008-09-25T20:35:17Z | [
"python",
"swig",
"ctypes",
"multilanguage",
"ffi"
] |
Python: SWIG vs ctypes | 135,834 | <p>In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). <br><br>What are the performance metrics of the two?</p>
| 45 | 2008-09-25T20:29:27Z | 135,966 | <p>SWIG generates (rather ugly) C or C++ code. It is straightforward to use for simple functions (things that can be translated directly) and reasonably easy to use for more complex functions (such as functions with output parameters that need an extra translation step to represent in Python.) For more powerful interfacing you often need to write bits of C as part of the interface file. For anything but simple use you will need to know about CPython and how it represents objects -- not hard, but something to keep in mind.</p>
<p>ctypes allows you to directly access C functions, structures and other data, and load arbitrary shared libraries. You do not need to write any C for this, but you do need to understand how C works. It is, you could argue, the flip side of SWIG: it doesn't generate code and it doesn't require a compiler at runtime, but for anything but simple use it does require that you understand how things like C datatypes, casting, memory management and alignment work. You also need to manually or automatically translate C structs, unions and arrays into the equivalent ctypes datastructure, including the right memory layout.</p>
<p>It is likely that in pure execution, SWIG is faster than ctypes -- because the management around the actual work is done in C at compiletime rather than in Python at runtime. However, unless you interface a lot of different C functions but each only a few times, it's unlikely the overhead will be really noticeable.</p>
<p>In development time, ctypes has a much lower startup cost: you don't have to learn about interface files, you don't have to generate .c files and compile them, you don't have to check out and silence warnings. You can just jump in and start using a single C function with minimal effort, then expand it to more. And you get to test and try things out directly in the Python interpreter. Wrapping lots of code is somewhat tedious, although there are attempts to make that simpler (like ctypes-configure.)</p>
<p>SWIG, on the other hand, can be used to generate wrappers for multiple languages (barring language-specific details that need filling in, like the custom C code I mentioned above.) When wrapping lots and lots of code that SWIG can handle with little help, the code generation can also be a lot simpler to set up than the ctypes equivalents.</p>
| 54 | 2008-09-25T20:47:28Z | [
"python",
"swig",
"ctypes",
"multilanguage",
"ffi"
] |
Python: SWIG vs ctypes | 135,834 | <p>In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). <br><br>What are the performance metrics of the two?</p>
| 45 | 2008-09-25T20:29:27Z | 136,019 | <p>You can also use <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">Pyrex</a>, which can act as glue between high-level Python code and low-level C code. <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a> is written in Pyrex, for instance.</p>
| 8 | 2008-09-25T20:54:22Z | [
"python",
"swig",
"ctypes",
"multilanguage",
"ffi"
] |
Python: SWIG vs ctypes | 135,834 | <p>In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). <br><br>What are the performance metrics of the two?</p>
| 45 | 2008-09-25T20:29:27Z | 136,232 | <p>ctypes is great, but does not handle C++ classes. I've also found ctypes is about 10% slower than a direct C binding, but that will highly depend on what you are calling.</p>
<p>If you are going to go with ctypes, definitely check out the Pyglet and Pyopengl projects, that have massive examples of ctype bindings.</p>
| 6 | 2008-09-25T21:22:15Z | [
"python",
"swig",
"ctypes",
"multilanguage",
"ffi"
] |
Python: SWIG vs ctypes | 135,834 | <p>In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). <br><br>What are the performance metrics of the two?</p>
| 45 | 2008-09-25T20:29:27Z | 137,827 | <p>I'm going to be contrarian and suggest that, if you can, you should write your extension library using the <a href="http://docs.python.org/api/" rel="nofollow">standard Python API</a>. It's really well-integrated from both a C and Python perspective... if you have any experience with the Perl API, you will find it a <em>very</em> pleasant surprise.</p>
<p>Ctypes is nice too, but as others have said, it doesn't do C++.</p>
<p>How big is the library you're trying to wrap? How quickly does the codebase change? Any other maintenance issues? These will all probably affect the choice of the best way to write the Python bindings.</p>
| 7 | 2008-09-26T04:49:05Z | [
"python",
"swig",
"ctypes",
"multilanguage",
"ffi"
] |
Python: SWIG vs ctypes | 135,834 | <p>In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). <br><br>What are the performance metrics of the two?</p>
| 45 | 2008-09-25T20:29:27Z | 463,848 | <p>In my experience, ctypes does have a big disadvantage: when something goes wrong (and it invariably will for any complex interfaces), it's a hell to debug.</p>
<p>The problem is that a big part of your stack is obscured by ctypes/ffi magic and there is no easy way to determine how did you get to a particular point and why parameter values are what they are..</p>
| 9 | 2009-01-21T01:36:28Z | [
"python",
"swig",
"ctypes",
"multilanguage",
"ffi"
] |
Python: SWIG vs ctypes | 135,834 | <p>In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). <br><br>What are the performance metrics of the two?</p>
| 45 | 2008-09-25T20:29:27Z | 4,892,651 | <p>I have a rich experience of using swig. SWIG claims that it is rapid solution for wrapping things. But in the real life...</p>
<hr>
<h1>Cons:</h1>
<p>SWIG is developed to be general, for everyone and for 20+ languages. Generally it leads to drawbacks:<br>
- needs configuration (SWIG .i templates), sometimes it is tricky,<br>
- lack of treatment of some special cases (see python properties further),<br>
- lack of the performance for some languages. </p>
<p><em>Python cons:</em> </p>
<p>1) <strong>Code style inconsistancy</strong>. C++ and python have very different code styles (that is obvious, certainly), the possibilities of swig of making target code more pythonish is very limited. As example, it is butt-heart to create properties from getters and setters. See <a href="http://stackoverflow.com/questions/1183716/python-properties-swig">this q&a</a></p>
<p>2) <strong>Lack of broad community</strong>. Swig have some good documentation. But if one caught something that is not in the documentation, there is no information at all. No blogs nor googling helps. So one have to heavily dig SWIG generated code in such cases... That is terrible, I could say... </p>
<h1>Procs:</h1>
<ul>
<li><p>In simple cases it is really rapid, easy and straight forward</p></li>
<li><p>If you produced swig interface files once, you can wrap this C++ code to ANY of other 20+ languages (!!!). </p></li>
<li><p>One big concern about SWIG is a performance. Since version 2.04 SWIG includes '-builtin' flag wich makes SWIG even faster than other automated ways of wrapping. At least <a href="http://stackoverflow.com/questions/456884/extending-python-to-swig-not-to-swig-or-cython">some benchmarks</a> shows this.</p></li>
</ul>
<hr>
<h1>When to USE SWIG?</h1>
<p>So I concluded for myself two cases when the swig is good to use:</p>
<p>2) If one needs to wrap C++ code <strong>for several languages</strong>. Or if potentially there could be a time when one needs to distribute the code for several languages. Using SWIG is reliable in this case. </p>
<p>1) If one needs to <strong>rapidly</strong> wrap <strong>just several</strong> functions from some C++ library for end use.</p>
<hr>
<h1>Live experience</h1>
<p><strong>Update</strong> :<br>
It is a year and half passed as we did a conversion of our library by using SWIG.</p>
<p>First we made a python version.There were several moments when we experienced troubles with SWIG - it is true. But right now we expanded our library to Java and .NET. So we have 3 languages with 1 SWIG. And I could say that <strong>SWIG rocks</strong> in terms of saving a LOT of time. </p>
<p><strong>Update 2</strong>:<br>
It is two years as we use SWIG for this library. SWIG is integrated in our build system. Recently we had major API change of C++ library. SWIG worked perfectly. The only thing we needed to do is to add several %rename to .i files so our <code>CppCamelStyleFunctions()</code> now <code>looks_more_pythonish</code> in python. First I was concerned about some problems that could arise, but nothing went wrong. It was amazing. Just several edits and everything distributed in 3 languages. Now I am confident that it was a good solution to use SWIG in our case. </p>
<p><strong>Update 3</strong>:<br>
It is 3+ years we use SWIG for our library. <strong>Major change</strong>: python part was totally rewritten in pure python. The reason is that python is used for the majority of applications of our library now. Even if pure python version works slower than C++ wrapping, it is more convenient for users to work with pure python, not struggling with native libraries. </p>
<p>SWIG is still used for .NET and Java versions.</p>
<p>The Main question here "Would we use SWIG for python, if we started the project from the beginning?". We would! SWIG allowed us to rapidly distribute our product to many languages. It worked for a period of time which gave us the opportunity for better understanding our users requirements. </p>
| 69 | 2011-02-03T22:47:25Z | [
"python",
"swig",
"ctypes",
"multilanguage",
"ffi"
] |
Python: SWIG vs ctypes | 135,834 | <p>In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). <br><br>What are the performance metrics of the two?</p>
| 45 | 2008-09-25T20:29:27Z | 5,113,986 | <p>Something to keep in mind is that SWIG targets only the CPython implementation. Since ctypes is also supported by the PyPy and IronPython implementations it may be worth writing your modules with ctypes for compatibility with the wider Python ecosystem.</p>
| 3 | 2011-02-25T05:35:20Z | [
"python",
"swig",
"ctypes",
"multilanguage",
"ffi"
] |
Python: SWIG vs ctypes | 135,834 | <p>In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). <br><br>What are the performance metrics of the two?</p>
| 45 | 2008-09-25T20:29:27Z | 6,936,927 | <p>Just wanted to add a few more considerations that I didn't see mentioned yet.
[EDIT: Ooops, didn't see Mike Steder's answer]</p>
<p>If you want to try using a non Cpython implementation (like PyPy, IronPython or Jython), then ctypes is about the only way to go. PyPy doesn't allow writing C-extensions, so that rules out pyrex/cython and Boost.python. For the same reason, ctypes is the only mechanism that will work for IronPython and (eventually, once they get it all working) jython.</p>
<p>As someone else mentioned, no compilation is required. This means that if a new version of the .dll or .so comes out, you can just drop it in, and load that new version. As long as the none of the interfaces changed, it's a drop in replacement. </p>
| 5 | 2011-08-04T06:13:02Z | [
"python",
"swig",
"ctypes",
"multilanguage",
"ffi"
] |
Python: SWIG vs ctypes | 135,834 | <p>In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). <br><br>What are the performance metrics of the two?</p>
| 45 | 2008-09-25T20:29:27Z | 16,795,658 | <p>I have found SWIG to be be a little bloated in its approach (in general, not just Python) and difficult to implement without having to cross the sore point of writing Python code with an explicit mindset to be SWIG friendly, rather than writing clean well-written Python code. It is, IMHO, a much more straightforward process to write C bindings to C++ (if using C++) and then use ctypes to interface to any C layer.</p>
<p>If the library you are interfacing to has a C interface as part of the library, another advantage of ctypes is that you don't have to compile a separate python-binding library to access third-party libraries. This is particularly nice in formulating a pure-python solution that avoids cross-platform compilation issues (for those third-party libs offered on disparate platforms). Having to embed compiled code into a package you wish to deploy on something like PyPi in a cross-platform friendly way is a pain; one of my most irritating points about Python packages using SWIG or underlying explicit C code is their general inavailability cross-platform. So consider this if you are working with cross-platform available third party libraries and developing a python solution around them.</p>
<p>As a real-world example, consider PyGTK. This (I believe) uses SWIG to generate C code to interface to the GTK C calls. I used this for the briefest time only to find it a real pain to set up and use, with quirky odd errors if you didn't do things in the correct order on setup and just in general. It was such a frustrating experience, and when I looked at the interace definitions provided by GTK on the web I realized what a simple excercise it would be to write a translator of those interface to python ctypes interface. A project called PyGGI was born, and in ONE day I was able to rewrite PyGTK to be a much more functiona and useful product that matches cleanly to the GTK C-object-oriented interfaces. And it required no compilation of C-code making it cross-platform friendly. (I was actually after interfacing to webkitgtk, which isn't so cross-platform). I can also easily deploy PyGGI to any platform supporting GTK. </p>
| -1 | 2013-05-28T15:17:46Z | [
"python",
"swig",
"ctypes",
"multilanguage",
"ffi"
] |
Python web development - with or without a framework | 136,069 | <p>I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface. </p>
<p>I did not use a framework in the PHP version, but being new to Python, I am wondering if it would be advantageous to use something like Django or at the very least Genshi. The caveat is I do not want my application distribution to be overwhelmed by the framework parts I would need to distribute with the application. </p>
<p>Is using only the cgi import in Python the best way to go in this circumstance? I would tend to think a framework is too much overhead, but perhaps I'm not thinking in a very "python" way about them. What suggestions do you have in this scenario?</p>
| 18 | 2008-09-25T20:59:49Z | 136,152 | <p>Depends on the size of the project. If you had only a few previous php-scripts which called your stand alone application then I'd probably go for a cgi-app.</p>
<p>If you have use for databases, url rewriting, templating, user management and such, then using a framework is a good idea.</p>
<p>And of course, before you port it, consider if it's worth it just to switch the language or if there are specific Python features you need.</p>
<p>Good luck!</p>
| 4 | 2008-09-25T21:07:44Z | [
"python",
"frameworks"
] |
Python web development - with or without a framework | 136,069 | <p>I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface. </p>
<p>I did not use a framework in the PHP version, but being new to Python, I am wondering if it would be advantageous to use something like Django or at the very least Genshi. The caveat is I do not want my application distribution to be overwhelmed by the framework parts I would need to distribute with the application. </p>
<p>Is using only the cgi import in Python the best way to go in this circumstance? I would tend to think a framework is too much overhead, but perhaps I'm not thinking in a very "python" way about them. What suggestions do you have in this scenario?</p>
| 18 | 2008-09-25T20:59:49Z | 136,166 | <p>It depends on the way you are going to distribute your application.<br />
If it will only be used internally, go for django. It's a joy to work with it.
However, django really falls short at the distribution-task; django-applications are a pain to set up.</p>
| 0 | 2008-09-25T21:11:08Z | [
"python",
"frameworks"
] |
Python web development - with or without a framework | 136,069 | <p>I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface. </p>
<p>I did not use a framework in the PHP version, but being new to Python, I am wondering if it would be advantageous to use something like Django or at the very least Genshi. The caveat is I do not want my application distribution to be overwhelmed by the framework parts I would need to distribute with the application. </p>
<p>Is using only the cgi import in Python the best way to go in this circumstance? I would tend to think a framework is too much overhead, but perhaps I'm not thinking in a very "python" way about them. What suggestions do you have in this scenario?</p>
| 18 | 2008-09-25T20:59:49Z | 136,188 | <p>The command-line Python, IMO, definitely comes first. Get that to work, since that's the core of what you're doing.</p>
<p>The issue is that using a web framework's ORM from a command line application isn't obvious. Django provides specific instructions for using their ORM from a command-line app. Those are annoying at first, but I think they're a life-saver in the long run. I use it heavily for giant uploads of customer-supplied files.</p>
<p>Don't use bare CGI. It's not impossible, but too many things can go wrong, and they've all been solved by the frameworks. Why reinvent something? Just use someone else's code.</p>
<p>Frameworks involve learning, but no real "overhead". They're not slow. They're code you don't have to write or debug.</p>
<ol>
<li><p>Learn some Python.</p></li>
<li><p>Do the <a href="http://docs.djangoproject.com/en/dev/">Django</a> tutorial.</p></li>
<li><p>Start to build a web app.</p>
<p>a. Start a Django project. Build a small application in that project.</p>
<p>b. Build your new model using the Django ORM. Create a Django unit test for the model. Be sure that it works. You'll be able to use the default admin pages and do a lot of playing around. Just don't build the <em>entire</em> web site yet.</p></li>
<li><p>Get your command-line app to work using Django ORM. Essentially, you have to finesse the settings file for this app to work nicely. See the <a href="http://docs.djangoproject.com/en/dev/topics/settings/#topics-settings">settings/configuration</a> section. </p></li>
<li><p>Once you've got your command line and the default admin running, you can finish
the web app.</p></li>
</ol>
<p>Here's the golden rule of frameworks: <strong>It's code you don't have to write, debug or maintain.</strong> Use them.</p>
| 13 | 2008-09-25T21:14:33Z | [
"python",
"frameworks"
] |
Python web development - with or without a framework | 136,069 | <p>I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface. </p>
<p>I did not use a framework in the PHP version, but being new to Python, I am wondering if it would be advantageous to use something like Django or at the very least Genshi. The caveat is I do not want my application distribution to be overwhelmed by the framework parts I would need to distribute with the application. </p>
<p>Is using only the cgi import in Python the best way to go in this circumstance? I would tend to think a framework is too much overhead, but perhaps I'm not thinking in a very "python" way about them. What suggestions do you have in this scenario?</p>
| 18 | 2008-09-25T20:59:49Z | 136,234 | <p>I recently ported a PHP app to Python using <a href="http://webpy.org/" rel="nofollow">web.py</a>. As frameworks go it is extremely lightweight with minimal dependencies, and it tends to stay out of your way, so it might be the compromise you're looking for. </p>
<p>It all depends on your initial application though, because with a large application the advantages of having a full-featured framework handling the plumbing tend to outweigh the disadvantages involved in having to drag around all the framework code.</p>
| 3 | 2008-09-25T21:22:30Z | [
"python",
"frameworks"
] |
Python web development - with or without a framework | 136,069 | <p>I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface. </p>
<p>I did not use a framework in the PHP version, but being new to Python, I am wondering if it would be advantageous to use something like Django or at the very least Genshi. The caveat is I do not want my application distribution to be overwhelmed by the framework parts I would need to distribute with the application. </p>
<p>Is using only the cgi import in Python the best way to go in this circumstance? I would tend to think a framework is too much overhead, but perhaps I'm not thinking in a very "python" way about them. What suggestions do you have in this scenario?</p>
| 18 | 2008-09-25T20:59:49Z | 136,683 | <p>Django makes it possible to whip out a website rapidly, that's for sure. You don't need to be a Python master to use it, and since it's very pythonic in it's design, and there is not really any "magic" going on, it will help you learn Python along the way.</p>
<p>Start with the examples, check out some django screencasts from TwiD and you'll be on your way.</p>
<p>Start slow, tweaking the admin, and playing with it via shell is the way to start. Once you have a handle on the ORM and get how things work, start building the real stuff!</p>
<p>The framework isn't going to cause any performance problems, like S. Lott said, it's code you don't have to maintain, and that's the best kind.</p>
| 2 | 2008-09-25T22:47:33Z | [
"python",
"frameworks"
] |
Python web development - with or without a framework | 136,069 | <p>I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface. </p>
<p>I did not use a framework in the PHP version, but being new to Python, I am wondering if it would be advantageous to use something like Django or at the very least Genshi. The caveat is I do not want my application distribution to be overwhelmed by the framework parts I would need to distribute with the application. </p>
<p>Is using only the cgi import in Python the best way to go in this circumstance? I would tend to think a framework is too much overhead, but perhaps I'm not thinking in a very "python" way about them. What suggestions do you have in this scenario?</p>
| 18 | 2008-09-25T20:59:49Z | 136,804 | <p>You might consider using something like <a href="http://webpy.org/">web.py</a> which would be easy to distribute (since it's small) and it would also be easy to adapt your other tools to it since it doesn't require you to submit to the framework so much like Django does. </p>
<p>Be forewarned, however, it's not the most loved framework in the Python community, but it might be just the thing for you. You might also check out <a href="http://mdp.cti.depaul.edu/">web2py</a>, but I know less about that.</p>
| 10 | 2008-09-25T23:17:24Z | [
"python",
"frameworks"
] |
Python web development - with or without a framework | 136,069 | <p>I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface. </p>
<p>I did not use a framework in the PHP version, but being new to Python, I am wondering if it would be advantageous to use something like Django or at the very least Genshi. The caveat is I do not want my application distribution to be overwhelmed by the framework parts I would need to distribute with the application. </p>
<p>Is using only the cgi import in Python the best way to go in this circumstance? I would tend to think a framework is too much overhead, but perhaps I'm not thinking in a very "python" way about them. What suggestions do you have in this scenario?</p>
| 18 | 2008-09-25T20:59:49Z | 138,888 | <p>Go for a framework. Basic stuffs like session handling are a nightmare if you don't use a one because Python is not web specialized like PHP.</p>
<p>If you think django is too much, you can try a lighter one like the very small but still handy web.py.</p>
| 2 | 2008-09-26T11:31:45Z | [
"python",
"frameworks"
] |
Python web development - with or without a framework | 136,069 | <p>I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface. </p>
<p>I did not use a framework in the PHP version, but being new to Python, I am wondering if it would be advantageous to use something like Django or at the very least Genshi. The caveat is I do not want my application distribution to be overwhelmed by the framework parts I would need to distribute with the application. </p>
<p>Is using only the cgi import in Python the best way to go in this circumstance? I would tend to think a framework is too much overhead, but perhaps I'm not thinking in a very "python" way about them. What suggestions do you have in this scenario?</p>
| 18 | 2008-09-25T20:59:49Z | 1,436,495 | <p>For the love of pete, use a framework! There are literally dozens of frameworks out there, from cherrypy to django to albatross to ... well.. you name it. In fact, the huge number of web frameworks are what people point to when they whine about the popularity of Rails. </p>
<p>The Python web development community is divided up with no single voice. But that's another topic alltogether! The point is, there are "web toolkits" (e.g. albatross) that are fairly lightweight but powerful enough to get you through the day (e.g. auto-verifying a bot didn't do a simple form submission fake, or helping with keeping MVC clean).</p>
<p>If you want something that's not "too much framework" look here:</p>
<p><a href="http://wiki.python.org/moin/WebFrameworks" rel="nofollow">http://wiki.python.org/moin/WebFrameworks</a></p>
<p>Look under "Basic Frameworks Providing Templating". They're all lightweight and do all the "don't reinvent the wheel" stuff without forcing a Mac truck on you.</p>
| 2 | 2009-09-17T02:47:39Z | [
"python",
"frameworks"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 136,138 | <p>A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.</p>
<p>A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how <code>dict.fromkeys()</code>, a classmethod, returns an instance of the subclass when called on a subclass:</p>
<pre><code>>>> class DictSubclass(dict):
... def __repr__(self):
... return "DictSubclass"
...
>>> dict.fromkeys("abc")
{'a': None, 'c': None, 'b': None}
>>> DictSubclass.fromkeys("abc")
DictSubclass
>>>
</code></pre>
| 525 | 2008-09-25T21:05:53Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 136,149 | <p>Basically <code>@classmethod</code> makes a method whose first argument is the class it's called from (rather than the class instance), <code>@staticmethod</code> does not have any implicit arguments.</p>
| 54 | 2008-09-25T21:07:06Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 136,246 | <p><code>@staticmethod</code> just disables the default function as method descriptor. classmethod wraps your function in a container callable that passes a reference to the owning class as first argument:</p>
<pre><code>>>> class C(object):
... pass
...
>>> def f():
... pass
...
>>> staticmethod(f).__get__(None, C)
<function f at 0x5c1cf0>
>>> classmethod(f).__get__(None, C)
<bound method type.f of <class '__main__.C'>>
</code></pre>
<p>As a matter of fact, <code>classmethod</code> has a runtime overhead but makes it possible to access the owning class. Alternatively I recommend using a metaclass and putting the class methods on that metaclass:</p>
<pre><code>>>> class CMeta(type):
... def foo(cls):
... print cls
...
>>> class C(object):
... __metaclass__ = CMeta
...
>>> C.foo()
<class '__main__.C'>
</code></pre>
| 12 | 2008-09-25T21:24:13Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 1,669,457 | <p><a href="http://rapd.wordpress.com/2008/07/02/python-staticmethod-vs-classmethod/">Here</a> is a short article on this question</p>
<blockquote>
<p>@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. Itâs definition is immutable via inheritance.</p>
<p>@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance. Thatâs because the first argument for @classmethod function must always be cls (class).</p>
</blockquote>
| 32 | 2009-11-03T19:02:23Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 1,669,524 | <p>Maybe a bit of example code will help: Notice the difference in the call signatures of <code>foo</code>, <code>class_foo</code> and <code>static_foo</code>:</p>
<pre><code>class A(object):
def foo(self,x):
print "executing foo(%s,%s)"%(self,x)
@classmethod
def class_foo(cls,x):
print "executing class_foo(%s,%s)"%(cls,x)
@staticmethod
def static_foo(x):
print "executing static_foo(%s)"%x
a=A()
</code></pre>
<p>Below is the usual way an object instance calls a method. The object instance, <code>a</code>, is implicitly passed as the first argument.</p>
<pre><code>a.foo(1)
# executing foo(<__main__.A object at 0xb7dbef0c>,1)
</code></pre>
<hr>
<p><strong>With classmethods</strong>, the class of the object instance is implicitly passed as the first argument instead of <code>self</code>.</p>
<pre><code>a.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)
</code></pre>
<p>You can also call <code>class_foo</code> using the class. In fact, if you define something to be
a classmethod, it is probably because you intend to call it from the class rather than from a class instance. <code>A.foo(1)</code> would have raised a TypeError, but <code>A.class_foo(1)</code> works just fine:</p>
<pre><code>A.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)
</code></pre>
<p>One use people have found for class methods is to create <a href="http://stackoverflow.com/a/1950927/190597">inheritable alternative constructors</a>.</p>
<hr>
<p><strong>With staticmethods</strong>, neither <code>self</code> (the object instance) nor <code>cls</code> (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:</p>
<pre><code>a.static_foo(1)
# executing static_foo(1)
A.static_foo('hi')
# executing static_foo(hi)
</code></pre>
<p>Staticmethods are used to group functions which have some logical connection with a class to the class.</p>
<hr>
<p><code>foo</code> is just a function, but when you call <code>a.foo</code> you don't just get the function,
you get a "partially applied" version of the function with the object instance <code>a</code> bound as the first argument to the function. <code>foo</code> expects 2 arguments, while <code>a.foo</code> only expects 1 argument.</p>
<p><code>a</code> is bound to <code>foo</code>. That is what is meant by the term "bound" below:</p>
<pre><code>print(a.foo)
# <bound method A.foo of <__main__.A object at 0xb7d52f0c>>
</code></pre>
<p>With <code>a.class_foo</code>, <code>a</code> is not bound to <code>class_foo</code>, rather the class <code>A</code> is bound to <code>class_foo</code>.</p>
<pre><code>print(a.class_foo)
# <bound method type.class_foo of <class '__main__.A'>>
</code></pre>
<p>Here, with a staticmethod, even though it is a method, <code>a.static_foo</code> just returns
a good 'ole function with no arguments bound. <code>static_foo</code> expects 1 argument, and
<code>a.static_foo</code> expects 1 argument too.</p>
<pre><code>print(a.static_foo)
# <function static_foo at 0xb7d479cc>
</code></pre>
<p>And of course the same thing happens when you call <code>static_foo</code> with the class <code>A</code> instead.</p>
<pre><code>print(A.static_foo)
# <function static_foo at 0xb7d479cc>
</code></pre>
| 1,256 | 2009-11-03T19:13:48Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 1,669,579 | <p><strong>Official python docs:</strong></p>
<p><a href="http://docs.python.org/library/functions.html#classmethod">@classmethod</a></p>
<blockquote>
<p>A class method receives the class as
implicit first argument, just like an
instance method receives the instance.
To declare a class method, use this
idiom:</p>
<pre><code>class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
</code></pre>
<p>The <code>@classmethod</code> form is a function
<a href="http://docs.python.org/2/glossary.html#term-decorator"><em>decorator</em></a> â see the description of
function definitions in <a href="http://docs.python.org/2/reference/compound_stmts.html#function"><em>Function
definitions</em></a> for details.</p>
<p>It can be called either on the class
(such as <code>C.f()</code>) or on an instance
(such as <code>C().f()</code>). The instance is
ignored except for its class. If a
class method is called for a derived
class, the derived class object is
passed as the implied first argument.</p>
<p>Class methods are different than C++
or Java static methods. If you want
those, see <a href="http://docs.python.org/2/library/functions.html#staticmethod"><code>staticmethod()</code></a> in this
section.</p>
</blockquote>
<p><a href="http://docs.python.org/library/functions.html#staticmethod">@staticmethod</a></p>
<blockquote>
<p>A static method does not receive an
implicit first argument. To declare a
static method, use this idiom:</p>
<pre><code>class C:
@staticmethod
def f(arg1, arg2, ...): ...
</code></pre>
<p>The <code>@staticmethod</code> form is a function
<a href="http://docs.python.org/2/glossary.html#term-decorator"><em>decorator</em></a> â see the description of
function definitions in <a href="http://docs.python.org/2/reference/compound_stmts.html#function"><em>Function
definitions</em></a> for details.</p>
<p>It can be called either on the class
(such as <code>C.f()</code>) or on an instance
(such as <code>C().f()</code>). The instance is
ignored except for its class.</p>
<p>Static methods in Python are similar
to those found in Java or C++. For a
more advanced concept, see
<a href="http://docs.python.org/2/library/functions.html#classmethod"><code>classmethod()</code></a> in this section.</p>
</blockquote>
| 40 | 2009-11-03T19:23:19Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 9,428,384 | <p>I just wanted to add that the @decorators were added in python 2.4.</p>
<p>If you're using python < 2.4 you can use the classmethod() and staticmethod() function.
For example, if you want to create a factory method (A function returning an instance of a different implementation of a class depending on what argument it gets) you can do something like:</p>
<pre><code>class Cluster(object):
def _is_cluster_for(cls, name):
"""
see if this class is the cluster with this name
this is a classmethod
"""
return cls.__name__ == name
_is_cluster_for = classmethod(_is_cluster_for)
#static method
def getCluster(name):
"""
static factory method, should be in Cluster class
returns a cluster object of the given name
"""
for cls in Cluster.__subclasses__():
if cls._is_cluster_for(name):
return cls()
getCluster = staticmethod(getCluster)
</code></pre>
<p>Also observe that this is a good example for using a classmethod and a static method,
The static method clearly belongs to the class, since it uses the class Cluster internally.
The classmethod only needs information about the class, and no instance of the object.</p>
<p>Another benefit of making the <code>_is_cluster_for</code> method a classmethod is so a subclass can decide to change it's implementation, maybe because it is pretty generic and can handle more than one type of cluster, so just checking the name of the class would not be enough.</p>
| 17 | 2012-02-24T09:32:32Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 13,524,845 | <p>I disagree that static methods are not useful, but I also use Python differently than most. It is being used as a scripting language for another piece of software and anything I write must be able to use a default python install, no custom modules allowed except for very specific circumstances. All my classes are in one file(ugh!!) and a utility class with random, unrelated static helper methods, mostly related to interacting with the software being extended, becomes extremely useful and helps clean up the code quite a bit. Doing "normal" Python programming, however, I never do use them and use modules. Best part about Python is how versatile it can be. The more creative you get, the more it seems it can do for you.</p>
| -2 | 2012-11-23T07:40:42Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 13,920,259 | <p>A quick hack-up ofotherwise identical methods in iPython reveals that <code>@staticmethod</code> yields marginal performance gains (in the nanoseconds), but otherwise it seems to serve no function. Also, any performance gains will probably be wiped out by the additional work of processing the method through <code>staticmethod()</code> during compilation (which happens prior to any code execution when you run a script).</p>
<p>For the sake of code readability I'd avoid <code>@staticmethod</code> unless your method will be used for loads of work, where the nanoseconds count.</p>
| -6 | 2012-12-17T18:51:40Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 20,041,016 | <pre><code>#!/usr/bin/python
#coding:utf-8
class Demo(object):
def __init__(self,x):
self.x = x
@classmethod
def addone(self, x):
return x+1
@staticmethod
def addtwo(x):
return x+2
def addthree(self, x):
return x+3
def main():
print Demo.addone(2)
print Demo.addtwo(2)
#print Demo.addthree(2) #Error
demo = Demo(2)
print demo.addthree(2)
if __name__ == '__main__':
main()
</code></pre>
| -5 | 2013-11-18T05:53:17Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 28,117,800 | <blockquote>
<p><strong>What is the difference between @staticmethod and @classmethod in Python?</strong></p>
</blockquote>
<p>You may have seen Python code like this pseudocode, which demonstrates the signatures of the various method types and provides a docstring to explain each:</p>
<pre><code>class Foo(object):
def a_normal_method(self, arg_1, kwarg_2=None):
'''
Return a value that is a function of the instance with its
attributes, and other arguments such as arg_1 and kwarg2
'''
@staticmethod
def a_static_method(arg_0):
'''
Return a value that is a function of arg_0. It does not know the
instance or class it is called from.
'''
@classmethod
def a_class_method(cls, arg1):
'''
Return a value that is a function of the class and other arguments.
respects subclassing, it is called with the class it is called from.
'''
</code></pre>
<h1>The Normal Method</h1>
<p>First I'll explain the <code>normal_method</code>. This may be better called an "<strong>instance method</strong>". When an instance method is used, it is used as a partial function (as opposed to a total function, defined for all values when viewed in source code) that is, when used, the first of the arguments is predefined as the instance of the object, with all of its given attributes. It has the instance of the object bound to it, and it must be called from an instance of the object. Typically, it will access various attributes of the instance.</p>
<p>For example, this is an instance of a string:</p>
<pre><code>', '
</code></pre>
<p>if we use the instance method, <code>join</code> on this string, to join another iterable,
it quite obviously is a function of the instance, in addition to being a function of the iterable list, <code>['a', 'b', 'c']</code>:</p>
<pre><code>>>>', '.join(['a', 'b', 'c'])
'a, b, c'
</code></pre>
<h1>Static Method</h1>
<p>The static method does <em>not</em> take the instance as an argument. Yes it is very similar to a module level function. However, a module level function must live in the module and be specially imported to other places where it is used. If it is attached to the object, however, it will follow the object conveniently through importing and inheritance as well.</p>
<p>An example is the <code>str.maketrans</code> static method, moved from the <code>string</code> module in Python 3. It makes a translation table suitable for consumption by <code>str.translate</code>. It does seem rather silly when used from an instance of a string, as demonstrated below, but importing the function from the <code>string</code> module is rather clumsy, and it's nice to be able to call it from the class, as in <code>str.maketrans</code></p>
<pre><code># demonstrate same function whether called from instance or not:
>>> ', '.maketrans('ABC', 'abc')
{65: 97, 66: 98, 67: 99}
>>> str.maketrans('ABC', 'abc')
{65: 97, 66: 98, 67: 99}
</code></pre>
<p>In python 2, you have to import this function from the increasingly deprecated string module:</p>
<pre><code>>>> import string
>>> 'ABCDEFG'.translate(string.maketrans('ABC', 'abc'))
'abcDEFG'
</code></pre>
<h1>Class Method</h1>
<p>A class method is a similar to a static method in that it takes an implicit first argument, but instead of taking the instance, it takes the class. Frequently these are used as alternative constructors for better semantic usage and it will support inheritance.</p>
<p>The most canonical example of a builtin classmethod is <code>dict.fromkeys</code>. It is used as an alternative constructor of dict, (well suited for when you know what your keys are and want a default value for them.)</p>
<pre><code>>>> dict.fromkeys(['a', 'b', 'c'])
{'c': None, 'b': None, 'a': None}
</code></pre>
<p>When we subclass dict, we can use the same constructor, which creates an instance of the subclass.</p>
<pre><code>>>> class MyDict(dict): 'A dict subclass, use to demo classmethods'
>>> md = MyDict.fromkeys(['a', 'b', 'c'])
>>> md
{'a': None, 'c': None, 'b': None}
>>> type(md)
<class '__main__.MyDict'>
</code></pre>
<p>See the <a href="https://github.com/pydata/pandas/blob/master/pandas/core/frame.py">pandas source code</a> for other similar examples of alternative constructors, and see also the official Python documentation on <a href="https://docs.python.org/library/functions.html#classmethod"><code>classmethod</code></a> and <a href="https://docs.python.org/library/functions.html#staticmethod"><code>staticmethod</code></a>.</p>
| 15 | 2015-01-23T20:01:20Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 30,329,887 | <p>I think a better question is "When would you use @classmethod vs @staticmethod?"</p>
<p>@classmethod allows you easy access to private members that are associated to the class definition. this is a great way to do singletons, or factory classes that control the number of instances of the created objects exist.</p>
<p>@staticmethod provides marginal performance gains, but I have yet to see a productive use of a static method within a class that couldn't be achieved as a standalone function outside the class.</p>
| 14 | 2015-05-19T15:27:13Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 33,727,452 | <p><a href="https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods" rel="nofollow">Here</a> is one good link for this topic, and summary it as following.</p>
<p><strong><code>@staticmethod</code></strong> function is nothing more than a function defined inside a class. It is callable without instantiating the class first. Itâs definition is immutable via inheritance.</p>
<ul>
<li>Python does not have to instantiate a bound-method for object.</li>
<li>It eases the readability of the code, and it does not depend on the state of object itself;</li>
</ul>
<p><strong><code>@classmethod</code></strong> function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance, can be overridden by subclass. Thatâs because the first argument for <code>@classmethod</code> function must always be <em>cls</em> (class).</p>
<ul>
<li><em>Factory methods</em>, that are used to create an instance for a class using for example some sort of pre-processing.</li>
<li><em>Static methods calling static methods</em>: if you split a static methods in several static methods, you shouldn't hard-code the class name but use class methods</li>
</ul>
| 2 | 2015-11-16T02:00:50Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 34,255,425 | <p><strong>@classmethod means</strong>: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.</p>
<p><strong>@staticmethod means:</strong> when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).</p>
| 4 | 2015-12-13T19:37:43Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 36,798,076 | <p>To decide whether to use <a href="https://docs.python.org/3/library/functions.html?highlight=staticmethod#staticmethod" rel="nofollow">@staticmethod</a> or <a href="https://docs.python.org/3.5/library/functions.html?highlight=classmethod#classmethod" rel="nofollow">@classmethod</a> you have to look inside your method. <strong>If your method accesses other variables/methods in your class then use @classmethod</strong>. On the other hand if your method does not touch any other parts of the class then use @staticmethod.</p>
<pre><code>class Apple:
counter = 0
@staticmethod
def about_apple():
print('Apple is good for you.')
# note you can still access other member of the class
# but you have to use the class instance
# which is not very nice, because you have repeat yourself
#
# For example:
# @staticmethod
# print('Number of apples have been juiced: %s' % Apple.counter)
# @classmethod
# it is especially useful when you move code to other classes
# print('Number of apples have been juiced: %s' % cls.counter)
@classmethod
def make_apple_juice(cls, number_of_apples):
print('Make juice:')
for i in range(number_of_apples):
cls._juice_this(i)
@classmethod
def _juice_this(cls, apple):
cls.counter += 1
print('Juicing %d...' % apple)
</code></pre>
| 4 | 2016-04-22T15:40:20Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 38,219,891 | <p>In <a href="https://www.eduonix.com/courses/Software-Development/the-developers-guide-to-python-3-programming?coupon_code=edusk5" rel="nofollow">Python</a>, a classmethod receives a class as the implicit first argument. The class of the object instance is implicitly passed as the first argument. This can be useful
when one wants the method to be a factory of the class as it gets the actual class (which called the method) as the first argument, one can instantiate the right class, even if subclasses are also concerned.</p>
<p>A staticmethod is just a function defined inside a class. It does not know anything about the class or instance it was called on and only gets the arguments that were passed without any implicit first argument.
Example:</p>
<pre><code>class Test(object):
def foo(self, a):
print "testing (%s,%s)"%(self,a)
@classmethod
def foo_classmethod(cls, a):
print "testing foo_classmethod(%s,%s)"%(cls,a)
@staticmethod
def foo_staticmethod(a):
print "testing foo_staticmethod(%s)"%a
test = Test()
</code></pre>
<p>staticmethods are used to group functions which have some logical connection with a class to the class.</p>
| 2 | 2016-07-06T08:53:02Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 39,589,894 | <p>I will try to explain the basic difference using an example.</p>
<pre><code>class A(object):
x = 0
def say_hi(self):
pass
@staticmethod
def say_hi_static():
pass
@classmethod
def say_hi_class(cls):
pass
def run_self(self):
self.x += 1
print self.x # outputs 1
self.say_hi()
self.say_hi_static()
self.say_hi_class()
@staticmethod
def run_static():
print A.x # outputs 0
# A.say_hi() # wrong
A.say_hi_static()
A.say_hi_class()
@classmethod
def run_class(cls):
print cls.x # outputs 0
# cls.say_hi() # wrong
cls.say_hi_static()
cls.say_hi_class()
</code></pre>
<p>1 - we can directly call static and classmethods without initializing</p>
<pre><code># A.run_self() # wrong
A.run_static()
A.run_class()
</code></pre>
<p>2- Static method cannot call self method but can call other static and classmethod</p>
<p>3- Static method belong to class and will not use object at all.</p>
<p>4- Class method are not bound to an object but to a class.</p>
| 0 | 2016-09-20T09:03:29Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 39,776,104 | <p>Another consideration with respect to staticmethod vs classmethod comes up with inheritance. Say you have the following class:</p>
<pre><code>class Foo(object):
@staticmethod
def bar():
return "In Foo"
</code></pre>
<p>And you then want to override <code>bar()</code> in a child class:</p>
<pre><code>class Foo2(Foo):
@staticmethod
def bar():
return "In Foo2"
</code></pre>
<p>This works, but note that now the <code>bar()</code> implementation in the child class (<code>Foo2</code>) can no longer take advantage of anything specific to that class. For example, say <code>Foo2</code> had a method called <code>magic()</code> that you want to use in the <code>Foo2</code> implementation of <code>bar()</code>:</p>
<pre><code>class Foo2(Foo):
@staticmethod
def bar():
return "In Foo2"
@staticmethod
def magic():
return "Something useful you'd like to use in bar, but now can't"
</code></pre>
<p>The workaround here would be to call <code>Foo2.magic()</code> in <code>bar()</code>, but then you're repeating yourself (if the name of <code>Foo2</code> changes, you'll have to remember to update that <code>bar()</code> method).</p>
<p>To me, this is a slight violation of the <a href="https://en.wikipedia.org/wiki/Open/closed_principle" rel="nofollow">open/closed principle</a>, since a decision made in <code>Foo</code> is impacting your ability to refactor common code in a derived class (ie it's less open to extension). If <code>bar()</code> were a <code>classmethod</code> we'd be fine:</p>
<pre><code>class Foo(object):
@classmethod
def bar(cls):
return "In Foo"
class Foo2(Foo):
@classmethod
def bar(cls):
return "In Foo2 " + cls.magic()
@classmethod
def magic(cls):
return "MAGIC"
print Foo2().bar()
</code></pre>
<p>Gives: <code>In Foo2 MAGIC</code></p>
| 1 | 2016-09-29T17:02:51Z | [
"python"
] |
What is the difference between @staticmethod and @classmethod in Python? | 136,097 | <p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod"><code>@classmethod</code></a>?</p>
| 1,583 | 2008-09-25T21:01:57Z | 39,829,692 | <p><strong>Static Methods:</strong></p>
<ul>
<li>Simple functions with no self argument. </li>
<li>Work on class attributes; not on instance attributes.</li>
<li>Can be called through both class and instance.</li>
<li>The built-in function staticmethod()is used to create them.</li>
</ul>
<p><strong>Benefits of Static Methods:</strong></p>
<ul>
<li>It localizes the function name in the classscope</li>
<li><p>It moves the function code closer to where it is used</p>
<pre><code> @staticmethod
def some_static_method(*args, **kwds):
pass
</code></pre></li>
</ul>
<p><strong>Class Methods:</strong></p>
<ul>
<li>Functions that have first argument as classname.</li>
<li>Can be called through both class and instance.</li>
<li><p>These are created with classmethod in-built function.</p>
<pre><code> @classmethod
def some_class_method(cls, *args, **kwds):
pass
</code></pre></li>
</ul>
| 0 | 2016-10-03T10:41:18Z | [
"python"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 136,280 | <p>Assumes a unix-like system.</p>
<pre><code>import os
def tail(f, n, offset=0):
stdin,stdout = os.popen2("tail -n "+n+offset+" "+f)
stdin.close()
lines = stdout.readlines(); stdout.close()
return lines[:,-offset]
</code></pre>
| 57 | 2008-09-25T21:30:14Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 136,354 | <p>For efficiency with very large files (common in logfile situations where you may want to use tail), you generally want to avoid reading the whole file (even if you do do it without reading the whole file into memory at once) However, you do need to somehow work out the offset in lines rather than characters. One possibility is reading backwards with seek() char by char, but this is very slow. Instead, its better to process in larger blocks.</p>
<p>I've a utility function I wrote a while ago to read files backwards that can be used here.</p>
<pre><code>import os, itertools
def rblocks(f, blocksize=4096):
"""Read file as series of blocks from end of file to start.
The data itself is in normal order, only the order of the blocks is reversed.
ie. "hello world" -> ["ld","wor", "lo ", "hel"]
Note that the file must be opened in binary mode.
"""
if 'b' not in f.mode.lower():
raise Exception("File must be opened using binary mode.")
size = os.stat(f.name).st_size
fullblocks, lastblock = divmod(size, blocksize)
# The first(end of file) block will be short, since this leaves
# the rest aligned on a blocksize boundary. This may be more
# efficient than having the last (first in file) block be short
f.seek(-lastblock,2)
yield f.read(lastblock)
for i in range(fullblocks-1,-1, -1):
f.seek(i * blocksize)
yield f.read(blocksize)
def tail(f, nlines):
buf = ''
result = []
for block in rblocks(f):
buf = block + buf
lines = buf.splitlines()
# Return all lines except the first (since may be partial)
if lines:
result.extend(lines[1:]) # First line may not be complete
if(len(result) >= nlines):
return result[-nlines:]
buf = lines[0]
return ([buf]+result)[-nlines:]
f=open('file_to_tail.txt','rb')
for line in tail(f, 20):
print line
</code></pre>
<p>[Edit] Added more specific version (avoids need to reverse twice)</p>
| 1 | 2008-09-25T21:40:32Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 136,368 | <p>This may be quicker than yours. Makes no assumptions about line length. Backs through the file one block at a time till it's found the right number of '\n' characters.</p>
<pre><code>def tail( f, lines=20 ):
total_lines_wanted = lines
BLOCK_SIZE = 1024
f.seek(0, 2)
block_end_byte = f.tell()
lines_to_go = total_lines_wanted
block_number = -1
blocks = [] # blocks of size BLOCK_SIZE, in reverse order starting
# from the end of the file
while lines_to_go > 0 and block_end_byte > 0:
if (block_end_byte - BLOCK_SIZE > 0):
# read the last block we haven't yet read
f.seek(block_number*BLOCK_SIZE, 2)
blocks.append(f.read(BLOCK_SIZE))
else:
# file too small, start from begining
f.seek(0,0)
# only read what was not read
blocks.append(f.read(block_end_byte))
lines_found = blocks[-1].count('\n')
lines_to_go -= lines_found
block_end_byte -= BLOCK_SIZE
block_number -= 1
all_read_text = ''.join(reversed(blocks))
return '\n'.join(all_read_text.splitlines()[-total_lines_wanted:])
</code></pre>
<p>I don't like tricky assumptions about line length when -- as a practical matter -- you can never know things like that.</p>
<p>Generally, this will locate the last 20 lines on the first or second pass through the loop. If your 74 character thing is actually accurate, you make the block size 2048 and you'll tail 20 lines almost immediately.</p>
<p>Also, I don't burn a lot of brain calories trying to finesse alignment with physical OS blocks. Using these high-level I/O packages, I doubt you'll see any performance consequence of trying to align on OS block boundaries. If you use lower-level I/O, then you might see a speedup.</p>
| 97 | 2008-09-25T21:43:18Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 136,475 | <p>On second thought, this is probably just as fast as anything here.</p>
<pre><code>def tail( f, window=20 ):
lines= ['']*window
count= 0
for l in f:
lines[count%window]= l
count += 1
print lines[count%window:], lines[:count%window]
</code></pre>
<p>It's a lot simpler. And it does seem to rip along at a good pace. </p>
| -1 | 2008-09-25T22:03:09Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 280,083 | <p>If reading the whole file is acceptable then use a deque.</p>
<pre><code>from collections import deque
deque(f, maxlen=n)
</code></pre>
<p>Prior to 2.6, deques didn't have a maxlen option, but it's easy enough to implement.</p>
<pre><code>import itertools
def maxque(items, size):
items = iter(items)
q = deque(itertools.islice(items, size))
for item in items:
del q[0]
q.append(item)
return q
</code></pre>
<p>If it's a requirement to read the file from the end, then use a gallop (a.k.a exponential) search.</p>
<pre><code>def tail(f, n):
assert n >= 0
pos, lines = n+1, []
while len(lines) <= n:
try:
f.seek(-pos, 2)
except IOError:
f.seek(0)
break
finally:
lines = list(f)
pos *= 2
return lines[-n:]
</code></pre>
| 19 | 2008-11-11T05:17:18Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 692,616 | <p>The code I ended up using. I think this is the best so far:</p>
<pre><code>def tail(f, n, offset=None):
"""Reads a n lines from f with an offset of offset lines. The return
value is a tuple in the form ``(lines, has_more)`` where `has_more` is
an indicator that is `True` if there are more lines in the file.
"""
avg_line_length = 74
to_read = n + (offset or 0)
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None], \
len(lines) > to_read or pos > 0
avg_line_length *= 1.3
</code></pre>
| 17 | 2009-03-28T11:13:44Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 3,018,671 | <p>based on S.Lott's top voted answer (Sep 25 '08 at 21:43), but fixed for small files.</p>
<pre><code>def tail(the_file, lines_2find=20):
the_file.seek(0, 2) #go to end of file
bytes_in_file = the_file.tell()
lines_found, total_bytes_scanned = 0, 0
while lines_2find+1 > lines_found and bytes_in_file > total_bytes_scanned:
byte_block = min(1024, bytes_in_file-total_bytes_scanned)
the_file.seek(-(byte_block+total_bytes_scanned), 2)
total_bytes_scanned += byte_block
lines_found += the_file.read(1024).count('\n')
the_file.seek(-total_bytes_scanned, 2)
line_list = list(the_file.readlines())
return line_list[-lines_2find:]
#we read at least 21 line breaks from the bottom, block by block for speed
#21 to ensure we don't get a half line
</code></pre>
<p>Hope this is useful.</p>
| 2 | 2010-06-10T21:28:20Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Get last n lines of a file with Python, similar to tail | 136,168 | <p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.</p>
<p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and supports an offset. What I came up with looks like this:</p>
<pre><code>def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
</code></pre>
<p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
| 122 | 2008-09-25T21:11:11Z | 4,131,157 | <p>you can go to the end of your file with f.seek(0, 2) and then read off lines one by one with the following replacement for readline():</p>
<pre><code>def readline_backwards(self, f):
backline = ''
last = ''
while not last == '\n':
backline = last + backline
if f.tell() <= 0:
return backline
f.seek(-1, 1)
last = f.read(1)
f.seek(-1, 1)
backline = last
last = ''
while not last == '\n':
backline = last + backline
if f.tell() <= 0:
return backline
f.seek(-1, 1)
last = f.read(1)
f.seek(-1, 1)
f.seek(1, 1)
return backline
</code></pre>
| 1 | 2010-11-09T06:50:09Z | [
"python",
"file",
"file-io",
"tail",
"logfiles"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.