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 |
---|---|---|---|---|---|---|---|---|---|
Using global variables in a function other than the one that created them | 423,379 | <p>If I create a global variable in one function, how can I use that variable in another function?<br>
Do I need to store the global variable in a local variable of the function which needs its access?</p>
| 1,686 | 2009-01-08T05:45:02Z | 6,664,227 | <p>Python uses a simple heuristic to decide which scope it should load a variable from, between local and global. If a variable name appears on the left hand side of an assignment, but is not declared global, it is assumed to be local. If it does not appear on the left hand side of an assignment, it is assumed to be global. </p>
<pre><code>>>> import dis
>>> def foo():
... global bar
... baz = 5
... print bar
... print baz
... print quux
...
>>> dis.disassemble(foo.func_code)
3 0 LOAD_CONST 1 (5)
3 STORE_FAST 0 (baz)
4 6 LOAD_GLOBAL 0 (bar)
9 PRINT_ITEM
10 PRINT_NEWLINE
5 11 LOAD_FAST 0 (baz)
14 PRINT_ITEM
15 PRINT_NEWLINE
6 16 LOAD_GLOBAL 1 (quux)
19 PRINT_ITEM
20 PRINT_NEWLINE
21 LOAD_CONST 0 (None)
24 RETURN_VALUE
>>>
</code></pre>
<p>See how baz, which appears on the left side of an assignment in <code>foo()</code>, is the only <code>LOAD_FAST</code> variable.</p>
| 50 | 2011-07-12T12:35:08Z | [
"python",
"global-variables",
"scope"
]
|
Using global variables in a function other than the one that created them | 423,379 | <p>If I create a global variable in one function, how can I use that variable in another function?<br>
Do I need to store the global variable in a local variable of the function which needs its access?</p>
| 1,686 | 2009-01-08T05:45:02Z | 19,151,605 | <p>Global variables are much more fun when you deal with parallel execution. Here is an example of using a global variable within multiprocessing. We can clearly see that each process works with its own copy of the variable:</p>
<pre><code>import multiprocessing
import time
import os
import sys
import random
def worker(a):
oldValue = get()
set(random.randint(0, 100))
sys.stderr.write(' '.join([str(os.getpid()), str(a), 'old:', str(oldValue), 'new:', str(get()), '\n']))
def get():
global globalVariable
return globalVariable
globalVariable = -1
def set(v):
global globalVariable
globalVariable = v
print get()
set(-2)
print get()
processPool = multiprocessing.Pool(5)
results = processPool.map(worker, range(15))
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>27094 0 old: -2 new: 2
27094 1 old: 2 new: 95
27094 2 old: 95 new: 20
27094 3 old: 20 new: 54
27098 4 old: -2 new: 80
27098 6 old: 80 new: 62
27095 5 old: -2 new: 100
27094 7 old: 54 new: 23
27098 8 old: 62 new: 67
27098 10 old: 67 new: 22
27098 11 old: 22 new: 85
27095 9 old: 100 new: 32
27094 12 old: 23 new: 65
27098 13 old: 85 new: 60
27095 14 old: 32 new: 71
</code></pre>
| 14 | 2013-10-03T05:41:16Z | [
"python",
"global-variables",
"scope"
]
|
Using global variables in a function other than the one that created them | 423,379 | <p>If I create a global variable in one function, how can I use that variable in another function?<br>
Do I need to store the global variable in a local variable of the function which needs its access?</p>
| 1,686 | 2009-01-08T05:45:02Z | 19,347,254 | <p>As it turns out the answer is always simple.</p>
<p>Here is a small sample module. It is is a way to show it in a main definition:</p>
<pre><code>def five(enterAnumber,sumation):
global helper
helper = enterAnumber + sumation
def isTheNumber():
return helper
</code></pre>
<p>Here is a way to show it in a main definition:</p>
<pre><code>import TestPy
def main():
atest = TestPy
atest.five(5,8)
print(atest.isTheNumber())
if __name__ == '__main__':
main()
</code></pre>
<p>This simple code works just like that, and it will execute. I hope it helps.</p>
| 8 | 2013-10-13T16:07:41Z | [
"python",
"global-variables",
"scope"
]
|
Using global variables in a function other than the one that created them | 423,379 | <p>If I create a global variable in one function, how can I use that variable in another function?<br>
Do I need to store the global variable in a local variable of the function which needs its access?</p>
| 1,686 | 2009-01-08T05:45:02Z | 24,572,187 | <p>In addition to already existing answers and to make this more confusing:</p>
<blockquote>
<p>In Python, variables that are only referenced inside a function are
<strong>implicitly global</strong>. If a variable is assigned a new value anywhere
within the functionâs body, itâs assumed to be a <strong>local</strong>. If a variable
is ever assigned a new value inside the function, the variable is
implicitly local, and you need to explicitly declare it as âglobalâ.</p>
<p>Though a bit surprising at first, a momentâs consideration explains
this. On one hand, requiring global for assigned variables provides a
bar against unintended side-effects. On the other hand, if global was
required for all global references, youâd be using global all the
time. Youâd have to declare as global every reference to a built-in
function or to a component of an imported module. This clutter would
defeat the usefulness of the global declaration for identifying
side-effects.</p>
</blockquote>
<p>Source: <em><a href="https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python">What are the rules for local and global variables in Python?</a></em>.</p>
| 21 | 2014-07-04T10:23:56Z | [
"python",
"global-variables",
"scope"
]
|
Using global variables in a function other than the one that created them | 423,379 | <p>If I create a global variable in one function, how can I use that variable in another function?<br>
Do I need to store the global variable in a local variable of the function which needs its access?</p>
| 1,686 | 2009-01-08T05:45:02Z | 27,287,648 | <p>What you are saying is to use the method like this:</p>
<pre><code>globvar = 5
def f():
var = globvar
print(var)
f()** #prints 5
</code></pre>
<p>but the better way is to use the global variable like this:<br/></p>
<pre><code>globavar = 5
def f():
global globvar
print(globvar)
f() #prints 5
</code></pre>
<p>both give the same output.</p>
| 8 | 2014-12-04T06:27:43Z | [
"python",
"global-variables",
"scope"
]
|
Using global variables in a function other than the one that created them | 423,379 | <p>If I create a global variable in one function, how can I use that variable in another function?<br>
Do I need to store the global variable in a local variable of the function which needs its access?</p>
| 1,686 | 2009-01-08T05:45:02Z | 27,580,376 | <p>You need to reference the global variable in every function you want to use.</p>
<p>As follows:</p>
<pre><code>var = "test"
def printGlobalText():
global var #wWe are telling to explicitly use the global version
var = "global from printGlobalText fun."
print "var from printGlobalText: " + var
def printLocalText():
#We are NOT telling to explicitly use the global version, so we are creating a local variable
var = "local version from printLocalText fun"
print "var from printLocalText: " + var
printGlobalText()
printLocalText()
"""
Output Result:
var from printGlobalText: global from printGlobalText fun.
var from printLocalText: local version from printLocalText
[Finished in 0.1s]
"""
</code></pre>
| 8 | 2014-12-20T12:45:26Z | [
"python",
"global-variables",
"scope"
]
|
Using global variables in a function other than the one that created them | 423,379 | <p>If I create a global variable in one function, how can I use that variable in another function?<br>
Do I need to store the global variable in a local variable of the function which needs its access?</p>
| 1,686 | 2009-01-08T05:45:02Z | 28,329,600 | <p>Try This :</p>
<pre><code>def x1():
global x
x = 6
def x2():
global x
x = x+1
print x
x = 5
x1()
x2()
</code></pre>
| 4 | 2015-02-04T19:19:54Z | [
"python",
"global-variables",
"scope"
]
|
Using global variables in a function other than the one that created them | 423,379 | <p>If I create a global variable in one function, how can I use that variable in another function?<br>
Do I need to store the global variable in a local variable of the function which needs its access?</p>
| 1,686 | 2009-01-08T05:45:02Z | 33,320,055 | <p>following on and as an add on use a file to contain all global variables all declared locally and then 'import as'</p>
<pre><code>file initval.py
Stocksin = 300
Prices = []
File getstocks.py
import initval as iv
Def getmystocks ():
iv.Stocksin = getstockcount ()
Def getmycharts ():
For ic in range (0,iv.Stocksin):
</code></pre>
<p>.....</p>
| 2 | 2015-10-24T15:46:18Z | [
"python",
"global-variables",
"scope"
]
|
Using global variables in a function other than the one that created them | 423,379 | <p>If I create a global variable in one function, how can I use that variable in another function?<br>
Do I need to store the global variable in a local variable of the function which needs its access?</p>
| 1,686 | 2009-01-08T05:45:02Z | 34,559,513 | <blockquote>
<h1>If I create a global variable in one function, how can I use that variable in another function?</h1>
</blockquote>
<p>We can create a global with the following function:</p>
<pre><code>def create_global_variable():
global global_variable # must declare it to be a global first
# modifications are thus reflected on the module's global scope
global_variable = 'Foo'
</code></pre>
<p>Writing a function does not actually run its code. So we call the <code>create_global_variable</code> function:</p>
<pre><code>>>> create_global_variable()
</code></pre>
<h2>Using globals without modification</h2>
<p>You can just use it, so long as you don't expect to change which object it points to: </p>
<p>For example, </p>
<pre><code>def use_global_variable():
return global_variable + '!!!'
</code></pre>
<p>and now we can use the global variable:</p>
<pre><code>>>> use_global_variable()
'Foo!!!'
</code></pre>
<h2>Modification of the global variable from inside a function</h2>
<p>To point the global variable at a different object, you are required to use the global keyword again:</p>
<pre><code>def change_global_variable():
global global_variable
global_variable = 'Bar'
</code></pre>
<p>Note that after writing this function, the code actually changing it has still not run:</p>
<pre><code>>>> use_global_variable()
'Foo!!!'
</code></pre>
<p>So after calling the function:</p>
<pre><code>>>> change_global_variable()
</code></pre>
<p>we can see that the global variable has been changed. The <code>global_variable</code> name now points to <code>'Bar'</code>:</p>
<pre><code>>>> use_global_variable()
'Bar!!!'
</code></pre>
<p>Note that "global" in Python is not truly global - it's only global to the module level. So it is only available to functions written in the modules in which it is global. Functions remember the module in which they are written, so when they are exported into other modules, they still look in the module in which they were created to find global variables.</p>
<h1>Local variables with the same name</h1>
<p>If you create a local variable with the same name, it will overshadow a global variable:</p>
<pre><code>def use_local_with_same_name_as_global():
# bad name for a local variable, though.
global_variable = 'Baz'
return global_variable + '!!!'
>>> use_local_with_same_name_as_global()
'Baz!!!'
</code></pre>
<p>But using that misnamed local variable does not change the global variable:</p>
<pre><code>>>> use_global_variable()
'Bar!!!'
</code></pre>
<p>Note that you should avoid using the local variables with the same names as globals unless you know precisely what you are doing and have a very good reason to do so. I have not yet encountered such a reason.</p>
| 10 | 2016-01-01T19:55:14Z | [
"python",
"global-variables",
"scope"
]
|
Using global variables in a function other than the one that created them | 423,379 | <p>If I create a global variable in one function, how can I use that variable in another function?<br>
Do I need to store the global variable in a local variable of the function which needs its access?</p>
| 1,686 | 2009-01-08T05:45:02Z | 34,664,752 | <p>Writing to explicit elements of a global array does not apparently need the global declaration, though writing to it "wholesale" does have that requirement:</p>
<pre><code>import numpy as np
hostValue = 3.14159
hostArray = np.array([2., 3.])
hostMatrix = np.array([[1.0, 0.0],[ 0.0, 1.0]])
def func1():
global hostValue # mandatory, else local.
hostValue = 2.0
def func2():
global hostValue # mandatory, else UnboundLocalError.
hostValue += 1.0
def func3():
global hostArray # mandatory, else local.
hostArray = np.array([14., 15.])
def func4(): # no need for globals
hostArray[0] = 123.4
def func5(): # no need for globals
hostArray[1] += 1.0
def func6(): # no need for globals
hostMatrix[1][1] = 12.
def func7(): # no need for globals
hostMatrix[0][0] += 0.33
func1()
print "After func1(), hostValue = ", hostValue
func2()
print "After func2(), hostValue = ", hostValue
func3()
print "After func3(), hostArray = ", hostArray
func4()
print "After func4(), hostArray = ", hostArray
func5()
print "After func5(), hostArray = ", hostArray
func6()
print "After func6(), hostMatrix = \n", hostMatrix
func7()
print "After func7(), hostMatrix = \n", hostMatrix
</code></pre>
| 3 | 2016-01-07T20:41:19Z | [
"python",
"global-variables",
"scope"
]
|
Using global variables in a function other than the one that created them | 423,379 | <p>If I create a global variable in one function, how can I use that variable in another function?<br>
Do I need to store the global variable in a local variable of the function which needs its access?</p>
| 1,686 | 2009-01-08T05:45:02Z | 35,831,191 | <p>I've found that when you try to assign a global variable to something else inside a function, it doesn't usually work. As in:</p>
<pre><code>globalVar = 1
def functionname():
global globalVar
globalVar = 18
print globalVar
</code></pre>
<p>What works for me to change it is when I assign it <em>outside</em> of the function, as in:</p>
<pre><code>globalVar = 1
globalVar += 1
def functionname():
global globalVar
print globalVar
</code></pre>
<p>It works for me, but whatever.</p>
| -4 | 2016-03-06T19:04:21Z | [
"python",
"global-variables",
"scope"
]
|
long double returns and ctypes | 423,404 | <p>i have a c function which returns a <code>long double</code>. i'd like to call this function from python using ctypes, and it mostly works. setting <code>so.func.restype = c_longdouble</code> does the trick -- except that python's float type is a <code>c_double</code> so if the returned value is larger than a double, but well within the bounds of a long double, python still gets inf as the return value. i'm on a 64 bit processor and <code>sizeof(long double)</code> is 16.</p>
<p>any ideas on getting around this (e.g. using the decimal class or numpy) without modifying the c code?</p>
| 9 | 2009-01-08T06:00:48Z | 423,479 | <p>I'm not sure you can do it without modifying the C code. ctypes seems to have really bad support for <code>long double</code>s - you can't manipulate them like numbers at all, all you can do is convert them back and forth between the native <code>float</code> Python type.</p>
<p>You can't even use a byte array as the return value instead of a <code>c_longdouble</code>, because of the ABI - floating-point values aren't returned in the <code>%eax</code> register or on the stack like normal return values, they're passed through the hardware-specific floating-point registers.</p>
| 1 | 2009-01-08T06:56:41Z | [
"python",
"ctypes"
]
|
long double returns and ctypes | 423,404 | <p>i have a c function which returns a <code>long double</code>. i'd like to call this function from python using ctypes, and it mostly works. setting <code>so.func.restype = c_longdouble</code> does the trick -- except that python's float type is a <code>c_double</code> so if the returned value is larger than a double, but well within the bounds of a long double, python still gets inf as the return value. i'm on a 64 bit processor and <code>sizeof(long double)</code> is 16.</p>
<p>any ideas on getting around this (e.g. using the decimal class or numpy) without modifying the c code?</p>
| 9 | 2009-01-08T06:00:48Z | 423,491 | <p>If you need high-precision floating point, have a look at GMPY.</p>
<p><a href="http://code.google.com/p/gmpy/" rel="nofollow">GMPY</a> is a C-coded Python extension module that wraps the GMP library to provide to Python code fast multiprecision arithmetic (integer, rational, and float), random number generation, advanced number-theoretical functions, and more.</p>
<p><a href="http://gmplib.org/#FUNCCLASSES" rel="nofollow">GMP</a> contains high-level floating-point arithmetic functions (<code>mpf</code>). This is the GMP function category to use if the C type `double' doesn't give enough precision for an application. There are about 65 functions in this category.</p>
| 0 | 2009-01-08T07:08:54Z | [
"python",
"ctypes"
]
|
long double returns and ctypes | 423,404 | <p>i have a c function which returns a <code>long double</code>. i'd like to call this function from python using ctypes, and it mostly works. setting <code>so.func.restype = c_longdouble</code> does the trick -- except that python's float type is a <code>c_double</code> so if the returned value is larger than a double, but well within the bounds of a long double, python still gets inf as the return value. i'm on a 64 bit processor and <code>sizeof(long double)</code> is 16.</p>
<p>any ideas on getting around this (e.g. using the decimal class or numpy) without modifying the c code?</p>
| 9 | 2009-01-08T06:00:48Z | 28,994,452 | <p>If you have a function return a <em>subclass</em> of <code>c_longdouble</code>, it will return the ctypes wrapped field object rather than converting to a python <code>float</code>. You can then extract the bytes from this (with <code>memcpy</code> into a c_char array, for example) or pass the object to another C function for further processing. The <code>snprintf</code> function can format it into a string for printing or conversion into a high-precision python numeric type.</p>
<pre><code>import ctypes
libc = ctypes.cdll['libc.so.6']
libm = ctypes.cdll['libm.so.6']
class my_longdouble(ctypes.c_longdouble):
def __str__(self):
size = 100
buf = (ctypes.c_char * size)()
libc.snprintf(buf, size, '%.35Le', self)
return buf[:].rstrip('\0')
powl = libm.powl
powl.restype = my_longdouble
powl.argtypes = [ctypes.c_longdouble, ctypes.c_longdouble]
for i in range(1020,1030):
res = powl(2,i)
print '2**'+str(i), '=', str(res)
</code></pre>
<p>Output:</p>
<pre><code>2**1020 = 1.12355820928894744233081574424314046e+307
2**1021 = 2.24711641857789488466163148848628092e+307
2**1022 = 4.49423283715578976932326297697256183e+307
2**1023 = 8.98846567431157953864652595394512367e+307
2**1024 = 1.79769313486231590772930519078902473e+308
2**1025 = 3.59538626972463181545861038157804947e+308
2**1026 = 7.19077253944926363091722076315609893e+308
2**1027 = 1.43815450788985272618344415263121979e+309
2**1028 = 2.87630901577970545236688830526243957e+309
2**1029 = 5.75261803155941090473377661052487915e+309
</code></pre>
<p>(Note that my estimate of 35 digits of precision turned out to be excessively optimistic for <code>long double</code> calculations on Intel processors, which only have 64 bits of mantissa. You should use <code>%a</code> rather than <code>%e</code>/<code>f</code>/<code>g</code> if you intend to convert to a format that is not based on decimal representation.)</p>
| 1 | 2015-03-11T18:21:36Z | [
"python",
"ctypes"
]
|
How to save inline formset models in Django? | 423,437 | <p>Formsets have a .save() method, and the <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view" rel="nofollow">documentation</a> says to save in views like this:</p>
<pre><code>if request.method == "POST":
formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
if formset.is_valid():
formset.save()
# Do something.
else:
formset = BookInlineFormSet(instance=author)
</code></pre>
<p>I am following this, and it works when the parent is created, but I'm getting an exception in Django when it is saving existing models. The parent actually is saved to the database and the exception occurs when saving related models.</p>
<pre><code>KeyError at /bcdetails/NewProds/1/
None
Request Method: POST
Request URL: http://rdif.local/bcdetails/NewProds/1/
Exception Type: KeyError
Exception Value:
None
Exception Location: /usr/lib/python2.5/site-packages/django/forms/models.py in save_existing_objects, line 403
Python Executable: /usr/bin/python
Python Version: 2.5.2
Python Path: ['/usr/lib/python2.5/site-packages/paramiko-1.7.4-py2.5.egg', '/usr/lib/python2.5/site-packages/Fabric-0.0.9-py2.5.egg', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0', '/usr/lib/site-python', '/home/www/rdif.com/test/']
Server time: Wed, 7 Jan 2009 23:18:19 -0700
</code></pre>
<p>I spent some time in Django source but can't find anything there. Do I need to iterate through each formset and only save models that have changed?</p>
| 3 | 2009-01-08T06:28:41Z | 423,804 | <p>I discovered my problem, and it's embarrassing.</p>
<p>In the parent model form I had <code>exclude = ('...',)</code> in the Meta class, and one of the excluded fields was critical for the relations in the inline_formsets. So, I've removed the excludes and ignoring those fields in the template.</p>
| 4 | 2009-01-08T10:27:55Z | [
"python",
"django",
"django-forms"
]
|
Python unittest with expensive setup | 423,483 | <p>My test file is basically:</p>
<pre><code>class Test(unittest.TestCase):
def testOk():
pass
if __name__ == "__main__":
expensiveSetup()
try:
unittest.main()
finally:
cleanUp()
</code></pre>
<p>However, I do wish to run my test through Netbeans testing tools, and to do that I need unittests that don't rely on an environment setup done in <strong>main</strong>. Looking at <a href="http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest">http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest</a> - it recommends using Nose. However, I don't think Netbeans supports this. I didn't find any information indicating that it does. Additionally, I am the only one here actually writing tests, so I don't want to introduce additional dependencies for the other 2 developers unless they are needed.</p>
<p>How can I do the setup and cleanup once for all the tests in my TestSuite?</p>
<p>The expensive setup here is creating some files with dummy data, as well as setting up and tearing down a simple xml-rpc server. I also have 2 test classes, one testing locally and one testing all methods over xml-rpc.</p>
| 18 | 2009-01-08T07:00:36Z | 423,569 | <p>You can save the state if <code>expensiveSetup()</code> is run or not.</p>
<pre><code>__expensiveSetup_has_run = False
class ExpensiveSetupMixin(unittest.TestCase):
def setUp(self):
global __expensiveSetup_has_run
super(ExpensiveSetupMixin, self).setUp()
if __expensiveSetup_has_run is False:
expensiveSetup()
__expensiveSetup_has_run = True
</code></pre>
<p>Or some kind of variation of this. Maybe pinging xml-rpc server and create a new one if it isn't answering.</p>
<p>But the unit-testing way AFAIK is to <strong>setup and teardown per unittest</strong> even if it is expensive.</p>
| 2 | 2009-01-08T08:08:44Z | [
"python",
"unit-testing"
]
|
Python unittest with expensive setup | 423,483 | <p>My test file is basically:</p>
<pre><code>class Test(unittest.TestCase):
def testOk():
pass
if __name__ == "__main__":
expensiveSetup()
try:
unittest.main()
finally:
cleanUp()
</code></pre>
<p>However, I do wish to run my test through Netbeans testing tools, and to do that I need unittests that don't rely on an environment setup done in <strong>main</strong>. Looking at <a href="http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest">http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest</a> - it recommends using Nose. However, I don't think Netbeans supports this. I didn't find any information indicating that it does. Additionally, I am the only one here actually writing tests, so I don't want to introduce additional dependencies for the other 2 developers unless they are needed.</p>
<p>How can I do the setup and cleanup once for all the tests in my TestSuite?</p>
<p>The expensive setup here is creating some files with dummy data, as well as setting up and tearing down a simple xml-rpc server. I also have 2 test classes, one testing locally and one testing all methods over xml-rpc.</p>
| 18 | 2009-01-08T07:00:36Z | 423,887 | <p>You can assure <code>setUp</code> and <code>tearDown</code> execute once if you have only one test method, <code>runTest</code>. This method can do whatever else it wants. Just be sure you don't have any methods with names that start with <code>test</code>.</p>
<pre><code>class MyExpensiveTest( unittest.TestCase ):
def setUp( self ):
self.resource = owThatHurts()
def tearDown( self ):
self.resource.flush()
self.resource.finish()
def runTest( self ):
self.runTest1()
self.tunTest2()
def runTest1( self ):
self.assertEquals(...)
def runTest2( self ):
self.assertEquals(...)
</code></pre>
<p>It doesn't automagically figure out what to run. If you add a test method, you also have to update runTest. </p>
| -2 | 2009-01-08T11:03:35Z | [
"python",
"unit-testing"
]
|
Python unittest with expensive setup | 423,483 | <p>My test file is basically:</p>
<pre><code>class Test(unittest.TestCase):
def testOk():
pass
if __name__ == "__main__":
expensiveSetup()
try:
unittest.main()
finally:
cleanUp()
</code></pre>
<p>However, I do wish to run my test through Netbeans testing tools, and to do that I need unittests that don't rely on an environment setup done in <strong>main</strong>. Looking at <a href="http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest">http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest</a> - it recommends using Nose. However, I don't think Netbeans supports this. I didn't find any information indicating that it does. Additionally, I am the only one here actually writing tests, so I don't want to introduce additional dependencies for the other 2 developers unless they are needed.</p>
<p>How can I do the setup and cleanup once for all the tests in my TestSuite?</p>
<p>The expensive setup here is creating some files with dummy data, as well as setting up and tearing down a simple xml-rpc server. I also have 2 test classes, one testing locally and one testing all methods over xml-rpc.</p>
| 18 | 2009-01-08T07:00:36Z | 424,438 | <p>First of all, what S. Lott said. However!, you do not want to do that. There is a reason setUp and tearDown are wrapped around each test: they help preserve the determinism of testing.</p>
<p>Otherwise, if some test places the system in a bad state, your next tests may fail. Ideally, each of your tests should be independent.</p>
<p>Also, if you insist on doing it this way, instead of writing by hand self.runTest1(), self.runTest2(), you might want to do a bit of introspection in order to find the methods to run.</p>
| 5 | 2009-01-08T14:35:18Z | [
"python",
"unit-testing"
]
|
Python unittest with expensive setup | 423,483 | <p>My test file is basically:</p>
<pre><code>class Test(unittest.TestCase):
def testOk():
pass
if __name__ == "__main__":
expensiveSetup()
try:
unittest.main()
finally:
cleanUp()
</code></pre>
<p>However, I do wish to run my test through Netbeans testing tools, and to do that I need unittests that don't rely on an environment setup done in <strong>main</strong>. Looking at <a href="http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest">http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest</a> - it recommends using Nose. However, I don't think Netbeans supports this. I didn't find any information indicating that it does. Additionally, I am the only one here actually writing tests, so I don't want to introduce additional dependencies for the other 2 developers unless they are needed.</p>
<p>How can I do the setup and cleanup once for all the tests in my TestSuite?</p>
<p>The expensive setup here is creating some files with dummy data, as well as setting up and tearing down a simple xml-rpc server. I also have 2 test classes, one testing locally and one testing all methods over xml-rpc.</p>
| 18 | 2009-01-08T07:00:36Z | 425,483 | <p>If you use Python >= 2.7 (or <a href="http://pypi.python.org/pypi/unittest2">unittest2</a> for Python >= 2.4 & <= 2.6), the best approach would be be to use </p>
<pre><code>def setUpClass(cls):
# ...
setUpClass = classmethod(setUpClass)
</code></pre>
<p>to perform some initialization once for all tests belonging to the given class.</p>
<p>And to perform the cleanup, use:</p>
<pre><code>@classmethod
def tearDownClass(cls):
# ...
</code></pre>
<p>See also the unittest standard library <a href="http://docs.python.org/py3k/library/unittest.html#setupclass-and-teardownclass">documentation on setUpClass and tearDownClass classmethods</a>.</p>
| 21 | 2009-01-08T19:12:44Z | [
"python",
"unit-testing"
]
|
Python unittest with expensive setup | 423,483 | <p>My test file is basically:</p>
<pre><code>class Test(unittest.TestCase):
def testOk():
pass
if __name__ == "__main__":
expensiveSetup()
try:
unittest.main()
finally:
cleanUp()
</code></pre>
<p>However, I do wish to run my test through Netbeans testing tools, and to do that I need unittests that don't rely on an environment setup done in <strong>main</strong>. Looking at <a href="http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest">http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest</a> - it recommends using Nose. However, I don't think Netbeans supports this. I didn't find any information indicating that it does. Additionally, I am the only one here actually writing tests, so I don't want to introduce additional dependencies for the other 2 developers unless they are needed.</p>
<p>How can I do the setup and cleanup once for all the tests in my TestSuite?</p>
<p>The expensive setup here is creating some files with dummy data, as well as setting up and tearing down a simple xml-rpc server. I also have 2 test classes, one testing locally and one testing all methods over xml-rpc.</p>
| 18 | 2009-01-08T07:00:36Z | 431,932 | <p>Won't package-level initialization do it for you? From the <a href="https://nose.readthedocs.org/en/latest/writing_tests.html?highlight=setup_package" rel="nofollow">Nose Wiki</a>:</p>
<blockquote>
<p>nose allows tests to be grouped into
test packages. This allows
package-level setup; for instance, if
you need to create a test database or
other data fixture for your tests, you
may create it in package setup and
remove it in package teardown once per
test run, rather than having to create
and tear it down once per test module
or test case.</p>
<p>To create package-level setup and
teardown methods, define setup and/or
teardown functions in the <code>__init__.py</code>
of a test package. Setup methods may
be named <code>setup</code>, <code>setup_package</code>, <code>setUp</code>,
or <code>setUpPackage</code>; teardown may be named
<code>teardown</code>, <code>teardown_package</code>, <code>tearDown</code>
or <code>tearDownPackage</code>. Execution of tests
in a test package begins as soon as
the first test module is loaded from
the test package.</p>
</blockquote>
| 3 | 2009-01-10T23:07:09Z | [
"python",
"unit-testing"
]
|
Python unittest with expensive setup | 423,483 | <p>My test file is basically:</p>
<pre><code>class Test(unittest.TestCase):
def testOk():
pass
if __name__ == "__main__":
expensiveSetup()
try:
unittest.main()
finally:
cleanUp()
</code></pre>
<p>However, I do wish to run my test through Netbeans testing tools, and to do that I need unittests that don't rely on an environment setup done in <strong>main</strong>. Looking at <a href="http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest">http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest</a> - it recommends using Nose. However, I don't think Netbeans supports this. I didn't find any information indicating that it does. Additionally, I am the only one here actually writing tests, so I don't want to introduce additional dependencies for the other 2 developers unless they are needed.</p>
<p>How can I do the setup and cleanup once for all the tests in my TestSuite?</p>
<p>The expensive setup here is creating some files with dummy data, as well as setting up and tearing down a simple xml-rpc server. I also have 2 test classes, one testing locally and one testing all methods over xml-rpc.</p>
| 18 | 2009-01-08T07:00:36Z | 4,577,724 | <p>This is what I do:</p>
<pre><code>class TestSearch(unittest.TestCase):
"""General Search tests for...."""
matcher = None
counter = 0
num_of_tests = None
def setUp(self): # pylint: disable-msg=C0103
"""Only instantiate the matcher once"""
if self.matcher is None:
self.__class__.matcher = Matcher()
self.__class__.num_of_tests = len(filter(self.isTestMethod, dir(self)))
self.__class__.counter = self.counter + 1
def tearDown(self): # pylint: disable-msg=C0103
"""And kill it when done"""
if self.counter == self.num_of_tests:
print 'KILL KILL KILL'
del self.__class__.matcher
</code></pre>
<p>Sadly (because I do want my tests to be independent and deterministic), I do this a lot (because system testing that take less than 5 minutes are also important).</p>
| 5 | 2011-01-02T08:31:13Z | [
"python",
"unit-testing"
]
|
Python unittest with expensive setup | 423,483 | <p>My test file is basically:</p>
<pre><code>class Test(unittest.TestCase):
def testOk():
pass
if __name__ == "__main__":
expensiveSetup()
try:
unittest.main()
finally:
cleanUp()
</code></pre>
<p>However, I do wish to run my test through Netbeans testing tools, and to do that I need unittests that don't rely on an environment setup done in <strong>main</strong>. Looking at <a href="http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest">http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest</a> - it recommends using Nose. However, I don't think Netbeans supports this. I didn't find any information indicating that it does. Additionally, I am the only one here actually writing tests, so I don't want to introduce additional dependencies for the other 2 developers unless they are needed.</p>
<p>How can I do the setup and cleanup once for all the tests in my TestSuite?</p>
<p>The expensive setup here is creating some files with dummy data, as well as setting up and tearing down a simple xml-rpc server. I also have 2 test classes, one testing locally and one testing all methods over xml-rpc.</p>
| 18 | 2009-01-08T07:00:36Z | 4,578,214 | <p>I know nothing about Netbeans, but I though I should mention <a href="http://pypi.python.org/pypi/zope.testrunner" rel="nofollow">zope.testrunner</a> and it's support for a nifty thing: Layers. Basically, you do the testsetup in separate classes, and attach those classes to the tests. These classes can inherit from each other, forming a layer of setups. The testrunner will then only call each setup once, and saving the state of that in memory, and instead of setting up and tearing down, it will simply just copy the relevant layer context as a setup.</p>
<p>This speeds up test setup a lot, and is used when you test Zope products and Plone, where the testsetup often needs you to start a Plone CMS server, create a Plone site and add loads of content, a process that can take upwards half a minute. Doing that for each test method is obviously impossible, but with layers it is done only once. This shortens the test setup <em>and</em> protects the test methods from each other, and therefore means that the testing continues to be determenistic.</p>
<p>So I don't know of zope.testrunner will work for you, but it's worth a try.</p>
| 0 | 2011-01-02T11:43:59Z | [
"python",
"unit-testing"
]
|
Python and different Operating Systems | 425,343 | <p>I am about to start a personal project using python and I will be using it on both Linux(Fedora) and Windows(Vista), Although I might as well make it work on a mac while im at it. I have found an API for the GUI that will work on all 3. The reason I am asking is because I have always heard of small differences that are easily avoided if you know about them before starting. Does anyone have any tips or suggestions that fall along these lines?</p>
| 4 | 2009-01-08T18:38:09Z | 425,383 | <p>In general:</p>
<ul>
<li>Be careful with paths. Use os.path wherever possible.</li>
<li>Don't assume that HOME points to the user's home/profile directory.</li>
<li>Avoid using things like unix-domain sockets, fifos, and other POSIX-specific stuff.</li>
</ul>
<p>More specific stuff:</p>
<ul>
<li>If you're using wxPython, note that there may be differences in things like which thread certain events are generated in. Don't assume that events are generated in a specific thread. If you're calling a method which triggers a GUI-event, don't assume that event-handlers have completed by the time your method returns. (And vice versa, of course.)</li>
<li>There are always differences in how a GUI will appear. Layouts are not always implemented in the exact same way.</li>
</ul>
| 4 | 2009-01-08T18:49:31Z | [
"python",
"cross-platform"
]
|
Python and different Operating Systems | 425,343 | <p>I am about to start a personal project using python and I will be using it on both Linux(Fedora) and Windows(Vista), Although I might as well make it work on a mac while im at it. I have found an API for the GUI that will work on all 3. The reason I am asking is because I have always heard of small differences that are easily avoided if you know about them before starting. Does anyone have any tips or suggestions that fall along these lines?</p>
| 4 | 2009-01-08T18:38:09Z | 425,403 | <ol>
<li><p>You should take care of the Python version you are developing against. Especially, on a Mac, the default version of Python installed with the OS, is rather old (of course, newer versions can be installed)</p></li>
<li><p>Don't use the OS specific libraries</p></li>
<li><p>Take special care of 'special' UI elements, like taskbar icons (windows), ...</p></li>
<li><p>Use forward slashes when using paths, avoid C:/, /home/..., ... Use os.path to work with paths.</p></li>
</ol>
| 1 | 2009-01-08T18:55:12Z | [
"python",
"cross-platform"
]
|
Python and different Operating Systems | 425,343 | <p>I am about to start a personal project using python and I will be using it on both Linux(Fedora) and Windows(Vista), Although I might as well make it work on a mac while im at it. I have found an API for the GUI that will work on all 3. The reason I am asking is because I have always heard of small differences that are easily avoided if you know about them before starting. Does anyone have any tips or suggestions that fall along these lines?</p>
| 4 | 2009-01-08T18:38:09Z | 425,409 | <p>Some things I've noticed in my cross platform development in Python:</p>
<ul>
<li>OSX doesn't have a tray, so application notifications usually happen right in the dock. So if you're building a background notification service you may need a small amount of platform-specific code.</li>
<li>os.startfile() apparently only works on Windows. Either that or Python 2.5.1 on Leopard doesn't support it.</li>
<li>os.normpath() is something you might want to consider using too, just to keep your paths and volumes using the correct slash notation and volume names.</li>
<li>icons are dealt with in fundamentally different ways in Windows and OSX, be sure you provide icons at all the right sizes for both (16x16, 24x24, 32x32, 48x48, 64x64, 128x128 and 256x256) and be sure to read up on setting up icons with wx widgets.</li>
</ul>
| 3 | 2009-01-08T18:56:46Z | [
"python",
"cross-platform"
]
|
Python and different Operating Systems | 425,343 | <p>I am about to start a personal project using python and I will be using it on both Linux(Fedora) and Windows(Vista), Although I might as well make it work on a mac while im at it. I have found an API for the GUI that will work on all 3. The reason I am asking is because I have always heard of small differences that are easily avoided if you know about them before starting. Does anyone have any tips or suggestions that fall along these lines?</p>
| 4 | 2009-01-08T18:38:09Z | 425,465 | <p>Some filename problems: This.File and this.file are different files on Linux, but point to the same file on Windows. Troublesome if you manage some file repository and access it from both platforms. Less frequent related problem is that of names like NUL or LPT being files on Windows.</p>
<p>Binary distribution code (if any) would likely use py2exe on Win, py2app on Mac and wouldn't be present on Linux.</p>
| 0 | 2009-01-08T19:08:40Z | [
"python",
"cross-platform"
]
|
Best Way To Determine if a Sequence is in another sequence in Python | 425,604 | <p>This is a generalization of the "string contains substring" problem to (more) arbitrary types.</p>
<p>Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts:</p>
<p>Example usage (Sequence in Sequence):</p>
<pre><code>>>> seq_in_seq([5,6], [4,'a',3,5,6])
3
>>> seq_in_seq([5,7], [4,'a',3,5,6])
-1 # or None, or whatever
</code></pre>
<p>So far, I just rely on brute force and it seems slow, ugly, and clumsy.</p>
| 15 | 2009-01-08T19:46:10Z | 425,622 | <p>Brute force may be fine for small patterns.</p>
<p>For larger ones, look at the <a href="http://en.wikipedia.org/wiki/Aho-Corasick_algorithm" rel="nofollow">Aho-Corasick algorithm</a>.</p>
| 1 | 2009-01-08T19:51:19Z | [
"python",
"algorithm",
"sequence"
]
|
Best Way To Determine if a Sequence is in another sequence in Python | 425,604 | <p>This is a generalization of the "string contains substring" problem to (more) arbitrary types.</p>
<p>Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts:</p>
<p>Example usage (Sequence in Sequence):</p>
<pre><code>>>> seq_in_seq([5,6], [4,'a',3,5,6])
3
>>> seq_in_seq([5,7], [4,'a',3,5,6])
-1 # or None, or whatever
</code></pre>
<p>So far, I just rely on brute force and it seems slow, ugly, and clumsy.</p>
| 15 | 2009-01-08T19:46:10Z | 425,677 | <p>Same thing as string matching sir...<a href="http://www.ics.uci.edu/~eppstein/161/960227.html" rel="nofollow">Knuth-Morris-Pratt string matching</a></p>
| 5 | 2009-01-08T20:05:09Z | [
"python",
"algorithm",
"sequence"
]
|
Best Way To Determine if a Sequence is in another sequence in Python | 425,604 | <p>This is a generalization of the "string contains substring" problem to (more) arbitrary types.</p>
<p>Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts:</p>
<p>Example usage (Sequence in Sequence):</p>
<pre><code>>>> seq_in_seq([5,6], [4,'a',3,5,6])
3
>>> seq_in_seq([5,7], [4,'a',3,5,6])
-1 # or None, or whatever
</code></pre>
<p>So far, I just rely on brute force and it seems slow, ugly, and clumsy.</p>
| 15 | 2009-01-08T19:46:10Z | 425,764 | <pre><code>>>> def seq_in_seq(subseq, seq):
... while subseq[0] in seq:
... index = seq.index(subseq[0])
... if subseq == seq[index:index + len(subseq)]:
... return index
... else:
... seq = seq[index + 1:]
... else:
... return -1
...
>>> seq_in_seq([5,6], [4,'a',3,5,6])
3
>>> seq_in_seq([5,7], [4,'a',3,5,6])
-1
</code></pre>
<p>Sorry I'm not an algorithm expert, it's just the fastest thing my mind can think about at the moment, at least I think it looks nice (to me) and I had fun coding it. ;-)</p>
<p>Most probably it's the same thing your brute force approach is doing.</p>
| 1 | 2009-01-08T20:26:54Z | [
"python",
"algorithm",
"sequence"
]
|
Best Way To Determine if a Sequence is in another sequence in Python | 425,604 | <p>This is a generalization of the "string contains substring" problem to (more) arbitrary types.</p>
<p>Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts:</p>
<p>Example usage (Sequence in Sequence):</p>
<pre><code>>>> seq_in_seq([5,6], [4,'a',3,5,6])
3
>>> seq_in_seq([5,7], [4,'a',3,5,6])
-1 # or None, or whatever
</code></pre>
<p>So far, I just rely on brute force and it seems slow, ugly, and clumsy.</p>
| 15 | 2009-01-08T19:46:10Z | 425,825 | <p>I second the Knuth-Morris-Pratt algorithm. By the way, your problem (and the KMP solution) is exactly recipe 5.13 in <a href="http://rads.stackoverflow.com/amzn/click/0596007973">Python Cookbook</a> 2nd edition. You can find the related code at <a href="http://code.activestate.com/recipes/117214/">http://code.activestate.com/recipes/117214/</a></p>
<p>It finds <em>all</em> the correct subsequences in a given sequence, and should be used as an iterator:</p>
<pre><code>>>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,6]): print s
3
>>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,7]): print s
(nothing)
</code></pre>
| 14 | 2009-01-08T20:42:46Z | [
"python",
"algorithm",
"sequence"
]
|
Best Way To Determine if a Sequence is in another sequence in Python | 425,604 | <p>This is a generalization of the "string contains substring" problem to (more) arbitrary types.</p>
<p>Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts:</p>
<p>Example usage (Sequence in Sequence):</p>
<pre><code>>>> seq_in_seq([5,6], [4,'a',3,5,6])
3
>>> seq_in_seq([5,7], [4,'a',3,5,6])
-1 # or None, or whatever
</code></pre>
<p>So far, I just rely on brute force and it seems slow, ugly, and clumsy.</p>
| 15 | 2009-01-08T19:46:10Z | 425,838 | <p>Here is another KMP implementation:</p>
<pre><code>from itertools import tee
def seq_in_seq(seq1,seq2):
'''
Return the index where seq1 appears in seq2, or -1 if
seq1 is not in seq2, using the Knuth-Morris-Pratt algorithm
based heavily on code by Neale Pickett <neale@woozle.org>
found at: woozle.org/~neale/src/python/kmp.py
>>> seq_in_seq(range(3),range(5))
0
>>> seq_in_seq(range(3)[-1:],range(5))
2
>>>seq_in_seq(range(6),range(5))
-1
'''
def compute_prefix_function(p):
m = len(p)
pi = [0] * m
k = 0
for q in xrange(1, m):
while k > 0 and p[k] != p[q]:
k = pi[k - 1]
if p[k] == p[q]:
k = k + 1
pi[q] = k
return pi
t,p = list(tee(seq2)[0]), list(tee(seq1)[0])
m,n = len(p),len(t)
pi = compute_prefix_function(p)
q = 0
for i in range(n):
while q > 0 and p[q] != t[i]:
q = pi[q - 1]
if p[q] == t[i]:
q = q + 1
if q == m:
return i - m + 1
return -1
</code></pre>
| 0 | 2009-01-08T20:44:55Z | [
"python",
"algorithm",
"sequence"
]
|
Best Way To Determine if a Sequence is in another sequence in Python | 425,604 | <p>This is a generalization of the "string contains substring" problem to (more) arbitrary types.</p>
<p>Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts:</p>
<p>Example usage (Sequence in Sequence):</p>
<pre><code>>>> seq_in_seq([5,6], [4,'a',3,5,6])
3
>>> seq_in_seq([5,7], [4,'a',3,5,6])
-1 # or None, or whatever
</code></pre>
<p>So far, I just rely on brute force and it seems slow, ugly, and clumsy.</p>
| 15 | 2009-01-08T19:46:10Z | 426,168 | <p>Here's a brute-force approach <code>O(n*m)</code> (similar to <a href="http://stackoverflow.com/questions/425604/best-way-to-determine-if-a-sequence-is-in-another-sequence-in-python#425764">@mcella's answer</a>). It might be faster then the Knuth-Morris-Pratt algorithm implementation in pure Python <code>O(n+m)</code> (see <a href="http://stackoverflow.com/questions/425604/best-way-to-determine-if-a-sequence-is-in-another-sequence-in-python#425838">@Gregg Lind answer</a>) for <em>small</em> input sequences.</p>
<pre><code>#!/usr/bin/env python
def index(subseq, seq):
"""Return an index of `subseq`uence in the `seq`uence.
Or `-1` if `subseq` is not a subsequence of the `seq`.
The time complexity of the algorithm is O(n*m), where
n, m = len(seq), len(subseq)
>>> index([1,2], range(5))
1
>>> index(range(1, 6), range(5))
-1
>>> index(range(5), range(5))
0
>>> index([1,2], [0, 1, 0, 1, 2])
3
"""
i, n, m = -1, len(seq), len(subseq)
try:
while True:
i = seq.index(subseq[0], i + 1, n - m + 1)
if subseq == seq[i:i + m]:
return i
except ValueError:
return -1
if __name__ == '__main__':
import doctest; doctest.testmod()
</code></pre>
<p>I wonder how large is the <em>small</em> in this case?</p>
| 3 | 2009-01-08T21:55:59Z | [
"python",
"algorithm",
"sequence"
]
|
Best Way To Determine if a Sequence is in another sequence in Python | 425,604 | <p>This is a generalization of the "string contains substring" problem to (more) arbitrary types.</p>
<p>Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts:</p>
<p>Example usage (Sequence in Sequence):</p>
<pre><code>>>> seq_in_seq([5,6], [4,'a',3,5,6])
3
>>> seq_in_seq([5,7], [4,'a',3,5,6])
-1 # or None, or whatever
</code></pre>
<p>So far, I just rely on brute force and it seems slow, ugly, and clumsy.</p>
| 15 | 2009-01-08T19:46:10Z | 29,424,456 | <p>A simple approach: Convert to strings and rely on string matching.</p>
<p>Example using lists of strings:</p>
<pre><code> >>> f = ["foo", "bar", "baz"]
>>> g = ["foo", "bar"]
>>> ff = str(f).strip("[]")
>>> gg = str(g).strip("[]")
>>> gg in ff
True
</code></pre>
<p>Example using tuples of strings:</p>
<pre><code>>>> x = ("foo", "bar", "baz")
>>> y = ("bar", "baz")
>>> xx = str(x).strip("()")
>>> yy = str(y).strip("()")
>>> yy in xx
True
</code></pre>
<p>Example using lists of numbers:</p>
<pre><code>>>> f = [1 , 2, 3, 4, 5, 6, 7]
>>> g = [4, 5, 6]
>>> ff = str(f).strip("[]")
>>> gg = str(g).strip("[]")
>>> gg in ff
True
</code></pre>
| 1 | 2015-04-03T00:07:40Z | [
"python",
"algorithm",
"sequence"
]
|
Best Way To Determine if a Sequence is in another sequence in Python | 425,604 | <p>This is a generalization of the "string contains substring" problem to (more) arbitrary types.</p>
<p>Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts:</p>
<p>Example usage (Sequence in Sequence):</p>
<pre><code>>>> seq_in_seq([5,6], [4,'a',3,5,6])
3
>>> seq_in_seq([5,7], [4,'a',3,5,6])
-1 # or None, or whatever
</code></pre>
<p>So far, I just rely on brute force and it seems slow, ugly, and clumsy.</p>
| 15 | 2009-01-08T19:46:10Z | 34,059,337 | <p>Another approach, using sets:</p>
<pre><code>set([5,6])== set([5,6])&set([4,'a',3,5,6])
True
</code></pre>
| -1 | 2015-12-03T06:36:22Z | [
"python",
"algorithm",
"sequence"
]
|
Drag button between panels in wxPython | 425,722 | <p>Does anyone know of an example where it is shown how to drag a button from one panel to another in wxPython?</p>
<p>I have created a bitmap button in a panel, and I would like to be able to drag it to a different panel and drop I there. </p>
<p>I haven't found any examples using buttons, just text and files.</p>
<p>I am using the latest version of Python and wxPython.</p>
| 1 | 2009-01-08T20:17:05Z | 425,740 | <p>If you want to graphically represent the drag, one good way to do this is to create a borderless Frame that follows the mouse during a drag. You remove the button from your source Frame, temporarily put it in this "drag Frame", and then, when the user drops, add it to your destination Frame.</p>
| 3 | 2009-01-08T20:21:50Z | [
"python",
"drag-and-drop",
"wxpython"
]
|
Django on IronPython | 425,990 | <p>I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? </p>
<p>If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?</p>
| 50 | 2009-01-08T21:16:01Z | 426,257 | <p><a href="http://blogs.msdn.com/dinoviehland/archive/2008/03/17/ironpython-ms-sql-and-pep-249.aspx">Here's a database provider that runs on .NET & that works with Django</a></p>
| 8 | 2009-01-08T22:20:23Z | [
"python",
"django",
"ironpython"
]
|
Django on IronPython | 425,990 | <p>I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? </p>
<p>If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?</p>
| 50 | 2009-01-08T21:16:01Z | 509,424 | <p>This was <a href="http://www.infoq.com/news/2008/03/django-and-ironpython" rel="nofollow">demoed</a> at last year's PyCon (the <a href="http://blogs.msdn.com/dinoviehland/archive/2008/03/17/ironpython-ms-sql-and-pep-249.aspx" rel="nofollow">details</a> are also available). More recently, <a href="http://jdhardy.blogspot.com/2008/12/django-ironpython.html" rel="nofollow">Jeff Hardy has blogged about this</a>, including suggestions.</p>
| 5 | 2009-02-03T23:17:20Z | [
"python",
"django",
"ironpython"
]
|
Django on IronPython | 425,990 | <p>I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? </p>
<p>If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?</p>
| 50 | 2009-01-08T21:16:01Z | 518,317 | <p>Besides the Jeff Hardy blog post on <a href="http://jdhardy.blogspot.com/2008/12/django-ironpython.html">Django + IronPython</a> mentioned by Tony Meyer, it might be useful to also read Jeff's two other posts in the same series on his struggles with IronPython, easy_install and zlib. The first is <a href="http://jdhardy.blogspot.com/2008/12/solving-zlib-problem-ironpythonzlib.html">Solving the zlib problem</a> which discusses the absence of zlib for IronPython; hence, no easyinstall. Jeff reimplemented zlib based on ComponentAce's zlib.net. And finally, in <a href="http://jdhardy.blogspot.com/2008/12/easyinstall-on-ironpython-part-deux.html">easy_install on IronPython, Part Deux</a> Jeff discusses some final tweaks that are needed before easy_install can be used with IronPython.</p>
| 25 | 2009-02-05T22:40:08Z | [
"python",
"django",
"ironpython"
]
|
Django on IronPython | 425,990 | <p>I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? </p>
<p>If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?</p>
| 50 | 2009-01-08T21:16:01Z | 3,870,431 | <p>I don't think Django is yet working on IronPython, but I'm not saying it cannot be done.</p>
<p><a href="http://bitbucket.org/jdhardy/django-ironpython/overview" rel="nofollow">Django-ironpython</a> project is a work currently underway to run Django on IronPython. The project has reported <a href="http://twitter.com/#!/djangoipy" rel="nofollow">65.7% test pass rate</a> with sqlite on 2nd of May 2010. </p>
| 2 | 2010-10-06T07:51:45Z | [
"python",
"django",
"ironpython"
]
|
How do I (successfully) decode a encoded password from command line openSSL? | 426,294 | <p>Using PyCrypto (although I've tried this in ObjC with OpenSSL bindings as well) :</p>
<pre><code>from Crypto.Cipher import DES
import base64
obj=DES.new('abcdefgh', DES.MODE_ECB)
plain="Guido van Rossum is a space alien.XXXXXX"
ciph=obj.encrypt(plain)
enc=base64.b64encode(ciph)
#print ciph
print enc
</code></pre>
<p>outputs a base64 encoded value of :</p>
<pre><code>ESzjTnGMRFnfVOJwQfqtyXOI8yzAatioyufiSdE1dx02McNkZ2IvBg==
</code></pre>
<p>If you were in the interpreter, ciph will give you</p>
<pre><code>'\x11,\xe3Nq\x8cDY\xdfT\xe2pA\xfa\xad\xc9s\x88\xf3,\xc0j\xd8\xa8\xca\xe7\xe2I\xd15w\x1d61\xc3dgb/\x06'
</code></pre>
<p>Easy enough. I should be able to pipe this output to OpenSSL and decode it : </p>
<p>I test to make sure that the b64 decode works - </p>
<pre><code>python enctest.py | openssl enc -base64 -d
+ python enctest.py
+ openssl enc -base64 -d
,?Nq?DY?T?pA???s??,?jب???I?5w61?dgb/
</code></pre>
<p>Not pretty, but you can see that it got decoded fine, "dgb" and "Nq" are still there.</p>
<p>But go for the full thing :</p>
<pre><code>python enctest.py | openssl enc -base64 -d | openssl enc -nosalt -des-ecb -d -pass pass:abcdefgh
+ python enctest.py
+ openssl enc -nosalt -des-ecb -d -pass pass:abcdefgh
+ openssl enc -base64 -d
bad decrypt
15621:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:461:
j?7????vc]???LE?m³??q?
</code></pre>
<p>What am I doing wrong? I've tried using -k abcdefgh -iv 0000000000000000 or typing in the password interactively - same problem.</p>
| 2 | 2009-01-08T22:30:01Z | 427,344 | <p><code>
echo ESzjTnGMRFnfVOJwQfqtyXOI8yzAatioyufiSdE1dx02McNkZ2IvBg== | openssl enc -nopad -a -des-ecb -K 6162636465666768 -iv 0 -p -d
</code></p>
<p>6162636465666768 is the ASCII "abcdefgh" written out in hexadecimal.</p>
<p>But note that DES in ECB mode is probably not a good way to encode passwords and also is not the "DES crypt" you may have heard of being used on Unix systems.
(For passwords, it is usually better to use a hard-to-reverse algorithm (checking the password by regenerating the result instead decrypting the stored password). Even if you do need to be able to decrypt these encrypted passwords, single-DES and especially ECB are poor choices as far as confidentiality is concerned.)</p>
| 3 | 2009-01-09T07:41:44Z | [
"python",
"linux",
"bash",
"encryption",
"openssl"
]
|
How to use the HTTPPasswordMgrWithDefaultRealm() in Python | 426,298 | <p>I need to write some python ftp code that uses a ftp proxy. The proxy doesn't require authentication but the ftp server I am connecting to does. I have the following code but I am getting a "I/O error(ftp error): 501 USER format: proxy-user:auth-method@destination. Closing connection." error. My code is:</p>
<pre><code>import urllib2
proxies = {'ftp':'ftp://proxy_server:21'}
ftp_server = ' ftp.somecompany.com '
ftp_port='21'
username = 'aaaa'
password = 'secretPW'
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm( )
top_level_url = ftp_server
password_mgr.add_password(None , top_level_url, username, password)
proxy_support = urllib2.ProxyHandler(proxies )
handler = urllib2.HTTPBasicAuthHandler(password_mgr )
opener = urllib2.build_opener(proxy_support )
opener = urllib2.build_opener(handler )
a_url = 'ftp://' + ftp_server + ':' + ftp_port + '/'
print a_url
try:
data = opener.open(a_url )
print data
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
</code></pre>
<p>I would be grateful for any assistance I can get. </p>
| 1 | 2009-01-08T22:32:07Z | 426,331 | <p>I use the following code block which seems similar except i include the protocol in the <code>top_level_url</code> I use (and of course it's http). </p>
<p>You might also try calling <code>install_opener</code> after each <code>build_opener</code> call and then using <code>urllib2.urlopen</code></p>
<pre><code>auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='RESTRICTED ACCESS',
uri='http://website.com',
user='username',
passwd='password')
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
urllib2.urlopen('http://website.com/....')
</code></pre>
| 2 | 2009-01-08T22:41:37Z | [
"python"
]
|
How to use the HTTPPasswordMgrWithDefaultRealm() in Python | 426,298 | <p>I need to write some python ftp code that uses a ftp proxy. The proxy doesn't require authentication but the ftp server I am connecting to does. I have the following code but I am getting a "I/O error(ftp error): 501 USER format: proxy-user:auth-method@destination. Closing connection." error. My code is:</p>
<pre><code>import urllib2
proxies = {'ftp':'ftp://proxy_server:21'}
ftp_server = ' ftp.somecompany.com '
ftp_port='21'
username = 'aaaa'
password = 'secretPW'
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm( )
top_level_url = ftp_server
password_mgr.add_password(None , top_level_url, username, password)
proxy_support = urllib2.ProxyHandler(proxies )
handler = urllib2.HTTPBasicAuthHandler(password_mgr )
opener = urllib2.build_opener(proxy_support )
opener = urllib2.build_opener(handler )
a_url = 'ftp://' + ftp_server + ':' + ftp_port + '/'
print a_url
try:
data = opener.open(a_url )
print data
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
</code></pre>
<p>I would be grateful for any assistance I can get. </p>
| 1 | 2009-01-08T22:32:07Z | 13,391,859 | <p>I think you need to change this:</p>
<pre><code> opener = urllib2.build_opener(proxy_support )
opener = urllib2.build_opener(handler )
</code></pre>
<p>to this:</p>
<pre><code> opener = urllib2.build_opener([proxy_support, handler])
</code></pre>
<p>That gives you one opener that has both your authentication and your proxy support. You only need to use <code>install_opener</code> if you want the custom opener to be used whenever <code>urllib2.urlopen</code> is called.</p>
| 0 | 2012-11-15T05:09:27Z | [
"python"
]
|
How do I mock the Python method OptionParser.error(), which does a sys.exit()? | 426,500 | <p>I'm trying to unit test some code that looks like this:</p>
<pre><code>def main():
parser = optparse.OptionParser(description='This tool is cool', prog='cool-tool')
parser.add_option('--foo', action='store', help='The foo option is self-explanatory')
options, arguments = parser.parse_args()
if not options.foo:
parser.error('--foo option is required')
print "Your foo is %s." % options.foo
return 0
if __name__ == '__main__':
sys.exit(main())
</code></pre>
<p>With code that looks like this:</p>
<pre><code>@patch('optparse.OptionParser')
def test_main_with_missing_p4clientsdir_option(self, mock_optionparser):
#
# setup
#
optionparser_mock = Mock()
mock_optionparser.return_value = optionparser_mock
options_stub = Mock()
options_stub.foo = None
optionparser_mock.parse_args.return_value = (options_stub, sentinel.arguments)
def parser_error_mock(message):
self.assertEquals(message, '--foo option is required')
sys.exit(2)
optionparser_mock.error = parser_error_mock
#
# exercise & verify
#
self.assertEquals(sut.main(), 2)
</code></pre>
<p>I'm using <a href="http://www.voidspace.org.uk/python/mock.html">Michael Foord's Mock</a>, and nose to run the tests.</p>
<p>When I run the test, I get:</p>
<pre><code> File "/Users/dspitzer/Programming/Python/test-optparse-error/tests/sut_tests.py", line 27, in parser_error_mock
sys.exit(2)
SystemExit: 2
----------------------------------------------------------------------
Ran 1 test in 0.012s
FAILED (errors=1)
</code></pre>
<p>The problem is that OptionParser.error does a sys.exit(2), and so main() naturally relies on that. But nose or unittest detects the (expected) sys.exit(2) and fails the test.</p>
<p>I can make the test pass by adding "return 2" under the parser.error() call in main() and removing the sys.exit() call from parser_error_mock(), but I find it distasteful to modify the code under test to allow a test to pass. Is there a better solution?</p>
<p><strong>Update</strong>: <a href="http://stackoverflow.com/users/3002/df">df</a>'s answer works, although the correct call is "self.assertRaises(SystemExit, sut.main)".</p>
<p>Which means the test passes whatever the number is in the sys.exit() in parser_error_mock(). Is there any way to test for the exit code?</p>
<p>BTW, the test is more robust if I add:</p>
<pre><code>self.assertEquals(optionparser_mock.method_calls, [('add_option', ('--foo',), {'action': 'store', 'help': 'The foo option is self-explanatory'}), ('parse_args', (), {})])
</code></pre>
<p>at the end.</p>
<p><strong>Update 2</strong>: I can test for the exit code by replacing "self.assertRaises(SystemExit, sut.main)" with:</p>
<pre><code>try:
sut.main()
except SystemExit, e:
self.assertEquals(type(e), type(SystemExit()))
self.assertEquals(e.code, 2)
except Exception, e:
self.fail('unexpected exception: %s' % e)
else:
self.fail('SystemExit exception expected')
</code></pre>
| 14 | 2009-01-08T23:37:31Z | 426,624 | <p>Will this work instead of <code>assertEquals</code>?</p>
<pre><code>self.assertRaises(SystemExit, sut.main, 2)
</code></pre>
<p>This should catch the <code>SystemExit</code> exception and prevent the script from terminating.</p>
| 12 | 2009-01-09T00:24:15Z | [
"python",
"unit-testing",
"mocking",
"optparse"
]
|
How do I mock the Python method OptionParser.error(), which does a sys.exit()? | 426,500 | <p>I'm trying to unit test some code that looks like this:</p>
<pre><code>def main():
parser = optparse.OptionParser(description='This tool is cool', prog='cool-tool')
parser.add_option('--foo', action='store', help='The foo option is self-explanatory')
options, arguments = parser.parse_args()
if not options.foo:
parser.error('--foo option is required')
print "Your foo is %s." % options.foo
return 0
if __name__ == '__main__':
sys.exit(main())
</code></pre>
<p>With code that looks like this:</p>
<pre><code>@patch('optparse.OptionParser')
def test_main_with_missing_p4clientsdir_option(self, mock_optionparser):
#
# setup
#
optionparser_mock = Mock()
mock_optionparser.return_value = optionparser_mock
options_stub = Mock()
options_stub.foo = None
optionparser_mock.parse_args.return_value = (options_stub, sentinel.arguments)
def parser_error_mock(message):
self.assertEquals(message, '--foo option is required')
sys.exit(2)
optionparser_mock.error = parser_error_mock
#
# exercise & verify
#
self.assertEquals(sut.main(), 2)
</code></pre>
<p>I'm using <a href="http://www.voidspace.org.uk/python/mock.html">Michael Foord's Mock</a>, and nose to run the tests.</p>
<p>When I run the test, I get:</p>
<pre><code> File "/Users/dspitzer/Programming/Python/test-optparse-error/tests/sut_tests.py", line 27, in parser_error_mock
sys.exit(2)
SystemExit: 2
----------------------------------------------------------------------
Ran 1 test in 0.012s
FAILED (errors=1)
</code></pre>
<p>The problem is that OptionParser.error does a sys.exit(2), and so main() naturally relies on that. But nose or unittest detects the (expected) sys.exit(2) and fails the test.</p>
<p>I can make the test pass by adding "return 2" under the parser.error() call in main() and removing the sys.exit() call from parser_error_mock(), but I find it distasteful to modify the code under test to allow a test to pass. Is there a better solution?</p>
<p><strong>Update</strong>: <a href="http://stackoverflow.com/users/3002/df">df</a>'s answer works, although the correct call is "self.assertRaises(SystemExit, sut.main)".</p>
<p>Which means the test passes whatever the number is in the sys.exit() in parser_error_mock(). Is there any way to test for the exit code?</p>
<p>BTW, the test is more robust if I add:</p>
<pre><code>self.assertEquals(optionparser_mock.method_calls, [('add_option', ('--foo',), {'action': 'store', 'help': 'The foo option is self-explanatory'}), ('parse_args', (), {})])
</code></pre>
<p>at the end.</p>
<p><strong>Update 2</strong>: I can test for the exit code by replacing "self.assertRaises(SystemExit, sut.main)" with:</p>
<pre><code>try:
sut.main()
except SystemExit, e:
self.assertEquals(type(e), type(SystemExit()))
self.assertEquals(e.code, 2)
except Exception, e:
self.fail('unexpected exception: %s' % e)
else:
self.fail('SystemExit exception expected')
</code></pre>
| 14 | 2009-01-08T23:37:31Z | 427,288 | <p>Probably this question contains some new information:</p>
<p><a href="http://stackoverflow.com/questions/309396/java-how-to-test-methods-that-call-system-exit">http://stackoverflow.com/questions/309396/java-how-to-test-methods-that-call-system-exit</a></p>
| 0 | 2009-01-09T07:09:48Z | [
"python",
"unit-testing",
"mocking",
"optparse"
]
|
How do I mock the Python method OptionParser.error(), which does a sys.exit()? | 426,500 | <p>I'm trying to unit test some code that looks like this:</p>
<pre><code>def main():
parser = optparse.OptionParser(description='This tool is cool', prog='cool-tool')
parser.add_option('--foo', action='store', help='The foo option is self-explanatory')
options, arguments = parser.parse_args()
if not options.foo:
parser.error('--foo option is required')
print "Your foo is %s." % options.foo
return 0
if __name__ == '__main__':
sys.exit(main())
</code></pre>
<p>With code that looks like this:</p>
<pre><code>@patch('optparse.OptionParser')
def test_main_with_missing_p4clientsdir_option(self, mock_optionparser):
#
# setup
#
optionparser_mock = Mock()
mock_optionparser.return_value = optionparser_mock
options_stub = Mock()
options_stub.foo = None
optionparser_mock.parse_args.return_value = (options_stub, sentinel.arguments)
def parser_error_mock(message):
self.assertEquals(message, '--foo option is required')
sys.exit(2)
optionparser_mock.error = parser_error_mock
#
# exercise & verify
#
self.assertEquals(sut.main(), 2)
</code></pre>
<p>I'm using <a href="http://www.voidspace.org.uk/python/mock.html">Michael Foord's Mock</a>, and nose to run the tests.</p>
<p>When I run the test, I get:</p>
<pre><code> File "/Users/dspitzer/Programming/Python/test-optparse-error/tests/sut_tests.py", line 27, in parser_error_mock
sys.exit(2)
SystemExit: 2
----------------------------------------------------------------------
Ran 1 test in 0.012s
FAILED (errors=1)
</code></pre>
<p>The problem is that OptionParser.error does a sys.exit(2), and so main() naturally relies on that. But nose or unittest detects the (expected) sys.exit(2) and fails the test.</p>
<p>I can make the test pass by adding "return 2" under the parser.error() call in main() and removing the sys.exit() call from parser_error_mock(), but I find it distasteful to modify the code under test to allow a test to pass. Is there a better solution?</p>
<p><strong>Update</strong>: <a href="http://stackoverflow.com/users/3002/df">df</a>'s answer works, although the correct call is "self.assertRaises(SystemExit, sut.main)".</p>
<p>Which means the test passes whatever the number is in the sys.exit() in parser_error_mock(). Is there any way to test for the exit code?</p>
<p>BTW, the test is more robust if I add:</p>
<pre><code>self.assertEquals(optionparser_mock.method_calls, [('add_option', ('--foo',), {'action': 'store', 'help': 'The foo option is self-explanatory'}), ('parse_args', (), {})])
</code></pre>
<p>at the end.</p>
<p><strong>Update 2</strong>: I can test for the exit code by replacing "self.assertRaises(SystemExit, sut.main)" with:</p>
<pre><code>try:
sut.main()
except SystemExit, e:
self.assertEquals(type(e), type(SystemExit()))
self.assertEquals(e.code, 2)
except Exception, e:
self.fail('unexpected exception: %s' % e)
else:
self.fail('SystemExit exception expected')
</code></pre>
| 14 | 2009-01-08T23:37:31Z | 455,576 | <p>As noted in my updates to my question, I had to modify <a href="http://stackoverflow.com/users/3002/df">dF</a>'s answer to:</p>
<pre><code>self.assertRaises(SystemExit, sut.main)
</code></pre>
<p>...and I came up with a few longer snippet to test for the exit code.</p>
<p>[Note: I accepted my own answer, but I will delete this answer and accept <a href="http://stackoverflow.com/users/3002/df">dF</a>'s if he updates his.]</p>
| 1 | 2009-01-18T17:48:48Z | [
"python",
"unit-testing",
"mocking",
"optparse"
]
|
How do I mock the Python method OptionParser.error(), which does a sys.exit()? | 426,500 | <p>I'm trying to unit test some code that looks like this:</p>
<pre><code>def main():
parser = optparse.OptionParser(description='This tool is cool', prog='cool-tool')
parser.add_option('--foo', action='store', help='The foo option is self-explanatory')
options, arguments = parser.parse_args()
if not options.foo:
parser.error('--foo option is required')
print "Your foo is %s." % options.foo
return 0
if __name__ == '__main__':
sys.exit(main())
</code></pre>
<p>With code that looks like this:</p>
<pre><code>@patch('optparse.OptionParser')
def test_main_with_missing_p4clientsdir_option(self, mock_optionparser):
#
# setup
#
optionparser_mock = Mock()
mock_optionparser.return_value = optionparser_mock
options_stub = Mock()
options_stub.foo = None
optionparser_mock.parse_args.return_value = (options_stub, sentinel.arguments)
def parser_error_mock(message):
self.assertEquals(message, '--foo option is required')
sys.exit(2)
optionparser_mock.error = parser_error_mock
#
# exercise & verify
#
self.assertEquals(sut.main(), 2)
</code></pre>
<p>I'm using <a href="http://www.voidspace.org.uk/python/mock.html">Michael Foord's Mock</a>, and nose to run the tests.</p>
<p>When I run the test, I get:</p>
<pre><code> File "/Users/dspitzer/Programming/Python/test-optparse-error/tests/sut_tests.py", line 27, in parser_error_mock
sys.exit(2)
SystemExit: 2
----------------------------------------------------------------------
Ran 1 test in 0.012s
FAILED (errors=1)
</code></pre>
<p>The problem is that OptionParser.error does a sys.exit(2), and so main() naturally relies on that. But nose or unittest detects the (expected) sys.exit(2) and fails the test.</p>
<p>I can make the test pass by adding "return 2" under the parser.error() call in main() and removing the sys.exit() call from parser_error_mock(), but I find it distasteful to modify the code under test to allow a test to pass. Is there a better solution?</p>
<p><strong>Update</strong>: <a href="http://stackoverflow.com/users/3002/df">df</a>'s answer works, although the correct call is "self.assertRaises(SystemExit, sut.main)".</p>
<p>Which means the test passes whatever the number is in the sys.exit() in parser_error_mock(). Is there any way to test for the exit code?</p>
<p>BTW, the test is more robust if I add:</p>
<pre><code>self.assertEquals(optionparser_mock.method_calls, [('add_option', ('--foo',), {'action': 'store', 'help': 'The foo option is self-explanatory'}), ('parse_args', (), {})])
</code></pre>
<p>at the end.</p>
<p><strong>Update 2</strong>: I can test for the exit code by replacing "self.assertRaises(SystemExit, sut.main)" with:</p>
<pre><code>try:
sut.main()
except SystemExit, e:
self.assertEquals(type(e), type(SystemExit()))
self.assertEquals(e.code, 2)
except Exception, e:
self.fail('unexpected exception: %s' % e)
else:
self.fail('SystemExit exception expected')
</code></pre>
| 14 | 2009-01-08T23:37:31Z | 13,688,099 | <p>Add <code>@raises</code> to your test function. I.e:</p>
<pre><code>from nose.tools import raises
@raises(SystemExit)
@patch('optparse.OptionParser')
def test_main_with_missing_p4clientsdir_option(self, mock_optionparser):
# Setup
...
sut.main()
</code></pre>
| 0 | 2012-12-03T17:00:16Z | [
"python",
"unit-testing",
"mocking",
"optparse"
]
|
PyObjc vs RubyCocoa for Mac development: Which is more mature? | 426,607 | <p>I've been wanting to have a play with either Ruby or Python while at the same time I've been wanting to do a bit of Cocoa programming.</p>
<p>So I thought the best way to achieve both these goals is to develop something using either a Ruby or Python to Objective-C bridge (PyObjc or RubyCocoa).</p>
<p>I know that ideally to get the best learning experience I would learn each techonology independently but I don't have the time. :)</p>
<p>So my question is which is a more mature platform, PyObc or RubyCocoa, main things I am looking for:</p>
<ol>
<li>Documentation of API</li>
<li>Tutorials</li>
<li>Tools</li>
<li>Supportive Community</li>
<li>Completness of Cocoa API avaialble through the bridge </li>
</ol>
<p>Regarding point 5 I don't expect that the entire Cocoa API will be availble through either bridge but I need to have enough Cocoa APIs available to develop a functioning application.</p>
| 8 | 2009-01-09T00:16:24Z | 426,703 | <p>While you say you "don't have time" to learn technologies independently the fastest route to learning Cocoa will still be to learn it in its native language: Objective-C. Once you understand Objective-C and have gotten over the initial learning curve of the Cocoa frameworks you'll have a much easier time picking up either PyObjC or RubyCocoa.</p>
| 11 | 2009-01-09T01:08:54Z | [
"python",
"ruby",
"cocoa",
"pyobjc",
"ruby-cocoa"
]
|
PyObjc vs RubyCocoa for Mac development: Which is more mature? | 426,607 | <p>I've been wanting to have a play with either Ruby or Python while at the same time I've been wanting to do a bit of Cocoa programming.</p>
<p>So I thought the best way to achieve both these goals is to develop something using either a Ruby or Python to Objective-C bridge (PyObjc or RubyCocoa).</p>
<p>I know that ideally to get the best learning experience I would learn each techonology independently but I don't have the time. :)</p>
<p>So my question is which is a more mature platform, PyObc or RubyCocoa, main things I am looking for:</p>
<ol>
<li>Documentation of API</li>
<li>Tutorials</li>
<li>Tools</li>
<li>Supportive Community</li>
<li>Completness of Cocoa API avaialble through the bridge </li>
</ol>
<p>Regarding point 5 I don't expect that the entire Cocoa API will be availble through either bridge but I need to have enough Cocoa APIs available to develop a functioning application.</p>
| 8 | 2009-01-09T00:16:24Z | 426,733 | <p>Both are roughly equal, I'd say. Better in some places, worse in others. But I wouldn't recommend learning Cocoa with either. Like Chris said, Cocoa requires some understanding of Objective-C. I like Ruby better than Objective-C, but I still don't recommend using it to learn Cocoa. Once you have a solid foundation (no pun intended) in Cocoa/Objective-C, then the bridges can be useful to you.</p>
| 3 | 2009-01-09T01:25:52Z | [
"python",
"ruby",
"cocoa",
"pyobjc",
"ruby-cocoa"
]
|
PyObjc vs RubyCocoa for Mac development: Which is more mature? | 426,607 | <p>I've been wanting to have a play with either Ruby or Python while at the same time I've been wanting to do a bit of Cocoa programming.</p>
<p>So I thought the best way to achieve both these goals is to develop something using either a Ruby or Python to Objective-C bridge (PyObjc or RubyCocoa).</p>
<p>I know that ideally to get the best learning experience I would learn each techonology independently but I don't have the time. :)</p>
<p>So my question is which is a more mature platform, PyObc or RubyCocoa, main things I am looking for:</p>
<ol>
<li>Documentation of API</li>
<li>Tutorials</li>
<li>Tools</li>
<li>Supportive Community</li>
<li>Completness of Cocoa API avaialble through the bridge </li>
</ol>
<p>Regarding point 5 I don't expect that the entire Cocoa API will be availble through either bridge but I need to have enough Cocoa APIs available to develop a functioning application.</p>
| 8 | 2009-01-09T00:16:24Z | 426,883 | <p>Apple seems to be getting behind Ruby scripting for Cocoa but not RubyCocoa. They are hosting and I believe supporting <a href="http://www.macruby.org/trac/wiki/MacRuby" rel="nofollow">MacRuby</a>. I often wonder if MacRuby is Apple's answer to a higher level language for OSX prototyping and full on application development.</p>
| 1 | 2009-01-09T02:41:13Z | [
"python",
"ruby",
"cocoa",
"pyobjc",
"ruby-cocoa"
]
|
PyObjc vs RubyCocoa for Mac development: Which is more mature? | 426,607 | <p>I've been wanting to have a play with either Ruby or Python while at the same time I've been wanting to do a bit of Cocoa programming.</p>
<p>So I thought the best way to achieve both these goals is to develop something using either a Ruby or Python to Objective-C bridge (PyObjc or RubyCocoa).</p>
<p>I know that ideally to get the best learning experience I would learn each techonology independently but I don't have the time. :)</p>
<p>So my question is which is a more mature platform, PyObc or RubyCocoa, main things I am looking for:</p>
<ol>
<li>Documentation of API</li>
<li>Tutorials</li>
<li>Tools</li>
<li>Supportive Community</li>
<li>Completness of Cocoa API avaialble through the bridge </li>
</ol>
<p>Regarding point 5 I don't expect that the entire Cocoa API will be availble through either bridge but I need to have enough Cocoa APIs available to develop a functioning application.</p>
| 8 | 2009-01-09T00:16:24Z | 429,727 | <p>I would echo Chris' assesment and will expand a bit on why you should learn Objective-C to learn Cocoa. As Chris says, Objective-C is the foundation and native language of Cocoa and many of its paradigms are inextricably linked with that lineage. In particular, selectors and dynamic message resolution and ability to modify classes at run time are required to implement Cocoa technologies such as Distributed Objects and bindings. Although these features are available in other dynamic languages such as Ruby and Python, there is enough of a mismatch in the language models that you will have to at least understand Objective-C to understand Cocoa. I suggest you take a look at this previous question for further discussion: <a href="http://stackoverflow.com/questions/272660/do-i-have-to-learn-objective-c-for-professional-mac-development">Do I have to learn Objective-C for professional Mac Development?</a></p>
<p>Fortunately, Objective-C is very easy to learn. I often tell people it will take them a day to learn Objective-C coming from C/C++/Java or LISP, Scheme, or any of the 'newer' dynamic languages such as Ruby and Python. In addition to expanding your mind a bit, you'll learn to at least read the code that is used in virtually all of the Cocoa documentation and examples.</p>
<p>As for Ruby vs. Python, the bridge capabilities are very similar. In fact, they both use Apple's <a href="http://bridgesupport.macosforge.org/trac/" rel="nofollow">BridgeSupport</a> (shipped with Leopard) to provide the bridge description. Both are supported by Apple and ship with Leopard. It's a matter of personal taste which language you prefer. If you choose Ruby, I suggest you give <a href="http://www.macruby.org/trac/wiki/MacRuby" rel="nofollow">MacRuby</a> a look. It's definitely the future of Ruby on OS X, as it reimplements the Ruby runtime on top of the Objective-C run time. This provides some nice performance and conceptual advantages (including integration with the Objective-C garbage collection system, a feature currently lacking in PyObjC which uses the native python gc). MacRuby also includes a custom parser that makes the syntax of bridged objective-c methods a little nicer. The downside of MacRuby is that it's not quite ready for production-level use at the time of this writing (June 2009). Since it sounds like this is a learning project for you, that's probably not an issue.</p>
| 8 | 2009-01-09T21:02:42Z | [
"python",
"ruby",
"cocoa",
"pyobjc",
"ruby-cocoa"
]
|
PyObjc vs RubyCocoa for Mac development: Which is more mature? | 426,607 | <p>I've been wanting to have a play with either Ruby or Python while at the same time I've been wanting to do a bit of Cocoa programming.</p>
<p>So I thought the best way to achieve both these goals is to develop something using either a Ruby or Python to Objective-C bridge (PyObjc or RubyCocoa).</p>
<p>I know that ideally to get the best learning experience I would learn each techonology independently but I don't have the time. :)</p>
<p>So my question is which is a more mature platform, PyObc or RubyCocoa, main things I am looking for:</p>
<ol>
<li>Documentation of API</li>
<li>Tutorials</li>
<li>Tools</li>
<li>Supportive Community</li>
<li>Completness of Cocoa API avaialble through the bridge </li>
</ol>
<p>Regarding point 5 I don't expect that the entire Cocoa API will be availble through either bridge but I need to have enough Cocoa APIs available to develop a functioning application.</p>
| 8 | 2009-01-09T00:16:24Z | 3,930,584 | <p>ObjectiveC is nowhere near as much fun or as productive as either Python or Ruby. That is why people want to pick a python or ruby with good Objective C access. Advising them to learn Objective C first misses the point imo. I have really good things to say about pyobjc. Its ability to interoperate painlessly with Objective C frameworks is superb. I have less experience with Ruby Cocoa and that was partly because when I last looked it didn't seem to have as clean and relatively painless interoperability. I feel hesitant about MacRuby because it seems to go too far. In pyobjc you can write plain python and only subclass/use Foundation and Cocoa objects when you really want/mean to. From what I understand of MacRuby it is a Ruby on top of Cocoa. So a string is always an NSString. I am less happy with that. YMMV.</p>
| 1 | 2010-10-14T06:19:39Z | [
"python",
"ruby",
"cocoa",
"pyobjc",
"ruby-cocoa"
]
|
What is the easiest way to export data from a live google app engine application? | 426,820 | <p>I'm especially interested in solutions with source code available (django independency is a plus, but I'm willing to hack my way through)</p>
| 6 | 2009-01-09T02:09:04Z | 427,588 | <p>You can, of course, write your own handler. Other than that, your options currently are limited to:</p>
<ul>
<li><a href="http://github.com/fczuardi/gae-rest/tree/master">gae-rest</a>, which provides a RESTful interface to the datastore.</li>
<li><a href="http://code.google.com/p/approcket/">approcket</a>, a tool for replicating between MySQL and App Engine.</li>
<li>The amusingly named <a href="http://aralbalkan.com/1784">GAEBAR</a> - Google App Engine Backup and Restore.</li>
</ul>
| 6 | 2009-01-09T10:12:41Z | [
"python",
"google-app-engine",
"frameworks"
]
|
What is the easiest way to export data from a live google app engine application? | 426,820 | <p>I'm especially interested in solutions with source code available (django independency is a plus, but I'm willing to hack my way through)</p>
| 6 | 2009-01-09T02:09:04Z | 435,901 | <p><strong>Update</strong>: New version of Google AppEngine supports data import to and export from the online application natively. In their terms this is called <code>upload_data</code> and <code>download_data</code> respectively (names of subcommands of <code>appcfg.py</code>).</p>
<p>Please refer to Google documentation <a href="http://code.google.com/appengine/docs/python/tools/uploadingdata.html" rel="nofollow">how to export and import data from/to GAE</a>. This is probably the better way to do it today.</p>
<p>My old answer is below:</p>
<hr>
<p>I use <a href="http://code.google.com/intl/ru/appengine/docs/datastore/modelclass.html#Model_to_xml" rel="nofollow">to_xml()</a> method of the Model class to export the datastore.</p>
<pre><code>class XmlExport(webapp.RequestHandler):
def get(self):
objects=MyModel.all().fetch(1000)
xml='<?xml version="1.0" encoding="UTF-8"?>\n<site>\n'
for o in objects:
xml = xml + o.to_xml()
xml = xml + '</site>'
self.response.headers['Content-Type']='text/xml; charset=utf-8'
self.response.out.write(xml)
</code></pre>
| 3 | 2009-01-12T16:09:03Z | [
"python",
"google-app-engine",
"frameworks"
]
|
Scripting LMMS from Python | 427,037 | <p>Recently I <a href="http://stackoverflow.com/questions/267628/scripting-fruityloops-or-propellerheads-reason-from-vb-or-python">asked</a> about scripting FruityLoops or Reason from Python, which didn't turn up much.</p>
<p>Today I found <a href="http://lmms.sourceforge.net/" rel="nofollow">LMMS</a>, a free-software FruityLoops clone. So, similarly. Has anyone tried scripting this from Python (or similar)? Is there an API or wrapper for accessing its resources from outside?</p>
<p>If not, what would be the right approach to try writing one?</p>
| 1 | 2009-01-09T04:06:23Z | 427,330 | <p>It seems you can <a href="http://lmms.sourceforge.net/wiki/index.php?title=Plugin_development_tutorial" rel="nofollow">write plugins</a> for LMMS using C++. By <a href="http://www.python.org/doc/2.5.2/ext/embedding.html" rel="nofollow">embedding Python in the C++ plugin</a> you can effectively script the program in Python. </p>
| 3 | 2009-01-09T07:33:10Z | [
"python",
"music"
]
|
Scripting LMMS from Python | 427,037 | <p>Recently I <a href="http://stackoverflow.com/questions/267628/scripting-fruityloops-or-propellerheads-reason-from-vb-or-python">asked</a> about scripting FruityLoops or Reason from Python, which didn't turn up much.</p>
<p>Today I found <a href="http://lmms.sourceforge.net/" rel="nofollow">LMMS</a>, a free-software FruityLoops clone. So, similarly. Has anyone tried scripting this from Python (or similar)? Is there an API or wrapper for accessing its resources from outside?</p>
<p>If not, what would be the right approach to try writing one?</p>
| 1 | 2009-01-09T04:06:23Z | 427,841 | <p>Look at <a href="http://www.csounds.com/" rel="nofollow">http://www.csounds.com/</a> for an approach to scripting music synth programs in Python.</p>
| 0 | 2009-01-09T12:04:55Z | [
"python",
"music"
]
|
Scripting LMMS from Python | 427,037 | <p>Recently I <a href="http://stackoverflow.com/questions/267628/scripting-fruityloops-or-propellerheads-reason-from-vb-or-python">asked</a> about scripting FruityLoops or Reason from Python, which didn't turn up much.</p>
<p>Today I found <a href="http://lmms.sourceforge.net/" rel="nofollow">LMMS</a>, a free-software FruityLoops clone. So, similarly. Has anyone tried scripting this from Python (or similar)? Is there an API or wrapper for accessing its resources from outside?</p>
<p>If not, what would be the right approach to try writing one?</p>
| 1 | 2009-01-09T04:06:23Z | 430,550 | <p>You can connect pretty much everything in LMMS to a MIDI input. Try that?</p>
| 0 | 2009-01-10T04:26:13Z | [
"python",
"music"
]
|
Does anyone know of a Python equivalent of FMPP? | 427,095 | <p>Does anyone know of a Python equivalent for <a href="http://fmpp.sourceforge.net/" rel="nofollow">FMPP</a> the text file preprocessor?</p>
<p>Follow up: I am reading the docs and looking at the examples for the suggestions given. Just to expand. My usage of FMPP is to read in a data file (csv) and use multiple templates depending on that data to create multi page reports in html all linked to a main index.</p>
| 4 | 2009-01-09T04:46:37Z | 427,131 | <p>You could give <a href="http://www.cheetahtemplate.org/" rel="nofollow">Cheetah</a> a try. I've used it before with some success.</p>
| 1 | 2009-01-09T05:04:40Z | [
"python",
"preprocessor",
"template-engine",
"freemarker",
"fmpp"
]
|
Does anyone know of a Python equivalent of FMPP? | 427,095 | <p>Does anyone know of a Python equivalent for <a href="http://fmpp.sourceforge.net/" rel="nofollow">FMPP</a> the text file preprocessor?</p>
<p>Follow up: I am reading the docs and looking at the examples for the suggestions given. Just to expand. My usage of FMPP is to read in a data file (csv) and use multiple templates depending on that data to create multi page reports in html all linked to a main index.</p>
| 4 | 2009-01-09T04:46:37Z | 427,300 | <p>Python has lots of templating engines. It depends on your exact needs.</p>
<p><a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja2</a> is a good one, for example. <a href="http://www.kid-templating.org/" rel="nofollow">Kid</a> is another.</p>
| 2 | 2009-01-09T07:15:03Z | [
"python",
"preprocessor",
"template-engine",
"freemarker",
"fmpp"
]
|
Does anyone know of a Python equivalent of FMPP? | 427,095 | <p>Does anyone know of a Python equivalent for <a href="http://fmpp.sourceforge.net/" rel="nofollow">FMPP</a> the text file preprocessor?</p>
<p>Follow up: I am reading the docs and looking at the examples for the suggestions given. Just to expand. My usage of FMPP is to read in a data file (csv) and use multiple templates depending on that data to create multi page reports in html all linked to a main index.</p>
| 4 | 2009-01-09T04:46:37Z | 427,827 | <p>Let me add <a href="http://makotemplates.org" rel="nofollow">Mako</a> Fine fast tool (and it even uses ${var} syntax).</p>
<p>Note: Mako, Jinja and Cheetah are <em>textual</em> languages (they process and generate text). I'd order them Mako > Jinja > Cheetah (in term of features and readability), but people's preferences vary.</p>
<p>Kid and it's successor <a href="http://genshi.edgewall.org/" rel="nofollow">Genshi</a> are HTML/XML aware attribute languages (<code><div py:if="variable"> ... </div></code> etc ). That's completely different methodology - and tools suitable for HTML or XML only.</p>
| 3 | 2009-01-09T11:59:40Z | [
"python",
"preprocessor",
"template-engine",
"freemarker",
"fmpp"
]
|
Does anyone know of a Python equivalent of FMPP? | 427,095 | <p>Does anyone know of a Python equivalent for <a href="http://fmpp.sourceforge.net/" rel="nofollow">FMPP</a> the text file preprocessor?</p>
<p>Follow up: I am reading the docs and looking at the examples for the suggestions given. Just to expand. My usage of FMPP is to read in a data file (csv) and use multiple templates depending on that data to create multi page reports in html all linked to a main index.</p>
| 4 | 2009-01-09T04:46:37Z | 427,870 | <p>I'm not sure exactly what FMPP does, but from a quick glance it seems like a template language.</p>
<p><a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja2</a> is an excellent template system for python.</p>
<p>sample:</p>
<pre><code><ul>
{% for item in list %}
<li> {{ item.title }} </li>
{% endfor %}
</ul>
{% if user.is_admin() %}
<a href="./edit">Edit this page</a>
{% endif %}
</code></pre>
| 1 | 2009-01-09T12:19:06Z | [
"python",
"preprocessor",
"template-engine",
"freemarker",
"fmpp"
]
|
What is a "slug" in Django? | 427,102 | <p>When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used? </p>
<p>(I have read its definition in <a href="http://docs.djangoproject.com/en/dev/glossary/">this glossary</a>.)</p>
| 273 | 2009-01-09T04:52:26Z | 427,111 | <p>From <a href="http://jeffcroft.com/blog/2006/may/02/django-non-programmers/">here</a>.</p>
<blockquote>
<p>âSlugâ is a newspaper term, but what
it means here is the final bit of the
URL. For example, a post with the
title, âA bit about Djangoâ would
become, âbit-about-djangoâ
automatically (you can, of course,
change it easily if you donât like the
auto-generated slug).</p>
</blockquote>
| 13 | 2009-01-09T04:56:10Z | [
"python",
"django",
"django-models",
"slug"
]
|
What is a "slug" in Django? | 427,102 | <p>When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used? </p>
<p>(I have read its definition in <a href="http://docs.djangoproject.com/en/dev/glossary/">this glossary</a>.)</p>
| 273 | 2009-01-09T04:52:26Z | 427,125 | <p>It's a descriptive part of the URL that is there to make it more human descriptive, but without necessarily being required by the web server - in <a href="http://stackoverflow.com/questions/427102/in-django-what-is-a-slug">http://stackoverflow.com/questions/427102/in-django-what-is-a-slug</a> the slug is 'in-django-what-is-a-slug', but the slug is not used to determine the <a href="http://stackoverflow.com/questions/427102/different-slug-same-content">page served</a> (on this site at least)</p>
| 13 | 2009-01-09T05:02:48Z | [
"python",
"django",
"django-models",
"slug"
]
|
What is a "slug" in Django? | 427,102 | <p>When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used? </p>
<p>(I have read its definition in <a href="http://docs.djangoproject.com/en/dev/glossary/">this glossary</a>.)</p>
| 273 | 2009-01-09T04:52:26Z | 427,160 | <p>It's a way of generating a valid URL, generally using data already obtained. For instance, using the title of an article to generate a URL. I'd advise to generate the slug, using a function, given a title (or other piece of data), rather than setting it manually.</p>
<p>An example:</p>
<pre class="lang-html prettyprint-override"><code><title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>
</code></pre>
<p>Now let's pretend that we have a Django model such as:</p>
<pre class="lang-python prettyprint-override"><code>class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(max_length=1000)
slug = models.SlugField(max_length=40)
</code></pre>
<p>How would you reference this object with a URL, with a meaningful name? You could use Article.id so the URL would look like this:</p>
<pre><code>www.example.com/article/23
</code></pre>
<p>Or, you could reference the title like so:</p>
<pre><code>www.example.com/article/The 46 Year Old Virgin
</code></pre>
<p>Problem is, spaces aren't valid in URLs, they need to be replaced by <code>%20</code> which is ugly, making it the following:</p>
<pre><code>www.example.com/article/The%2046%20Year%20Old%20Virgin
</code></pre>
<p>That's not solving our meaningful URL. Wouldn't this be better:</p>
<pre><code>www.example.com/article/the-46-year-old-virgin
</code></pre>
<p>That's a slug. <code>the-46-year-old-virgin</code>. All letters are downcased and spaces are replaced by hyphens <code>-</code>. See the URL of this very webpage for an example!</p>
| 355 | 2009-01-09T05:31:47Z | [
"python",
"django",
"django-models",
"slug"
]
|
What is a "slug" in Django? | 427,102 | <p>When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used? </p>
<p>(I have read its definition in <a href="http://docs.djangoproject.com/en/dev/glossary/">this glossary</a>.)</p>
| 273 | 2009-01-09T04:52:26Z | 427,201 | <p>As a bit of history, the term 'slug' comes from the world of newspaper editing.</p>
<p>It's the informal name given to a story during the production process. As the story winds its torturous path from beat reporter through to editor through to the "printing presses", this is the name it is referenced by, e.g., "Have you fixed those errors in the 'russia-cuts-europe-gas' story?".</p>
<p>Django uses it as part of the URL to locate the story, an example being <code>www.mysite.com/archives/russia-cuts-europe-gas</code>.</p>
| 34 | 2009-01-09T06:01:06Z | [
"python",
"django",
"django-models",
"slug"
]
|
What is a "slug" in Django? | 427,102 | <p>When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used? </p>
<p>(I have read its definition in <a href="http://docs.djangoproject.com/en/dev/glossary/">this glossary</a>.)</p>
| 273 | 2009-01-09T04:52:26Z | 1,282,172 | <p>May I be complete to this :</p>
<p>The term <strong>"slug"</strong> has to do with casting metal, lead, in this case, out of which the press fonts were made of. Every Paper then, had its fonts factory, regularily, re-melted and recasted in fresh molds. Because after many prints they were worned out. Apprentice like me started their career there, and all the way to the top. (Not anymore)</p>
<p>Typographs had to compose the text of the article in a backward manner with lead caracters stacked in a wise. So at printing time the letters would be straight on the paper. All typographs could read the newspaper mirrored as fast as the printed one.Therefore the slugs, (like snails) also the slow stories (the lasts to be fixed) were many on the bench waiting, solely identified by their fist letters, mostly the whole title generaly more readable. Some "hot" news were waiting there on the bench, for possible last minute correction, (Evening paper) before last assembly and definitive printing.</p>
<p>Django emerged from the offices of the Lawrence journal in Kansas. Where probably some printing jargon still lingers. <strong>A-django-enthousiast-&-friendly-old-slug-boy-from-France.</strong></p>
| 58 | 2009-08-15T15:45:33Z | [
"python",
"django",
"django-models",
"slug"
]
|
What is a "slug" in Django? | 427,102 | <p>When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used? </p>
<p>(I have read its definition in <a href="http://docs.djangoproject.com/en/dev/glossary/">this glossary</a>.)</p>
| 273 | 2009-01-09T04:52:26Z | 14,438,884 | <p>Also auto slug at django-admin. Added at ModelAdmin:</p>
<pre><code>prepopulated_fields = {'slug': ('title', )}
</code></pre>
<p>As here:</p>
<pre><code>class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'slug')
search_fields = ('content', )
prepopulated_fields = {'slug': ('title', )}
</code></pre>
| 3 | 2013-01-21T12:42:44Z | [
"python",
"django",
"django-models",
"slug"
]
|
What is a "slug" in Django? | 427,102 | <p>When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used? </p>
<p>(I have read its definition in <a href="http://docs.djangoproject.com/en/dev/glossary/">this glossary</a>.)</p>
| 273 | 2009-01-09T04:52:26Z | 25,808,438 | <p>Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens.Theyâre generally used in URLs.(as in django docs)</p>
<p>A slug field in Django is used to store and generate valid <a href="http://en.wikipedia.org/wiki/Uniform_resource_locator" rel="nofollow">URLs</a> for your dynamically created web pages.</p>
<p>Just like the way you added this question on Stack Overflow and a dynamic page is generated and when you see in address bar you will see your question title with "-" in place of the spaces. That's exactly the job of a slug field.</p>
<p><img src="http://i.stack.imgur.com/hUr5J.jpg" alt="Enter image description here"></p>
<p>The title entered by you was something like this -> What is a âslugâ in Django?</p>
<p>&</p>
<p>On storing it into a slug, filed results it into
what-is-a-slug-in-django (see URL of this page)</p>
| 6 | 2014-09-12T12:32:10Z | [
"python",
"django",
"django-models",
"slug"
]
|
How do I timestamp simultaneous function calls in Python? | 427,152 | <p>I have a read function in a module.</p>
<p>If I perform that function simultaneously I need to timestamp it.</p>
<p>How do I do this?</p>
| -1 | 2009-01-09T05:21:49Z | 427,234 | <p>#!/usr/bin/env python</p>
<pre><code>import datetime
def timestampit(func):
def decorate(*args, **kwargs):
print datetime.datetime.now()
return func(*args, **kwargs)
return decorate
@timestampit
def hello():
print 'hello'
hello()
# Output:
# $ python test.py
# 2009-01-09 11:50:48.704584
# hello
</code></pre>
| 2 | 2009-01-09T06:21:01Z | [
"python",
"function-call",
"timestamping",
"simultaneous-calls"
]
|
How do I timestamp simultaneous function calls in Python? | 427,152 | <p>I have a read function in a module.</p>
<p>If I perform that function simultaneously I need to timestamp it.</p>
<p>How do I do this?</p>
| -1 | 2009-01-09T05:21:49Z | 427,317 | <p>I'll offer a slightly different approach:</p>
<pre><code>import time
def timestampit(func):
def decorate(*args, **kwargs):
decorate.timestamp = time.time()
return func(*args, **kwargs)
return decorate
@timestampit
def hello():
print 'hello'
hello()
print hello.timestamp
time.sleep(1)
hello()
print hello.timestamp
</code></pre>
<p>The differences from Swaroop's example are:</p>
<ol>
<li>I'm using time.time() and not datetime.now() for a timestamp, because it's more suitable for performance testing</li>
<li>I'm attaching the timestamp as an attribute of the decorated function. This way you may invoke and keep it whenever you want.</li>
</ol>
| 6 | 2009-01-09T07:25:40Z | [
"python",
"function-call",
"timestamping",
"simultaneous-calls"
]
|
How do I timestamp simultaneous function calls in Python? | 427,152 | <p>I have a read function in a module.</p>
<p>If I perform that function simultaneously I need to timestamp it.</p>
<p>How do I do this?</p>
| -1 | 2009-01-09T05:21:49Z | 427,619 | <p>If you're interested, there's <a href="http://wiki.python.org/moin/PythonDecorators" rel="nofollow">a wealth of information about decorators on the python wiki</a>.</p>
| 0 | 2009-01-09T10:27:02Z | [
"python",
"function-call",
"timestamping",
"simultaneous-calls"
]
|
How do I timestamp simultaneous function calls in Python? | 427,152 | <p>I have a read function in a module.</p>
<p>If I perform that function simultaneously I need to timestamp it.</p>
<p>How do I do this?</p>
| -1 | 2009-01-09T05:21:49Z | 427,803 | <p>Some example
<a href="http://blogs.nuxeo.com/sections/blogs/tarek_ziade/archive/2005/09" rel="nofollow">code by Terik Ziade</a></p>
<p>(more polished version, which uses timeit module, can be found in his recent book Expert Python Programming)</p>
| 0 | 2009-01-09T11:50:52Z | [
"python",
"function-call",
"timestamping",
"simultaneous-calls"
]
|
Unit testing and mocking email sender in Python with Google AppEngine | 427,400 | <p>I'm a newbie to python and the app engine.</p>
<p>I have this code that sends an email based on request params after some auth logic. in my Unit tests (i'm using <a href="http://code.google.com/p/gaeunit/" rel="nofollow">GAEUnit</a>), how do I confirm an email with specific contents were sent? - i.e. how do I mock the emailer with a fake emailer to verify send was called?</p>
<pre><code>class EmailHandler(webapp.RequestHandler):
def bad_input(self):
self.response.set_status(400)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>bad input </body></html>")
def get(self):
to_addr = self.request.get("to")
subj = self.request.get("subject")
msg = self.request.get("body")
if not mail.is_email_valid(to_addr):
# Return an error message...
# self.bad_input()
pass
# authenticate here
message = mail.EmailMessage()
message.sender = "my.company@gmail.com"
message.to = to_addr
message.subject = subj
message.body = msg
message.send()
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>success!</body></html>")
</code></pre>
<p>And the unit tests,</p>
<pre><code>import unittest
from webtest import TestApp
from google.appengine.ext import webapp
from email import EmailHandler
class SendingEmails(unittest.TestCase):
def setUp(self):
self.application = webapp.WSGIApplication([('/', EmailHandler)], debug=True)
def test_success(self):
app = TestApp(self.application)
response = app.get('http://localhost:8080/send?to=vijay.santhanam@gmail.com&body=blah_blah_blah&subject=mySubject')
self.assertEqual('200 OK', response.status)
self.assertTrue('success' in response)
# somehow, assert email was sent
</code></pre>
| 5 | 2009-01-09T08:33:34Z | 427,418 | <p>A very short introduction provides <a href="http://pypi.python.org/pypi/MiniMock/1.0" rel="nofollow">PyPI: MiniMock 1.0</a>. It's a very small library to establish mocks.</p>
<ol>
<li>Inject your mock into the module, that should be mocked</li>
<li>Define, what your mock will return</li>
<li>Call the method</li>
<li>Your mock will say, which method were called.</li>
</ol>
<p>Good luck!</p>
| 2 | 2009-01-09T08:46:09Z | [
"python",
"unit-testing",
"google-app-engine",
"mocking"
]
|
Unit testing and mocking email sender in Python with Google AppEngine | 427,400 | <p>I'm a newbie to python and the app engine.</p>
<p>I have this code that sends an email based on request params after some auth logic. in my Unit tests (i'm using <a href="http://code.google.com/p/gaeunit/" rel="nofollow">GAEUnit</a>), how do I confirm an email with specific contents were sent? - i.e. how do I mock the emailer with a fake emailer to verify send was called?</p>
<pre><code>class EmailHandler(webapp.RequestHandler):
def bad_input(self):
self.response.set_status(400)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>bad input </body></html>")
def get(self):
to_addr = self.request.get("to")
subj = self.request.get("subject")
msg = self.request.get("body")
if not mail.is_email_valid(to_addr):
# Return an error message...
# self.bad_input()
pass
# authenticate here
message = mail.EmailMessage()
message.sender = "my.company@gmail.com"
message.to = to_addr
message.subject = subj
message.body = msg
message.send()
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>success!</body></html>")
</code></pre>
<p>And the unit tests,</p>
<pre><code>import unittest
from webtest import TestApp
from google.appengine.ext import webapp
from email import EmailHandler
class SendingEmails(unittest.TestCase):
def setUp(self):
self.application = webapp.WSGIApplication([('/', EmailHandler)], debug=True)
def test_success(self):
app = TestApp(self.application)
response = app.get('http://localhost:8080/send?to=vijay.santhanam@gmail.com&body=blah_blah_blah&subject=mySubject')
self.assertEqual('200 OK', response.status)
self.assertTrue('success' in response)
# somehow, assert email was sent
</code></pre>
| 5 | 2009-01-09T08:33:34Z | 1,411,769 | <p>You could also override the <code>_GenerateLog</code> method in the <code>mail_stub</code> inside AppEngine.</p>
<p>Here is a parent TestCase class that I use as a mixin when testing that e-mails are sent:</p>
<pre><code>from google.appengine.api import apiproxy_stub_map, mail_stub
__all__ = ['MailTestCase']
class MailTestCase(object):
def setUp(self):
super(MailTestCase, self).setUp()
self.set_mail_stub()
self.clear_sent_messages()
def set_mail_stub(self):
test_case = self
class MailStub(mail_stub.MailServiceStub):
def _GenerateLog(self, method, message, log, *args, **kwargs):
test_case._sent_messages.append(message)
return super(MailStub, self)._GenerateLog(method, message, log, *args, **kwargs)
if 'mail' in apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map:
del apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map['mail']
apiproxy_stub_map.apiproxy.RegisterStub('mail', MailStub())
def clear_sent_messages(self):
self._sent_messages = []
def get_sent_messages(self):
return self._sent_messages
def assertEmailSent(self, to=None, sender=None, subject=None, body=None):
for message in self.get_sent_messages():
if to and to not in message.to_list(): continue
if sender and sender != message.sender(): continue
if subject and subject != message.subject(): continue
if body and body not in message.textbody(): continue
return
failure_message = "Expected e-mail message sent."
args = []
if to: args.append('To: %s' % to)
if sender: args.append('From: %s' % sender)
if subject: args.append('Subject: %s' % subject)
if body: args.append('Body (contains): %s' % body)
if args:
failure_message += ' Arguments expected: ' + ', '.join(args)
self.fail(failure_message)
</code></pre>
<p>After that, a sample test case might look like:</p>
<pre><code>import unittest, MailTestCase
class MyTestCase(unittest.TestCase, MailTestCase):
def test_email_sent(self):
send_email_to('test@example.org') # Some method that would send an e-mail.
self.assertEmailSent(to='test@example.org')
self.assertEqual(len(self.get_sent_messages()), 1)
</code></pre>
| 3 | 2009-09-11T15:50:57Z | [
"python",
"unit-testing",
"google-app-engine",
"mocking"
]
|
Unit testing and mocking email sender in Python with Google AppEngine | 427,400 | <p>I'm a newbie to python and the app engine.</p>
<p>I have this code that sends an email based on request params after some auth logic. in my Unit tests (i'm using <a href="http://code.google.com/p/gaeunit/" rel="nofollow">GAEUnit</a>), how do I confirm an email with specific contents were sent? - i.e. how do I mock the emailer with a fake emailer to verify send was called?</p>
<pre><code>class EmailHandler(webapp.RequestHandler):
def bad_input(self):
self.response.set_status(400)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>bad input </body></html>")
def get(self):
to_addr = self.request.get("to")
subj = self.request.get("subject")
msg = self.request.get("body")
if not mail.is_email_valid(to_addr):
# Return an error message...
# self.bad_input()
pass
# authenticate here
message = mail.EmailMessage()
message.sender = "my.company@gmail.com"
message.to = to_addr
message.subject = subj
message.body = msg
message.send()
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>success!</body></html>")
</code></pre>
<p>And the unit tests,</p>
<pre><code>import unittest
from webtest import TestApp
from google.appengine.ext import webapp
from email import EmailHandler
class SendingEmails(unittest.TestCase):
def setUp(self):
self.application = webapp.WSGIApplication([('/', EmailHandler)], debug=True)
def test_success(self):
app = TestApp(self.application)
response = app.get('http://localhost:8080/send?to=vijay.santhanam@gmail.com&body=blah_blah_blah&subject=mySubject')
self.assertEqual('200 OK', response.status)
self.assertTrue('success' in response)
# somehow, assert email was sent
</code></pre>
| 5 | 2009-01-09T08:33:34Z | 2,575,616 | <p>I used jgeewax's GAE Testbed with GAEUnit. Using GAEUnit instead of NoseGAE was easier for me since I already had GAEUnit in place. Here are the steps:</p>
<p><strong>Add GAEUnit to your app</strong></p>
<ol>
<li>Download the zipped archive of GAEUnit from <a href="http://code.google.com/p/gaeunit/" rel="nofollow">its Google Code project hosting page</a>.</li>
<li>Extract the archive.</li>
<li>From the folder extracted from the archive, copy <code>gaeunit.py</code> to your appâs root folder.</li>
<li>Add the following 2 lines to your <code>app.yaml</code>, directly below the line that says <code>handlers:</code>:</li>
</ol>
<p>Code:</p>
<pre><code>- url: /test.*
script: gaeunit.py
</code></pre>
<p>(Optional) From the folder extracted from the archive, thereâs a folder named <code>sample_app</code> and inside it is the modified version of the <code>webtest</code> module. Copy the <code>webtest</code> module (the entire folder containing <code>debugapp.py</code> and <code>__init__.py</code>) to the root of your app.</p>
<p><strong>Add GAE Testbed to GAEUnit:</strong></p>
<ol>
<li>Download the GAE Testbed tar gzipped archive from <a href="http://code.google.com/p/gae-testbed/" rel="nofollow">its Google Code project hosting page</a>.</li>
<li>Extract the archive.</li>
<li>Inside the extracted archive is the <code>gaetestbed</code> module (itâs the folder named âgaetestbedâ). Copy the module to the root of your app.</li>
<li>Create a file inside the test folder of the root of your app. For the sake of this example, letâs name it <code>test_mailer.py</code>.</li>
<li>Using the example from the GAE Testbed Google Code project hosting page, add the following lines to <code>test_mailer.py</code>:</li>
</ol>
<p>Code:</p>
<pre><code>import unittest
from gaetestbed import MailTestCase
class MyTestCase(MailTestCase, unittest.TestCase):
def test_email_sent(self):
send_email_to('test@example.org') # Some method that sends e-mail...
self.assertEmailSent(to='test@example.org')
self.assertEqual(len(self.get_sent_messages()), 1)
</code></pre>
<p>Start your server and go to <code>http://localhost:8080/test</code>. You should notice that (an additional) 1/1 test was ran from <code>http://localhost:8080/test</code>.</p>
<p>Source: <a href="http://blog.randell.ph/2010/04/05/using-gae-testbed-with-gaeunit-testing-that-email-was-sent/" rel="nofollow">Using GAE Testbed with GAEUnit: Testing that email was sent</a></p>
| 1 | 2010-04-04T19:33:07Z | [
"python",
"unit-testing",
"google-app-engine",
"mocking"
]
|
Unit testing and mocking email sender in Python with Google AppEngine | 427,400 | <p>I'm a newbie to python and the app engine.</p>
<p>I have this code that sends an email based on request params after some auth logic. in my Unit tests (i'm using <a href="http://code.google.com/p/gaeunit/" rel="nofollow">GAEUnit</a>), how do I confirm an email with specific contents were sent? - i.e. how do I mock the emailer with a fake emailer to verify send was called?</p>
<pre><code>class EmailHandler(webapp.RequestHandler):
def bad_input(self):
self.response.set_status(400)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>bad input </body></html>")
def get(self):
to_addr = self.request.get("to")
subj = self.request.get("subject")
msg = self.request.get("body")
if not mail.is_email_valid(to_addr):
# Return an error message...
# self.bad_input()
pass
# authenticate here
message = mail.EmailMessage()
message.sender = "my.company@gmail.com"
message.to = to_addr
message.subject = subj
message.body = msg
message.send()
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>success!</body></html>")
</code></pre>
<p>And the unit tests,</p>
<pre><code>import unittest
from webtest import TestApp
from google.appengine.ext import webapp
from email import EmailHandler
class SendingEmails(unittest.TestCase):
def setUp(self):
self.application = webapp.WSGIApplication([('/', EmailHandler)], debug=True)
def test_success(self):
app = TestApp(self.application)
response = app.get('http://localhost:8080/send?to=vijay.santhanam@gmail.com&body=blah_blah_blah&subject=mySubject')
self.assertEqual('200 OK', response.status)
self.assertTrue('success' in response)
# somehow, assert email was sent
</code></pre>
| 5 | 2009-01-09T08:33:34Z | 7,579,200 | <p>Just use the following to get all messages sent since activating the mail stub.</p>
<pre><code>from google.appengine.api import apiproxy_stub_map
sent_messages = apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map['mail'].get_sent_messages()
</code></pre>
| 2 | 2011-09-28T06:34:36Z | [
"python",
"unit-testing",
"google-app-engine",
"mocking"
]
|
Unit testing and mocking email sender in Python with Google AppEngine | 427,400 | <p>I'm a newbie to python and the app engine.</p>
<p>I have this code that sends an email based on request params after some auth logic. in my Unit tests (i'm using <a href="http://code.google.com/p/gaeunit/" rel="nofollow">GAEUnit</a>), how do I confirm an email with specific contents were sent? - i.e. how do I mock the emailer with a fake emailer to verify send was called?</p>
<pre><code>class EmailHandler(webapp.RequestHandler):
def bad_input(self):
self.response.set_status(400)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>bad input </body></html>")
def get(self):
to_addr = self.request.get("to")
subj = self.request.get("subject")
msg = self.request.get("body")
if not mail.is_email_valid(to_addr):
# Return an error message...
# self.bad_input()
pass
# authenticate here
message = mail.EmailMessage()
message.sender = "my.company@gmail.com"
message.to = to_addr
message.subject = subj
message.body = msg
message.send()
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>success!</body></html>")
</code></pre>
<p>And the unit tests,</p>
<pre><code>import unittest
from webtest import TestApp
from google.appengine.ext import webapp
from email import EmailHandler
class SendingEmails(unittest.TestCase):
def setUp(self):
self.application = webapp.WSGIApplication([('/', EmailHandler)], debug=True)
def test_success(self):
app = TestApp(self.application)
response = app.get('http://localhost:8080/send?to=vijay.santhanam@gmail.com&body=blah_blah_blah&subject=mySubject')
self.assertEqual('200 OK', response.status)
self.assertTrue('success' in response)
# somehow, assert email was sent
</code></pre>
| 5 | 2009-01-09T08:33:34Z | 32,511,845 | <p>Google has a really simple way to do this in their <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/appengine/localtesting/test_mail.py" rel="nofollow">documentation</a>.</p>
<p>You create a testbed and mail stub in your setup like this:</p>
<pre><code>self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_mail_stub()
self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME)
</code></pre>
<p>Run your method and then check it like this:</p>
<pre><code> messages = self.mail_stub.get_sent_messages(to='alice@example.com')
self.assertEqual(1, len(messages))
self.assertEqual('alice@example.com', messages[0].to)
</code></pre>
| 1 | 2015-09-10T21:24:47Z | [
"python",
"unit-testing",
"google-app-engine",
"mocking"
]
|
How can I get the source code of a Python function? | 427,453 | <p>Suppose I have a Python function as defined below:</p>
<pre><code>def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
</code></pre>
<p>I can get the name of the function using <code>foo.func_name</code>. How can I programmatically get its source code, as I typed above?</p>
| 127 | 2009-01-09T09:02:37Z | 427,504 | <p>The <a href="http://docs.python.org/library/inspect.html?highlight=inspect#retrieving-source-code">inspect module</a> has methods for retreiving source code from python objects. Seemingly it only works if the source is located in a file though. If you had that I guess you wouldn't need to get the source from the object.</p>
| 120 | 2009-01-09T09:25:54Z | [
"python",
"function"
]
|
How can I get the source code of a Python function? | 427,453 | <p>Suppose I have a Python function as defined below:</p>
<pre><code>def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
</code></pre>
<p>I can get the name of the function using <code>foo.func_name</code>. How can I programmatically get its source code, as I typed above?</p>
| 127 | 2009-01-09T09:02:37Z | 427,524 | <p>I <em>believe</em> that variable names aren't stored in pyc/pyd/pyo files, so you can not retrieve the exact code lines if you don't have source files.</p>
| 0 | 2009-01-09T09:38:47Z | [
"python",
"function"
]
|
How can I get the source code of a Python function? | 427,453 | <p>Suppose I have a Python function as defined below:</p>
<pre><code>def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
</code></pre>
<p>I can get the name of the function using <code>foo.func_name</code>. How can I programmatically get its source code, as I typed above?</p>
| 127 | 2009-01-09T09:02:37Z | 427,533 | <p>If the function is from a source file available on the filesystem, then <a href="https://docs.python.org/3/library/inspect.html#inspect.getsourcelines"><code>inspect.getsourcelines(foo)</code></a> might be of help.</p>
<p>I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.</p>
| 180 | 2009-01-09T09:44:38Z | [
"python",
"function"
]
|
How can I get the source code of a Python function? | 427,453 | <p>Suppose I have a Python function as defined below:</p>
<pre><code>def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
</code></pre>
<p>I can get the name of the function using <code>foo.func_name</code>. How can I programmatically get its source code, as I typed above?</p>
| 127 | 2009-01-09T09:02:37Z | 10,196,254 | <p>If you're strictly defining the function yourself and it's a relatively short definition, a solution without dependencies would be to define the function in a string and assign the eval() of the expression to your function. </p>
<p>E.g. </p>
<pre><code>funcstring = 'lambda x: x> 5'
func = eval(funcstring)
</code></pre>
<p>then optionally to attach the original code to the function: </p>
<pre><code>func.source = funcstring
</code></pre>
| 1 | 2012-04-17T17:44:09Z | [
"python",
"function"
]
|
How can I get the source code of a Python function? | 427,453 | <p>Suppose I have a Python function as defined below:</p>
<pre><code>def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
</code></pre>
<p>I can get the name of the function using <code>foo.func_name</code>. How can I programmatically get its source code, as I typed above?</p>
| 127 | 2009-01-09T09:02:37Z | 17,358,307 | <p><code>dis</code> is your friend if the source code is not available:</p>
<pre><code>>>> import dis
>>> def foo(arg1,arg2):
... #do something with args
... a = arg1 + arg2
... return a
...
>>> dis.dis(foo)
3 0 LOAD_FAST 0 (arg1)
3 LOAD_FAST 1 (arg2)
6 BINARY_ADD
7 STORE_FAST 2 (a)
4 10 LOAD_FAST 2 (a)
13 RETURN_VALUE
</code></pre>
| 45 | 2013-06-28T06:11:18Z | [
"python",
"function"
]
|
How can I get the source code of a Python function? | 427,453 | <p>Suppose I have a Python function as defined below:</p>
<pre><code>def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
</code></pre>
<p>I can get the name of the function using <code>foo.func_name</code>. How can I programmatically get its source code, as I typed above?</p>
| 127 | 2009-01-09T09:02:37Z | 21,339,166 | <p>While I'd generally agree that <code>inspect</code> is a good answer, I'd disagree that you can't get the source code of objects defined in the interpreter. If you use <code>dill.source.getsource</code> from <a href="https://github.com/uqfoundation/dill"><code>dill</code></a>, you can get the source of functions and lambdas, even if they are defined interactively.
It also can get the code for from bound or unbound class methods and functions defined in curries... however, you might not be able to compile that code without the enclosing object's code.</p>
<pre><code>>>> from dill.source import getsource
>>>
>>> def add(x,y):
... return x+y
...
>>> squared = lambda x:x**2
>>>
>>> print getsource(add)
def add(x,y):
return x+y
>>> print getsource(squared)
squared = lambda x:x**2
>>>
>>> class Foo(object):
... def bar(self, x):
... return x*x+x
...
>>> f = Foo()
>>>
>>> print getsource(f.bar)
def bar(self, x):
return x*x+x
>>>
</code></pre>
| 27 | 2014-01-24T17:51:36Z | [
"python",
"function"
]
|
How can I get the source code of a Python function? | 427,453 | <p>Suppose I have a Python function as defined below:</p>
<pre><code>def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
</code></pre>
<p>I can get the name of the function using <code>foo.func_name</code>. How can I programmatically get its source code, as I typed above?</p>
| 127 | 2009-01-09T09:02:37Z | 25,107,178 | <p>To expand on runeh's answer:</p>
<pre><code>>>> def foo(a):
... x = 2
... return x + a
>>> import inspect
>>> inspect.getsource(foo)
u'def foo(a):\n x = 2\n return x + a\n'
print inspect.getsource(foo)
def foo(a):
x = 2
return x + a
</code></pre>
<p>EDIT: As pointed out by @0sh this example works using <code>ipython</code> but not plain <code>python</code>. It should be fine in both, however, when importing code from source files.</p>
| 14 | 2014-08-03T17:23:42Z | [
"python",
"function"
]
|
How can I get the source code of a Python function? | 427,453 | <p>Suppose I have a Python function as defined below:</p>
<pre><code>def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
</code></pre>
<p>I can get the name of the function using <code>foo.func_name</code>. How can I programmatically get its source code, as I typed above?</p>
| 127 | 2009-01-09T09:02:37Z | 37,111,797 | <p>If you are using IPython, then you need to type "foo??"</p>
<pre><code>In [19]: foo??
Signature: foo(arg1, arg2)
Source:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
File: ~/Desktop/<ipython-input-18-3174e3126506>
Type: function
</code></pre>
| 12 | 2016-05-09T09:11:05Z | [
"python",
"function"
]
|
Ordered lists in django | 428,149 | <p>i have very simple problem. I need to create model, that represent element of ordered list. This model can be implemented like this:</p>
<pre><code>class Item(models.Model):
data = models.TextField()
order = models.IntegerField()
</code></pre>
<p>or like this:</p>
<pre><code>class Item(models.Model):
data = models.TextField()
next = models.ForeignKey('self')
</code></pre>
<p>What way is preferred? What drawbacks have each solution?</p>
| 10 | 2009-01-09T14:06:13Z | 428,165 | <p>That depends on what you want to do. </p>
<p>The first one seems better to make a single query in the database and get all data in the correct order</p>
<p>The second one seems better to insert an element between two existing elements (because in the first one you'd have to change a lot of items if the numbers are sequential)</p>
<p>I'd use the first one, because it seems to fit better a database table, which is how django stores model data behind the hood.</p>
| 6 | 2009-01-09T14:12:35Z | [
"python",
"django",
"django-models"
]
|
Ordered lists in django | 428,149 | <p>i have very simple problem. I need to create model, that represent element of ordered list. This model can be implemented like this:</p>
<pre><code>class Item(models.Model):
data = models.TextField()
order = models.IntegerField()
</code></pre>
<p>or like this:</p>
<pre><code>class Item(models.Model):
data = models.TextField()
next = models.ForeignKey('self')
</code></pre>
<p>What way is preferred? What drawbacks have each solution?</p>
| 10 | 2009-01-09T14:06:13Z | 428,189 | <p>Essentially, the second solution you propose is a linked list. Linked list implemented at the database level are usually not a good idea. To retrieve a list of <code>n</code> elements, you will need <code>n</code> database access (or use complicated queries). Performance wise, retrieving a list in O(n) is awfully not efficient.</p>
<p>In regular code, linked list are used to get better insert performance compared to arrays (no need to move all elements around). In your database, updating all elements is not that complicated in only 2 queries :</p>
<pre><code>UPDATE item.order = item.order + 1 FROM item WHERE order > 3
INSERT INTO item (order, ...) VALUES (3, ...)
</code></pre>
<p>I remember seeing a reuseable app that implemented all that and a nice admin interface, but I cant find it right now ...</p>
<p>To summarize, definitly use solution #1 and stay away from solution #2 unless you have a very very good reason not to !</p>
| 18 | 2009-01-09T14:17:26Z | [
"python",
"django",
"django-models"
]
|
Ordered lists in django | 428,149 | <p>i have very simple problem. I need to create model, that represent element of ordered list. This model can be implemented like this:</p>
<pre><code>class Item(models.Model):
data = models.TextField()
order = models.IntegerField()
</code></pre>
<p>or like this:</p>
<pre><code>class Item(models.Model):
data = models.TextField()
next = models.ForeignKey('self')
</code></pre>
<p>What way is preferred? What drawbacks have each solution?</p>
| 10 | 2009-01-09T14:06:13Z | 428,460 | <p>There is another solution.</p>
<pre><code>class Item(models.Model):
data = models.TextField()
</code></pre>
<p>You can just pickle or marshal Python list into the data field and the load it up. This one is good for updating and reading, but not for searching e.g. fetching all lists that contain a specific item.</p>
| -6 | 2009-01-09T15:22:38Z | [
"python",
"django",
"django-models"
]
|
Why do managed attributes just work for class attributes and not for instance attributes in python? | 428,264 | <p>To illustrate the question check the following code:</p>
<pre><code>class MyDescriptor(object):
def __get__(self, obj, type=None):
print "get", self, obj, type
return self._v
def __set__(self, obj, value):
self._v = value
print "set", self, obj, value
return None
class SomeClass1(object):
m = MyDescriptor()
class SomeClass2(object):
def __init__(self):
self.m = MyDescriptor()
x1 = SomeClass1()
x2 = SomeClass2()
x1.m = 1000
# -> set <__main__.MyDescriptor object at 0xb787c7ec> <__main__.SomeClass1 object at 0xb787cc8c> 10000
x2.m = 1000 # I guess that this overwrites the function. But why?
# ->
print x1.m
# -> get <__main__.MyDescriptor object at 0xb787c7ec> <__main__.SomeClass1 object at 0xb787cc8c> <class '__main__.SomeClass1'> 10000
print x2.m
# -> 10000
</code></pre>
<ol>
<li>Why doesn't <strong>x2.m = 1000</strong> not call the <strong>__set__</strong>-function? It seems that this overwrites the function. But why?</li>
<li>Where is <strong>_v</strong> in x1? It is not in <strong>x1._v</strong></li>
</ol>
| 2 | 2009-01-09T14:38:13Z | 428,357 | <p>To answer your second question, where is <code>_v</code>?</p>
<p>Your version of the descriptor keeps <code>_v</code> in the descriptor itself. Each instance of the descriptor (the class-level instance <code>SomeClass1</code>, and all of the object-level instances in objects of class <code>SomeClass2</code> will have distinct values of <code>_v</code>.</p>
<p>Look at this version. This version updates the object associated with the descriptor. This means the object (<code>SomeClass1</code> or <code>x2</code>) will contain the attribute <code>_v</code>. </p>
<pre><code>class MyDescriptor(object):
def __get__(self, obj, type=None):
print "get", self, obj, type
return obj._v
def __set__(self, obj, value):
obj._v = value
print "set", self, obj, value
</code></pre>
| 3 | 2009-01-09T14:55:59Z | [
"python",
"attributes",
"descriptor"
]
|
Why do managed attributes just work for class attributes and not for instance attributes in python? | 428,264 | <p>To illustrate the question check the following code:</p>
<pre><code>class MyDescriptor(object):
def __get__(self, obj, type=None):
print "get", self, obj, type
return self._v
def __set__(self, obj, value):
self._v = value
print "set", self, obj, value
return None
class SomeClass1(object):
m = MyDescriptor()
class SomeClass2(object):
def __init__(self):
self.m = MyDescriptor()
x1 = SomeClass1()
x2 = SomeClass2()
x1.m = 1000
# -> set <__main__.MyDescriptor object at 0xb787c7ec> <__main__.SomeClass1 object at 0xb787cc8c> 10000
x2.m = 1000 # I guess that this overwrites the function. But why?
# ->
print x1.m
# -> get <__main__.MyDescriptor object at 0xb787c7ec> <__main__.SomeClass1 object at 0xb787cc8c> <class '__main__.SomeClass1'> 10000
print x2.m
# -> 10000
</code></pre>
<ol>
<li>Why doesn't <strong>x2.m = 1000</strong> not call the <strong>__set__</strong>-function? It seems that this overwrites the function. But why?</li>
<li>Where is <strong>_v</strong> in x1? It is not in <strong>x1._v</strong></li>
</ol>
| 2 | 2009-01-09T14:38:13Z | 428,423 | <p>You should read <a href="http://docs.python.org/reference/datamodel.html#implementing-descriptors" rel="nofollow">this</a> and <a href="http://users.rcn.com/python/download/Descriptor.htm" rel="nofollow">this</a>.</p>
<p>It overwrites the function because you didn't overload the <code>__set__</code> and <code>__get__</code> functions of SomeClass but of MyDescriptor class. Maybe you wanted for SomeClass to inherit MyDescriptor? SomeClass1 prints the "get" and "set" output because it's a static method AFAIK. For details read the upper links.</p>
| 3 | 2009-01-09T15:11:27Z | [
"python",
"attributes",
"descriptor"
]
|
Why do managed attributes just work for class attributes and not for instance attributes in python? | 428,264 | <p>To illustrate the question check the following code:</p>
<pre><code>class MyDescriptor(object):
def __get__(self, obj, type=None):
print "get", self, obj, type
return self._v
def __set__(self, obj, value):
self._v = value
print "set", self, obj, value
return None
class SomeClass1(object):
m = MyDescriptor()
class SomeClass2(object):
def __init__(self):
self.m = MyDescriptor()
x1 = SomeClass1()
x2 = SomeClass2()
x1.m = 1000
# -> set <__main__.MyDescriptor object at 0xb787c7ec> <__main__.SomeClass1 object at 0xb787cc8c> 10000
x2.m = 1000 # I guess that this overwrites the function. But why?
# ->
print x1.m
# -> get <__main__.MyDescriptor object at 0xb787c7ec> <__main__.SomeClass1 object at 0xb787cc8c> <class '__main__.SomeClass1'> 10000
print x2.m
# -> 10000
</code></pre>
<ol>
<li>Why doesn't <strong>x2.m = 1000</strong> not call the <strong>__set__</strong>-function? It seems that this overwrites the function. But why?</li>
<li>Where is <strong>_v</strong> in x1? It is not in <strong>x1._v</strong></li>
</ol>
| 2 | 2009-01-09T14:38:13Z | 431,475 | <p>I found <strong>_v</strong> of <strong>x1</strong>: It is in <strong>SomeClass1.__dict__['m']._v</strong></p>
<p>For the version suggested by S.Lott within the other answer: <strong>_v</strong> is in <strong>x1._v</strong></p>
| 0 | 2009-01-10T18:17:28Z | [
"python",
"attributes",
"descriptor"
]
|
How to programmatically change urls of images in word documents | 428,308 | <p>I have a set of word documents that contains a lot of non-embedded images in them. The url that the images point to no longer exist. I would like to programmatically change the domain name of the url to something else. How can I go about doing this in Java or Python ?</p>
| 1 | 2009-01-09T14:46:36Z | 428,338 | <p>Perhaps the <a href="http://download.microsoft.com/download/0/B/E/0BE8BDD7-E5E8-422A-ABFD-4342ED7AD886/Word97-2007BinaryFileFormat(doc)Specification.pdf" rel="nofollow">Microsoft Office Word binary file format specification</a> could help you here, though someone who already did stuff like this might come up with a better answer.</p>
| 0 | 2009-01-09T14:53:03Z | [
"java",
"python",
"image",
"ms-word"
]
|
How to programmatically change urls of images in word documents | 428,308 | <p>I have a set of word documents that contains a lot of non-embedded images in them. The url that the images point to no longer exist. I would like to programmatically change the domain name of the url to something else. How can I go about doing this in Java or Python ?</p>
| 1 | 2009-01-09T14:46:36Z | 428,525 | <p>This is the sort of thing that VBA is for:</p>
<pre><code>Sub HlinkChanger()
Dim oRange As Word.Range
Dim oField As Field
Dim link As Variant
With ActiveDocument
.Range.AutoFormat
For Each oRange In .StoryRanges
For Each oFld In oRange.Fields
If oFld.Type = wdFieldHyperlink Then
For Each link In oFld.Result.Hyperlinks
// the hyperlink is stored in link.Address
// strip the first x characters of the URL
// and replace them with your new URL
Next link
End If
Next oFld
Set oRange = oRange.NextStoryRange
Next oRange
</code></pre>
| 1 | 2009-01-09T15:38:07Z | [
"java",
"python",
"image",
"ms-word"
]
|
How to programmatically change urls of images in word documents | 428,308 | <p>I have a set of word documents that contains a lot of non-embedded images in them. The url that the images point to no longer exist. I would like to programmatically change the domain name of the url to something else. How can I go about doing this in Java or Python ?</p>
| 1 | 2009-01-09T14:46:36Z | 430,717 | <p>You want to do this in Java or Python. Try OpenOffice.
In OpenOffice, you can insert Java or Python code as a "Makro".</p>
<p>I'm sure there will be a possibility to change the image URLs.</p>
| 0 | 2009-01-10T07:45:26Z | [
"java",
"python",
"image",
"ms-word"
]
|
How to programmatically change urls of images in word documents | 428,308 | <p>I have a set of word documents that contains a lot of non-embedded images in them. The url that the images point to no longer exist. I would like to programmatically change the domain name of the url to something else. How can I go about doing this in Java or Python ?</p>
| 1 | 2009-01-09T14:46:36Z | 1,615,775 | <p>The VBA answer is the closest because this is best done using the Microsoft Word COM API. However, you can use this just as well from Python. I've used it myself to import data into a database from hundreds of forms that were Word Documents.</p>
<p><a href="http://snippets.dzone.com/posts/show/2037" rel="nofollow">This article</a> explains the basics. Note that even though it creates a class wrapper for the WordDocument COM object, you don't need to do this if you don't want to. You can just access the COM API directly.</p>
<p>For documentation of the WordDocument COM API, open a word document, press Alt-F11 to open the VBA editor, and then F2 to view the object browser. This allows you to browse through all of the objects and the methods that they provide. An introduction to Python and the COM object model <a href="http://www.boddie.org.uk/python/COM.html" rel="nofollow">is found here</a>. </p>
| 0 | 2009-10-23T20:41:28Z | [
"java",
"python",
"image",
"ms-word"
]
|
Measure load time for python cgi script? | 428,704 | <p>I use python cgi for our intranet application.</p>
<p>When I measure time, the script takes 4s to finish. But after that, it still takes another 11s to show the screen in the browser.
The screen is build with tables (size: 10 KB, 91 KB uncompressed) and has a large css file (5 KB, 58 KB uncompressed).</p>
<p>I used YSlow and did as much optimization as suggested. Gzipping etc.
Firebug Net says: 11s for the file.</p>
<p>How do I measure where these last 11 seconds are needed for?
Is it just the size of the HTML, or the table structure?
Anyone more ideas for tweaking?</p>
| 2 | 2009-01-09T16:19:11Z | 428,767 | <p>I think I'd grab a copy of Ethereal and watch the TCP connection between the browser and the script, if I were concerned about whether the server is not getting its job done in an acceptable amount of time. If you see the TCP socket close before that 11s gap, you know that your issue is entirely on the browser side. If the TCP close comes well into the 11s gap, then you're going to have to do some debugging on the http server side.</p>
<p>I think that Ethereal has changed it's name to WireShark. Whatever it is calling itself recently, it's a must-have tool for this sort of work. I was using it just the other day to find out why I couldn't connect to my virtualized http server.</p>
| 1 | 2009-01-09T16:31:46Z | [
"python",
"html",
"css",
"browser",
"cgi"
]
|
Measure load time for python cgi script? | 428,704 | <p>I use python cgi for our intranet application.</p>
<p>When I measure time, the script takes 4s to finish. But after that, it still takes another 11s to show the screen in the browser.
The screen is build with tables (size: 10 KB, 91 KB uncompressed) and has a large css file (5 KB, 58 KB uncompressed).</p>
<p>I used YSlow and did as much optimization as suggested. Gzipping etc.
Firebug Net says: 11s for the file.</p>
<p>How do I measure where these last 11 seconds are needed for?
Is it just the size of the HTML, or the table structure?
Anyone more ideas for tweaking?</p>
| 2 | 2009-01-09T16:19:11Z | 428,832 | <p>with that much html to render I would also consider the speed of the computer. you can test this by saving the html file and opening it from your local hard drive :)</p>
| 1 | 2009-01-09T16:51:45Z | [
"python",
"html",
"css",
"browser",
"cgi"
]
|
How can I get the created date of a file on the web (with Python)? | 428,895 | <p>I have a python application that relies on a file that is downloaded by a client from a website.</p>
<p>The website is not under my control and has no API to check for a "latest version" of the file.</p>
<p>Is there a simple way to access the file (in python) via a URL and check it's date (or size) without having to download it to the clients machine each time?</p>
<p><strong>update:</strong> Thanks to those who mentioned the"last-modified" date. This is the correct parameter to look at.</p>
<p>I guess I didn't state the question well enough. How do I do this from a python script? I want to application to check the file and then download it if (last-modified date < current file date).</p>
| 1 | 2009-01-09T17:11:15Z | 428,899 | <p>Check the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.29" rel="nofollow">Last-Modified</a> header.</p>
<p>EDIT: Try <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml#introduction" rel="nofollow">urllib2</a>.</p>
<p>EDIT 2: This <a href="http://www.artima.com/forums/flat.jsp?forum=122&thread=15024" rel="nofollow">short tutorial</a> should give you a pretty good feel for accomplishing your goal.</p>
| 4 | 2009-01-09T17:13:09Z | [
"python",
"http"
]
|
How can I get the created date of a file on the web (with Python)? | 428,895 | <p>I have a python application that relies on a file that is downloaded by a client from a website.</p>
<p>The website is not under my control and has no API to check for a "latest version" of the file.</p>
<p>Is there a simple way to access the file (in python) via a URL and check it's date (or size) without having to download it to the clients machine each time?</p>
<p><strong>update:</strong> Thanks to those who mentioned the"last-modified" date. This is the correct parameter to look at.</p>
<p>I guess I didn't state the question well enough. How do I do this from a python script? I want to application to check the file and then download it if (last-modified date < current file date).</p>
| 1 | 2009-01-09T17:11:15Z | 428,951 | <p>There is no reliable way to do this. For all you know, the file can be created on the fly by the web server and the question "how old is this file" is not meaningful. The webserver may choose to provide Last-Modified header, but it could tell you whatever it wants.</p>
| 5 | 2009-01-09T17:29:52Z | [
"python",
"http"
]
|
How can I get the created date of a file on the web (with Python)? | 428,895 | <p>I have a python application that relies on a file that is downloaded by a client from a website.</p>
<p>The website is not under my control and has no API to check for a "latest version" of the file.</p>
<p>Is there a simple way to access the file (in python) via a URL and check it's date (or size) without having to download it to the clients machine each time?</p>
<p><strong>update:</strong> Thanks to those who mentioned the"last-modified" date. This is the correct parameter to look at.</p>
<p>I guess I didn't state the question well enough. How do I do this from a python script? I want to application to check the file and then download it if (last-modified date < current file date).</p>
| 1 | 2009-01-09T17:11:15Z | 428,986 | <p>In HTTP 1.1, the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1" rel="nofollow">Content-Disposition header field</a> is intended to hold this kind of information in the <code>creation-date</code> parameter (see <a href="http://www.ietf.org/rfc/rfc2183.txt" rel="nofollow">RFC 2183</a>).</p>
| 2 | 2009-01-09T17:38:47Z | [
"python",
"http"
]
|
How can I get the created date of a file on the web (with Python)? | 428,895 | <p>I have a python application that relies on a file that is downloaded by a client from a website.</p>
<p>The website is not under my control and has no API to check for a "latest version" of the file.</p>
<p>Is there a simple way to access the file (in python) via a URL and check it's date (or size) without having to download it to the clients machine each time?</p>
<p><strong>update:</strong> Thanks to those who mentioned the"last-modified" date. This is the correct parameter to look at.</p>
<p>I guess I didn't state the question well enough. How do I do this from a python script? I want to application to check the file and then download it if (last-modified date < current file date).</p>
| 1 | 2009-01-09T17:11:15Z | 429,239 | <p>I built a tool that does this based on etags. Sounds a lot like what you're describing:</p>
<p><a href="http://github.com/dustin/pfetch" rel="nofollow">pfetch</a> is a twisted tool that does this on a schedule and can run with many, many URLs and trigger events upon change (post-download). It's pretty simple, but still might be more complicated than you want.</p>
<p><a href="http://github.com/dustin/snippets/tree/master/python/net/http/fetch.py" rel="nofollow">This code</a> however, is exactly what you're asking for.</p>
<p>So, take your pick. :)</p>
| 0 | 2009-01-09T18:50:27Z | [
"python",
"http"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.