title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
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>&gt;&gt;&gt; a = lambda x :...
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) &gt;&gt;&gt; 12 f(4) &gt;&gt;&gt; 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>&gt;&gt;&gt; a = lambda x :...
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...
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>&gt;&gt;&gt; a = lambda x :...
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 ...
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>&gt;&gt;&gt; a = lambda x :...
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>He...
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>&gt;&gt;&gt; a = lambda x :...
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_d...
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>&gt;&gt;&gt; a = lambda x :...
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>L...
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,...
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 cor...
-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,...
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 co...
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,...
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,...
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-refe...
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-310...
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:...
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&gt;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>Unl...
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 e...
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 ...
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 foun...
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 no...
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...
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_obje...
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"...
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&amp;pg=PA114&amp;lpg=PA114&amp;dq=zip%28range%285%29,%20xrange%28100000000%29%29&amp;source=bl&amp;ots=-BxWZinKHq&amp;sig=O9G4mskHmYDljCCQv8v7alVUy_M&amp;hl=en&amp;sa=X&amp;ei=0mMPUoa9LsXJrAe7p4DABA&amp;ved=0CD0Q6AEwAw#v=onepage&a...
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 &amp; 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 fast...
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" ...
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" ...
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" ...
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...
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" ...
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 packe...
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" ...
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 paddi...
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 defaultS...
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...
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 fal...
-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” ...
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 = otherStr...
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-opera...
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-tw...
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) t...
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/b9a...
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 ...
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.<...
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 mu...
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 ...
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 interfa...
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.<...
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 ...
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 ...
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...
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 rule...
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 straightforwar...
-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 no...
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...
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 no...
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 no...
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 anno...
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 no...
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 thoug...
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 no...
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 scree...
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 no...
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...
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 no...
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 no...
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 i...
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...
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>&gt;&gt;&gt; class C(object): ... pass ... &gt;&gt;&gt; def f(): ... pass ... &gt;&gt;&gt; st...
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 vi...
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 "e...
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 idio...
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 &lt; 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 argum...
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...
-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>st...
-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) pri...
-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):...
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> ...
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 i...
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 mean...
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 metho...
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 w...
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 sel...
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><c...
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...
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. W...
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. W...
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 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. W...
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() l...
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. W...
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 se...
-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. W...
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 = d...
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. W...
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...
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. W...
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_2f...
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. W...
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() &lt;= 0: ...
1
2010-11-09T06:50:09Z
[ "python", "file", "file-io", "tail", "logfiles" ]