title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Dynamically import a method in a file, from a string | 8,790,003 | 25 | 2012-01-09T14:33:28Z | 8,790,077 | 14 | 2012-01-09T14:39:26Z | [
"python",
"dynamic",
"import",
"dynamic-import"
] | I have a string, say: `abc.def.ghi.jkl.myfile.mymethod`. How do I dynamically import `mymethod`?
Here is how I went about it:
```
def get_method_from_file(full_path):
if len(full_path) == 1:
return map(__import__,[full_path[0]])[0]
return getattr(get_method_from_file(full_path[:-1]),full_path[-1])
i... | You don't need to import the individual modules. It is enough to import the module you want to import a name from and provide the `fromlist` argument:
```
def import_from(module, name):
module = __import__(module, fromlist=[name])
return getattr(module, name)
```
For your example `abc.def.ghi.jkl.myfile.mymet... |
Dynamically import a method in a file, from a string | 8,790,003 | 25 | 2012-01-09T14:33:28Z | 8,790,232 | 28 | 2012-01-09T14:51:01Z | [
"python",
"dynamic",
"import",
"dynamic-import"
] | I have a string, say: `abc.def.ghi.jkl.myfile.mymethod`. How do I dynamically import `mymethod`?
Here is how I went about it:
```
def get_method_from_file(full_path):
if len(full_path) == 1:
return map(__import__,[full_path[0]])[0]
return getattr(get_method_from_file(full_path[:-1]),full_path[-1])
i... | From Python 2.7 you can use the [importlib.import\_module()](http://docs.python.org/library/importlib.html#importlib.import_module) function. You can import a module and access an object defined within it with the following code:
```
from importlib import import_module
p, m = name.rsplit('.', 1)
mod = import_module(... |
Can't import modules that are there | 8,790,038 | 13 | 2012-01-09T14:35:48Z | 8,790,063 | 12 | 2012-01-09T14:38:21Z | [
"python",
"google-app-engine",
"python-2.7"
] | From command line I can't import appengine, this might be something with my python path:
```
$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from google.appengine.ext import db
Traceback (most recent call last)... | appending:
```
/usr/local/google_appengine/:/usr/local/google_appengine/lib/:/usr/local/google_appengine/lib/yaml/
```
to your PYTHONPATH environment variable should do the trick (your SDK location may vary). |
Can't import modules that are there | 8,790,038 | 13 | 2012-01-09T14:35:48Z | 24,494,752 | 7 | 2014-06-30T16:28:09Z | [
"python",
"google-app-engine",
"python-2.7"
] | From command line I can't import appengine, this might be something with my python path:
```
$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from google.appengine.ext import db
Traceback (most recent call last)... | For appengine 1.9.6 google has created a new directory "yaml-3.10" that contains the yaml module. I added "[appengine install directory]/google\_appengine/lib/yaml-3.10" to PYTHONPATH in my .bashrc file and that solved this problem. BTW: I use Ubuntu 14.04 LTS. |
Can Python call Delphi functions in a DLL? | 8,790,123 | 8 | 2012-01-09T14:42:56Z | 8,790,399 | 11 | 2012-01-09T15:01:45Z | [
"python",
"delphi",
"dll",
"ctypes"
] | I am trying to call functions from a DLL which seems to be created in Delphi. An example of a some functions supported by the DLL are:
```
function oziDeleteWpByName(var name:pansichar):integer;stdcall
```
The Python code I have written to access the above functions is not working.
```
from ctypes import *
libc = cd... | ```
from ctypes import *
# Not strictly needed but it's good to be explicit.
windll.OziAPI.oziDeleteWpByName.argtypes = [POINTER(c_char_p)]
windll.OziAPI.oziDeleteWpByName.restype = c_int
p = c_char_p('test')
retval = windll.OziAPI.oziDeleteWpByName(byref(p))
``` |
how do I launch IDLE, the development environment for Python, on Mac OS 10.7? | 8,792,044 | 14 | 2012-01-09T16:50:24Z | 8,792,311 | 32 | 2012-01-09T17:11:05Z | [
"python",
"python-idle"
] | I am running python 2.7.1. I can't figure out how to launch the IDLE IDE. I am told it comes already installed with python, but I can't find it using spotlight. | In the stock Mac OS X python installation, idle is found in /usr/bin, which is not (easily) accessible from Finder and not indexed by Spotlight. The quickest option is to open the Terminal utility and type 'idle' at the prompt. For a more Mac-like way of opening it, you'll have to create a small app or shortcut to laun... |
how do I launch IDLE, the development environment for Python, on Mac OS 10.7? | 8,792,044 | 14 | 2012-01-09T16:50:24Z | 16,549,790 | 16 | 2013-05-14T17:59:48Z | [
"python",
"python-idle"
] | I am running python 2.7.1. I can't figure out how to launch the IDLE IDE. I am told it comes already installed with python, but I can't find it using spotlight. | When you open up a new terminal window, just type in
```
idle
```

Then you will see a little rocket icon show up as IDLE loads

Then the Python shell opens up for you to edit
 and if so, sets `z` to the third character:
```
if x == 'a' and y == 'b' or x == 'b' and y == 'a':
z = 'c'
elif x == 'b' and y == 'c' or x == 'c' and y == 'b':
z = 'a'
elif x == 'a' ... | ```
z = (set(("a", "b", "c")) - set((x, y))).pop()
```
I am assuming that one of the three cases in your code holds. If this is the case, the set `set(("a", "b", "c")) - set((x, y))` will consist of a single element, which is returned by `pop()`.
**Edit:** As suggested by Raymond Hettinger in the comments, you could ... |
How can I find the missing value more concisely? | 8,792,440 | 76 | 2012-01-09T17:21:31Z | 8,792,480 | 18 | 2012-01-09T17:24:21Z | [
"python",
"benchmarking",
"microbenchmark"
] | The following code checks if `x` and `y` are distinct values (the variables `x`, `y`, `z` can only have values `a`, `b`, or `c`) and if so, sets `z` to the third character:
```
if x == 'a' and y == 'b' or x == 'b' and y == 'a':
z = 'c'
elif x == 'b' and y == 'c' or x == 'c' and y == 'b':
z = 'a'
elif x == 'a' ... | ```
z = (set('abc') - set(x + y)).pop()
```
Here are all of the scenarios to show that it works:
```
>>> (set('abc') - set('ab')).pop() # x is a/b and y is b/a
'c'
>>> (set('abc') - set('bc')).pop() # x is b/c and y is c/b
'a'
>>> (set('abc') - set('ac')).pop() # x is a/c and y is c/a
'b'
``` |
How can I find the missing value more concisely? | 8,792,440 | 76 | 2012-01-09T17:21:31Z | 8,792,698 | 13 | 2012-01-09T17:39:58Z | [
"python",
"benchmarking",
"microbenchmark"
] | The following code checks if `x` and `y` are distinct values (the variables `x`, `y`, `z` can only have values `a`, `b`, or `c`) and if so, sets `z` to the third character:
```
if x == 'a' and y == 'b' or x == 'b' and y == 'a':
z = 'c'
elif x == 'b' and y == 'c' or x == 'c' and y == 'b':
z = 'a'
elif x == 'a' ... | I think the solution by Sven Marnach and F.J is beautiful, but it's not faster in my little test. This is Raymond's optimized version using a pre-computed `set`:
```
$ python -m timeit -s "choices = set('abc')" \
-s "x = 'c'" \
-s "y = 'a'" \
"z, = choices - ... |
How can I find the missing value more concisely? | 8,792,440 | 76 | 2012-01-09T17:21:31Z | 8,792,747 | 8 | 2012-01-09T17:44:02Z | [
"python",
"benchmarking",
"microbenchmark"
] | The following code checks if `x` and `y` are distinct values (the variables `x`, `y`, `z` can only have values `a`, `b`, or `c`) and if so, sets `z` to the third character:
```
if x == 'a' and y == 'b' or x == 'b' and y == 'a':
z = 'c'
elif x == 'b' and y == 'c' or x == 'c' and y == 'b':
z = 'a'
elif x == 'a' ... | ```
z = 'a'*('a' not in x+y) or 'b'*('b' not in x+y) or 'c'
```
or less hackish and using Conditional Assignment
```
z = 'a' if ('a' not in x+y) else 'b' if ('b' not in x+y) else 'c'
```
but probably the dict solution is faster... you'd have to time it. |
How can I find the missing value more concisely? | 8,792,440 | 76 | 2012-01-09T17:21:31Z | 8,792,761 | 8 | 2012-01-09T17:45:01Z | [
"python",
"benchmarking",
"microbenchmark"
] | The following code checks if `x` and `y` are distinct values (the variables `x`, `y`, `z` can only have values `a`, `b`, or `c`) and if so, sets `z` to the third character:
```
if x == 'a' and y == 'b' or x == 'b' and y == 'a':
z = 'c'
elif x == 'b' and y == 'c' or x == 'c' and y == 'b':
z = 'a'
elif x == 'a' ... | Try this option, using dictionaries:
```
z = {'ab':'c', 'ba':'c', 'bc':'a', 'cb':'a', 'ac':'b', 'ca':'b'}[x+y]
```
Of course, if the `x+y` key is not present in the map, it'll produce a `KeyError` which you'll have to handle.
If the dictionary is precomputed a single time and stored for future use, the access will b... |
How can I find the missing value more concisely? | 8,792,440 | 76 | 2012-01-09T17:21:31Z | 8,792,994 | 15 | 2012-01-09T18:02:04Z | [
"python",
"benchmarking",
"microbenchmark"
] | The following code checks if `x` and `y` are distinct values (the variables `x`, `y`, `z` can only have values `a`, `b`, or `c`) and if so, sets `z` to the third character:
```
if x == 'a' and y == 'b' or x == 'b' and y == 'a':
z = 'c'
elif x == 'b' and y == 'c' or x == 'c' and y == 'b':
z = 'a'
elif x == 'a' ... | If the three items in question weren't `"a"`, `"b"` and `"c"`, but rather `1`, `2` and `3`, you could also use a binary XOR:
```
z = x ^ y
```
More generally, if you want to set `z` to the remaining one of three numbers `a`, `b` and `c` given two numbers `x` and `y` from this set, you can use
```
z = x ^ y ^ a ^ b ^... |
How can I find the missing value more concisely? | 8,792,440 | 76 | 2012-01-09T17:21:31Z | 8,793,742 | 28 | 2012-01-09T19:06:26Z | [
"python",
"benchmarking",
"microbenchmark"
] | The following code checks if `x` and `y` are distinct values (the variables `x`, `y`, `z` can only have values `a`, `b`, or `c`) and if so, sets `z` to the third character:
```
if x == 'a' and y == 'b' or x == 'b' and y == 'a':
z = 'c'
elif x == 'b' and y == 'c' or x == 'c' and y == 'b':
z = 'a'
elif x == 'a' ... | Sven's excellent code did just a little too much work and chould have used tuple unpacking instead of *pop()*. Also, it could have added a guard `if x != y` to check for *x* and *y* being distinct. Here is what the improved answer looks like:
```
# create the set just once
choices = {'a', 'b', 'c'}
x = 'a'
y = 'b'
#... |
How can I find the missing value more concisely? | 8,792,440 | 76 | 2012-01-09T17:21:31Z | 8,793,849 | 47 | 2012-01-09T19:15:29Z | [
"python",
"benchmarking",
"microbenchmark"
] | The following code checks if `x` and `y` are distinct values (the variables `x`, `y`, `z` can only have values `a`, `b`, or `c`) and if so, sets `z` to the third character:
```
if x == 'a' and y == 'b' or x == 'b' and y == 'a':
z = 'c'
elif x == 'b' and y == 'c' or x == 'c' and y == 'b':
z = 'a'
elif x == 'a' ... | The `strip` method is another option that runs quickly for me:
```
z = 'abc'.strip(x+y) if x!=y else None
``` |
In the Sphinx doc generator, can I add an entire package (recursivly) to the Index? | 8,792,643 | 10 | 2012-01-09T17:35:09Z | 8,793,084 | 14 | 2012-01-09T18:09:23Z | [
"python",
"python-sphinx"
] | I want to generate documentation for my package. Every file in the project contains extensive documentation. Is there a way to quickly add my entire project to the documetation index?
I'd like to automatically generate some documentation for the entire project with as little as possible work. I started by adding the f... | You can use `sphinx-apidoc`.
From the [official documentation](http://sphinx.pocoo.org/man/sphinx-apidoc.html): *sphinx-apidoc is a tool for automatic generation of Sphinx sources that, using the autodoc extension, document a whole package in the style of other automatic API documentation tools.*
An usage example co... |
Embedding HTML in restructured text on PyPi package pages | 8,792,817 | 10 | 2012-01-09T17:48:50Z | 8,894,565 | 7 | 2012-01-17T12:25:48Z | [
"python",
"python-sphinx",
"restructuredtext",
"pypi"
] | In [Sphinx](http://sphinx.pocoo.org/) I know that you can do it:
```
.. raw:: html
<div style="margin-top:10px;">
<iframe width="560" height="315" src="http://www.youtube.com/embed/_EjisXtMy_Y" frameborder="0" allowfullscreen></iframe>
</div>
```
In [pypi](http://pypi.python.org/pypi), is there some wa... | The point of PyPI is a module package index for quick reference and access to Python modules and packages. It isn't intended to be a customizable media site. You can add a fair amount of information to the index page for your modules and packages you put onto it, but it isn't intended for anything more than an index si... |
Python: can a decorator determine if a function is being defined inside a class? | 8,793,233 | 11 | 2012-01-09T18:24:12Z | 8,793,684 | 10 | 2012-01-09T19:01:14Z | [
"python",
"inspect"
] | I'm writing a decorator, and for various annoying reasons[0] it would be expedient to check if the function it is wrapping is being defined stand-alone or as part of a class (and further which classes that new class is subclassing).
For example:
```
def my_decorator(f):
defined_in_class = ??
print "%r: %s" %(... | Take a look at the output of `inspect.stack()` when you wrap a method. When your decorator's execution is underway, the current stack frame is the function call to your decorator; the next stack frame down is the `@` wrapping action that is being applied to the new method; and the third frame will be the class definiti... |
How to convert to a Python datetime object with JSON.loads? | 8,793,448 | 15 | 2012-01-09T18:43:03Z | 10,734,224 | 9 | 2012-05-24T08:58:27Z | [
"python",
"json",
"datetime"
] | I have a string representation of a JSON object.
```
dumped_dict = '{"debug": false, "created_at": "2020-08-09T11:24:20"}'
```
When I call json.loads with this object;
```
json.loads(dumped_dict)
```
I get;
```
{'created_at': '2020-08-09T11:24:20', 'debug': False}
```
There is nothing wrong in here. However, I wa... | My solution so far:
```
>>> json_string = '{"last_updated": {"$gte": "Thu, 1 Mar 2012 10:00:49 UTC"}}'
>>> dct = json.loads(json_string, object_hook=datetime_parser)
>>> dct
{u'last_updated': {u'$gte': datetime.datetime(2012, 3, 1, 10, 0, 49)}}
def datetime_parser(dct):
for k, v in dct.items():
if isinst... |
How to split a sequence according to a predicate? | 8,793,772 | 9 | 2012-01-09T19:09:04Z | 8,793,838 | 10 | 2012-01-09T19:14:57Z | [
"python"
] | I very often run into the need to split a sequence into the two subsequences of elements that satisfy and don't satisfy a given predicate (preserving the original relative ordering).
This hypothetical "splitter" function would look something like this in action:
```
>>> data = map(str, range(14))
>>> pred = lambda i:... | Partitioning is one of those [itertools recipes](http://docs.python.org/dev/library/itertools.html#itertools-recipes) that does just that. It uses [`tee()`](http://docs.python.org/dev/library/itertools.html#itertools.tee) to make sure it's iterating the collection in one pass despite the multiple iterators, the builtin... |
How to split a sequence according to a predicate? | 8,793,772 | 9 | 2012-01-09T19:09:04Z | 8,793,925 | 17 | 2012-01-09T19:21:19Z | [
"python"
] | I very often run into the need to split a sequence into the two subsequences of elements that satisfy and don't satisfy a given predicate (preserving the original relative ordering).
This hypothetical "splitter" function would look something like this in action:
```
>>> data = map(str, range(14))
>>> pred = lambda i:... | I know you said you didn't want to write your own function, but I can't imagine why. Your solutions involve writing your own code, you just aren't modularizing them into functions.
This does exactly what you want, is understandable, and only evaluates the predicate once per element:
```
def splitter(data, pred):
... |
How to test if exception in ok in unittest | 8,793,835 | 2 | 2012-01-09T19:14:33Z | 8,793,918 | 8 | 2012-01-09T19:21:03Z | [
"python",
"unit-testing",
"testing",
"assert"
] | I have a question about unittest.
How to make a test to see if is there an exception?
an example:
Datum(3,32,2012)
If i call class Datum like this, where month is not in range (>31), it's everything OK, it throws an Exception and thats OK. But I want to make an unittest if Exception is OK, if is catching an exception... | Use
```
self.assertRaises(ValueError,Datum,3,32,2012)
```
in your `unittest.TestCase` test to assert that `Datum(3,32,2012)` raises a `ValueError`.
Reference:
* [Documentation](http://docs.python.org/library/unittest.html#unittest.TestCase.assertEqual) on the various types of `asserts` you can make in
TestCases. |
how to copy modules from one virtualenv to another | 8,793,877 | 16 | 2012-01-09T19:17:33Z | 8,794,404 | 28 | 2012-01-09T20:01:25Z | [
"python",
"django",
"virtualenv",
"pip"
] | Is it possibe to copy python modules from one virtualenv to another.If so how is this done? | As long as you're moving them from one virtualenv to another on the *same* machine, you could easily just do:
```
$ cp -r [env1]/lib/pythonX.X/site-packages/* [env2]/lib/pythonX.X/site-packages/
```
However, if the environments are on different machines or utilizing different versions of python or some other major di... |
How to pip install a package with min and max version range? | 8,795,617 | 89 | 2012-01-09T21:44:41Z | 8,811,418 | 112 | 2012-01-10T22:25:01Z | [
"python",
"pip",
"multiple-versions"
] | I'm wondering if there's any way to tell pip, specifically in a requirements file, to install a package with both a minimum version (`pip install package>=0.2`) and a maximum version which should never be installed (theoretical api: `pip install package<0.3`).
I ask because I am using a third party library that's in a... | You can do:
```
$ pip install "package>=0.2,<0.3"
```
And `pip` will look for the best match, assuming the version is at least 0.2, and less than 0.3.
This also applies to pip [requirements files](https://pip.readthedocs.io/en/stable/reference/pip_install/#requirements-file-format). See the full details on version s... |
How does this particular parameter receive a value? | 8,796,655 | 2 | 2012-01-09T21:53:17Z | 8,796,657 | 7 | 2012-01-09T22:11:42Z | [
"python"
] | I have the following script that is taken from a python game development book. The author explains everything, except for one thing. I tried to figure it out myself, but as a beginner it is not making much sense. Here is the code:
```
import random
import time
def displayIntro():
print('You are on a planet full o... | The parameter chosenCave receives its value when the checkCave function is invoked. Prior to that it doesn't have a value.
When you define a function you have to option to declare parameters to that function. That's where you see chosenCave in the parenthese next to the name of the function. Those parentheses create w... |
pyserial - possible to write to serial port from thread a, do blocking reads from thread b? | 8,796,800 | 5 | 2012-01-09T23:46:39Z | 8,808,218 | 9 | 2012-01-10T18:09:23Z | [
"python",
"serial-port",
"pyserial"
] | I tried googling this, couldn't find an answer, searched here, couldn't find an answer. Has anyone looked into whether it's thread safe to write to a Serial() object (pyserial) from thread a and do blocking reads from thread b?
I know how to use thread synchronization primitives and thread-safe data structures, and in... | I have done this with pyserial. Reading from one thread and writing from another should not cause problems in general, since there isn't really any kind of resource arbitration problem. Serial ports are full duplex, so reading and writing can happen completely independently and at the same time. |
Is it safe to just implement __lt__ for a class that will be sorted? | 8,796,886 | 14 | 2012-01-10T00:00:11Z | 8,796,908 | 22 | 2012-01-10T00:02:44Z | [
"python",
"sorting"
] | Suppose instances of my ClassA will end up in a data structure and we know sorted() will be called on it. It's someone else's code that'll call sorted() so I can't specify a sorting function but I can implement whatever methods are appropriate on ClassA.
It appears to me that
```
def __lt__(self, other):
```
is suff... | [PEP 8](http://www.python.org/dev/peps/pep-0008/) recommends against this practice. I also recommend against it because it is a fragile programming style (not robust against minor code modifications):
Instead, consider using the [functools.total\_ordering](http://docs.python.org/library/functools.html#functools.total_... |
Algorithm to extract network info from ifconfig (ubuntu) | 8,797,130 | 2 | 2012-01-10T00:32:46Z | 8,797,477 | 10 | 2012-01-10T01:21:45Z | [
"python",
"regex"
] | Im trying to parse info from ifconfig (ubuntu). Normally, I would split a chunk of data like this down into words, and then search for substrings to get what I want. For example, given `line = "inet addr:192.168.98.157 Bcast:192.168.98.255 Mask:255.255.255.0"`, and looking for the broadcast address, I would do:
```
fo... | Rather than reinventing the wheel:
* <https://pypi.python.org/pypi/python-ifconfig/0.1>
Or if you want a portable-ish version that works on multiple platforms..
* <https://pypi.python.org/pypi/netifaces/> |
Optimizing matplotlib pyplot: plotting for many small plots | 8,798,040 | 4 | 2012-01-10T02:57:44Z | 8,798,113 | 10 | 2012-01-10T03:11:40Z | [
"python",
"optimization",
"plot",
"matplotlib"
] | I want to make a movie of some plotted points moving around for a rudimentary traffic simulation. Plotting takes forever, though--~10 frames takes 7s!! What's up with that?
Python code:
```
import numpy as np
import matplotlib.pyplot as plt
import cProfile
def slowww_plot():
for i in range(10):
plt.plot(... | You're doing it very inefficiently if you want an animation.
Instead of making a new figure each time, just set the new data and redraw the existing figure.
For example:
```
import matplotlib.pyplot as plt
import numpy as np
xy = 100 * np.random.random((2,10))
x, y = xy
fig, ax = plt.subplots()
points, = ax.plot(x... |
Securing communication [Authenticity, Privacy & Integrity] with mobile app? | 8,798,707 | 32 | 2012-01-10T04:51:26Z | 8,803,983 | 21 | 2012-01-10T13:26:54Z | [
"android",
"iphone",
"python",
"django",
"security"
] | An Android/Iphone app will be accessing application data from the server.
[Django-Python]
How can I secure the communication with the mobile app ?
**Expectation** : Secure enough for sensitive information like passwords, there shall be no direct way of decryption except brute-forcing.
**My requirements** :
* Authen... | You're working on bad information. SSL can absolutely authenticate the client, it's just not something that is done for the bulk of SSL as the protocol is (or, atleast was) typically used to protect e-commerce sites where authentication of the server was important but doing so with the client was not important and/or n... |
IOError: [Errno 13] file not accessible with Google AppEngine 1.6.1 | 8,799,304 | 10 | 2012-01-10T06:16:00Z | 10,817,205 | 7 | 2012-05-30T13:22:36Z | [
"python",
"google-app-engine"
] | Maybe it's a bug, but I'm posting here anyway.
I get the following issue on my local AppEngine testing server:
```
WARNING 2012-01-10 06:08:40,336 rdbms_mysqldb.py:90] The rdbms API is not available because the MySQLdb library could not be loaded.
INFO 2012-01-10 06:08:40,470 appengine_rpc.py:159] Server: appeng... | Simply remove the file `setuptools-0.6c11-py2.7.egg` from your site packages.
**Find the location of your site packages**
Start python CLI:
```
python
```
List site packages:
```
>>> import site; site.getsitepackages()
``` |
IOError: [Errno 13] file not accessible with Google AppEngine 1.6.1 | 8,799,304 | 10 | 2012-01-10T06:16:00Z | 18,728,313 | 12 | 2013-09-10T20:36:21Z | [
"python",
"google-app-engine"
] | Maybe it's a bug, but I'm posting here anyway.
I get the following issue on my local AppEngine testing server:
```
WARNING 2012-01-10 06:08:40,336 rdbms_mysqldb.py:90] The rdbms API is not available because the MySQLdb library could not be loaded.
INFO 2012-01-10 06:08:40,470 appengine_rpc.py:159] Server: appeng... | I have another answer to his problem, which I experienced by myself. If you have for example a templates directory like this:
```
templates
|-- css
|-- img
|-- js
|-- html
```
And your app.yaml file like this:
```
- url: /templates
static_dir: templates
```
You are not able to render a template with jinja2 if you... |
How to calculate next Friday in Python? | 8,801,084 | 11 | 2012-01-10T09:37:01Z | 8,801,197 | 16 | 2012-01-10T09:45:23Z | [
"python",
"python-2.x"
] | I need to know how I can calculate the date of the next Friday?
I'm new to Python:)
Thanks! | To start off, you'll need the `datetime` library:
```
import datetime
```
Then you need a starting date; that is, today.
```
d = datetime.date.today()
```
Starting from there, you'll want to keep going forward until you reach Friday. The `date.weekday` method represents Monday through Sunday as 0 through 6, so:
``... |
How to calculate next Friday in Python? | 8,801,084 | 11 | 2012-01-10T09:37:01Z | 8,801,540 | 28 | 2012-01-10T10:11:03Z | [
"python",
"python-2.x"
] | I need to know how I can calculate the date of the next Friday?
I'm new to Python:)
Thanks! | A certain improvement on @taymon`s answer:
```
today = datetime.date.today()
friday = today + datetime.timedelta( (4-today.weekday()) % 7 )
```
4 is Friday's weekday (0 based, counting from Monday).
`( (4-today.weekday()) % 7)` is the number of days till next friday (`%` is always non-negative).
After seeing @ubun... |
How to calculate next Friday in Python? | 8,801,084 | 11 | 2012-01-10T09:37:01Z | 8,802,124 | 10 | 2012-01-10T10:55:36Z | [
"python",
"python-2.x"
] | I need to know how I can calculate the date of the next Friday?
I'm new to Python:)
Thanks! | Here is how you could do it using [dateutil](http://niemeyer.net/python-dateutil):
```
import datetime as DT
import dateutil.relativedelta as REL
today = DT.date.today()
print(today)
# 2012-01-10
rd = REL.relativedelta(days=1, weekday=REL.FR)
next_friday = today + rd
print(next_friday)
# 2012-01-13
```
(The `days = ... |
Python: 'if not any' using a dictionary | 8,801,249 | 2 | 2012-01-10T09:49:28Z | 8,801,480 | 8 | 2012-01-10T10:05:59Z | [
"python",
"list",
"dictionary"
] | ```
if not any(myList[0:5]):
```
does this also work with a dictionary instead of a list?
I want to check if the first five key-value-pairs of my dictionary all have the value 'False'. | if you have a list of keys you want to check, use a generator expression:
```
if not any(myDict[key] for key in myKeys):
``` |
Override Django form field's name attr | 8,801,910 | 12 | 2012-01-10T10:39:21Z | 8,802,119 | 19 | 2012-01-10T10:55:16Z | [
"python",
"django",
"forms"
] | I've built a Django form that submits to a page on another domain (that I don't control). The idea is that I have a nicely styled, neatly generated form that fits neatly into my own site and takes the user elsewhere when it is submitted.
However,
* If that other form changes the names of any of its fields, I need to ... | This is a pretty horrible abuse of the API, but there is a form method called `add_prefix` that is called to determine what the HTML name of each field should be, taking into account the form's prefix if any. You could override that so that it looks up the field name in a dictionary somewhere and returns the name you w... |
python list expression | 8,802,327 | 3 | 2012-01-10T11:10:47Z | 8,802,387 | 8 | 2012-01-10T11:15:55Z | [
"python",
"list",
"expression"
] | Say I got a string:
```
s = '''1 2 3
4 5 6
7 8 9
'''
```
I want to turn each line of string `s` into a list of floating-point value, that is:
```
l = [[1.0 2.0 3.0], [4.0 5.0 6.0], [7.0 8.0 9.0]]
```
How can I do this in one line? | ```
[[float(v) for v in l.split()] for l in s.strip().split('\n')]
``` |
Checking whether a string starts with XXXX | 8,802,860 | 167 | 2012-01-10T11:54:20Z | 8,802,889 | 246 | 2012-01-10T11:56:11Z | [
"python",
"string",
"string-comparison"
] | I would like to know how to check whether a string starts with "hello" in Python.
In Bash I usually do:
```
if [[ "$string" =~ ^hello ]]; then
do something here
fi
```
How do I achieve the same in Python? | ```
aString = "hello world"
aString.startswith("hello")
``` |
Checking whether a string starts with XXXX | 8,802,860 | 167 | 2012-01-10T11:54:20Z | 8,803,076 | 38 | 2012-01-10T12:11:10Z | [
"python",
"string",
"string-comparison"
] | I would like to know how to check whether a string starts with "hello" in Python.
In Bash I usually do:
```
if [[ "$string" =~ ^hello ]]; then
do something here
fi
```
How do I achieve the same in Python? | [RanRag has already answered](http://stackoverflow.com/a/8802889/1138689) it for your specific question.
However, more generally, what you are doing with
```
if [[ "$string" =~ ^hello ]]
```
is a *regex* match. To do the same in Python, you would do:
```
import re
if re.match(r'^hello', somestring):
# do stuff
... |
my matplotlib title gets cropped | 8,802,918 | 10 | 2012-01-10T11:59:29Z | 8,803,087 | 9 | 2012-01-10T12:12:15Z | [
"python",
"matplotlib"
] | SOLVED - see comment below on combining `wraptext.wrap` and `plt.tightlayout`.
PROBLEM:
Here's the code:
```
import matplotlib.pyplot as plt
plt.bar([1,2],[5,4])
plt.title('this is a very long title and therefore it gets cropped which is an unthinkable behaviour as it loses the information in the title')
plt.show()
`... | You could wrap the text with newline characters (`\n`) automatically using [textwrap](http://docs.python.org/library/textwrap.html):
```
>>> longstring = "this is a very long title and therefore it gets cropped which is an unthinkable behaviour as it loses the information in the title"
>>> "\n".join(textwrap.wrap(long... |
my matplotlib title gets cropped | 8,802,918 | 10 | 2012-01-10T11:59:29Z | 8,813,131 | 17 | 2012-01-11T01:45:36Z | [
"python",
"matplotlib"
] | SOLVED - see comment below on combining `wraptext.wrap` and `plt.tightlayout`.
PROBLEM:
Here's the code:
```
import matplotlib.pyplot as plt
plt.bar([1,2],[5,4])
plt.title('this is a very long title and therefore it gets cropped which is an unthinkable behaviour as it loses the information in the title')
plt.show()
`... | You can try the solution found [here](http://stackoverflow.com/questions/4018860/text-box-in-matplotlib/4056853#4056853).
It's quite a bit of code, but it seems to handle text wrapping for any sort of text on the plot.
Here's the code from the solution, modified to fit your example:
```
import matplotlib.pyplot as p... |
python-requests: order get parameters | 8,802,945 | 12 | 2012-01-10T12:01:30Z | 8,803,348 | 7 | 2012-01-10T12:34:35Z | [
"python",
"http-request",
"python-requests"
] | I am implementing a client library for a private HTTP-API using [python requests](http://python-requests.org). The API(which I don't control) expects the parameters to be in a certain order, but python-requests doesn't honor a sorted dict as parameter.
This is what i tried:
```
import requests
from django.utils.datas... | Currently requests doesn't allow to do this as you wish. This is of course shortcoming that will be [fixed](https://github.com/kennethreitz/requests/issues/179). However as `params` parameter can take not only dictionary but bytes as well you should be able to do something in between:
```
from collections import Order... |
python-requests: order get parameters | 8,802,945 | 12 | 2012-01-10T12:01:30Z | 18,490,657 | 14 | 2013-08-28T14:23:54Z | [
"python",
"http-request",
"python-requests"
] | I am implementing a client library for a private HTTP-API using [python requests](http://python-requests.org). The API(which I don't control) expects the parameters to be in a certain order, but python-requests doesn't honor a sorted dict as parameter.
This is what i tried:
```
import requests
from django.utils.datas... | The requests lib now supports this out-of-the-box: To get ordered parameters you use a sequence of two-valued tuples instead. This eliminates the additional requirement of OrderedDict.
```
payload = (('key1', 'value1'), ('key2', 'value2'))
r = requests.get("http://httpbin.org/get", params=payload)
```
Demo:
```
>>> ... |
Same result for pk=request.user and pk=request.user.id in django | 8,804,193 | 6 | 2012-01-10T13:42:18Z | 8,804,596 | 9 | 2012-01-10T14:10:39Z | [
"python",
"django"
] | ```
class MyUser(User):
job = ...
city = ....
```
`MyUser.objects.get(pk=request.user)` and `MyUser.objects.get(pk=request.user.id)` give me the same result. From [doc](https://docs.djangoproject.com/en/1.3/topics/db/queries/), pk must be an int. But request.user is an object. Why queries are the same for obje... | This is by design - if you pass a model object as the parameter to a query, it is the same as passing its primary key.
If this wasn't the behaviour, either passing the pk would be required, or an error, which would merely be annoying.
Thanks to rebus for this reference to the source: <https://code.djangoproject.com/b... |
Python multiprocessing pickling error | 8,804,830 | 67 | 2012-01-10T14:28:25Z | 8,805,244 | 91 | 2012-01-10T14:54:13Z | [
"python",
"multiprocessing",
"pickle"
] | I am sorry that I can't reproduce the error with a simpler example, and my code is too complicated to post. If I run the program in IPython shell instead of the regular python, things work out well.
I looked up some previous notes on this problem. They were all caused by using pool to call function defined within a cl... | Here is a [list of what can be pickled](http://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled). In particular, functions are only picklable if they are defined at the top-level of a module.
This piece of code:
```
import multiprocessing as mp
class Foo():
@staticmethod
def work(self):
... |
Python multiprocessing pickling error | 8,804,830 | 67 | 2012-01-10T14:28:25Z | 13,151,257 | 9 | 2012-10-31T04:25:05Z | [
"python",
"multiprocessing",
"pickle"
] | I am sorry that I can't reproduce the error with a simpler example, and my code is too complicated to post. If I run the program in IPython shell instead of the regular python, things work out well.
I looked up some previous notes on this problem. They were all caused by using pool to call function defined within a cl... | I have found that I can also generate exactly that error output on a perfectly working piece of code by attempting to use the profiler on it.
Note that this was on Windows (where the forking is a bit less elegant).
I was running:
```
python -m profile -o output.pstats <script>
```
And found that removing the profil... |
Python multiprocessing pickling error | 8,804,830 | 67 | 2012-01-10T14:28:25Z | 21,345,423 | 17 | 2014-01-25T01:34:08Z | [
"python",
"multiprocessing",
"pickle"
] | I am sorry that I can't reproduce the error with a simpler example, and my code is too complicated to post. If I run the program in IPython shell instead of the regular python, things work out well.
I looked up some previous notes on this problem. They were all caused by using pool to call function defined within a cl... | I'd use `pathos.multiprocesssing`, instead of `multiprocessing`. `pathos.multiprocessing` is a fork of `multiprocessing` that uses `dill`. `dill` can serialize almost anything in python, so you are able to send a lot more around in parallel. The `pathos` fork also has the ability to work directly with multiple argument... |
Python multiprocessing pickling error | 8,804,830 | 67 | 2012-01-10T14:28:25Z | 24,673,524 | 9 | 2014-07-10T09:56:14Z | [
"python",
"multiprocessing",
"pickle"
] | I am sorry that I can't reproduce the error with a simpler example, and my code is too complicated to post. If I run the program in IPython shell instead of the regular python, things work out well.
I looked up some previous notes on this problem. They were all caused by using pool to call function defined within a cl... | As others have said `multiprocessing` can only transfer Python objects to worker processes which can be pickled. If you cannot reorganize your code as described by unutbu, you can use `dill`s extended pickling/unpickling capabilities for transferring data (especially code data) as I show below.
This solution requires ... |
Redirect stdout from python for C calls | 8,804,893 | 7 | 2012-01-10T14:32:47Z | 8,805,144 | 9 | 2012-01-10T14:47:26Z | [
"python",
"stdout",
"io-redirection",
"dup2",
"dup"
] | This is a follow up question from [here](http://stackoverflow.com/q/5081657/572616) specifically concerning its [answer](http://stackoverflow.com/a/5103455/572616).
---
From a python module I am calling a *Hello World* executable that simply prints `Hello World` to the stdout. I am interested in redirecting that outp... | I've written below a few additional comments that should make clearer what it's going on inside the `redirect_stdout` function:
```
def redirect_stdout():
print "Redirecting stdout"
sys.stdout.flush() # <--- important when redirecting to files
# Duplicate stdout (file descriptor 1)
# to a different fi... |
xvfb run error in ubuntu 11.04 | 8,805,032 | 13 | 2012-01-10T14:40:21Z | 8,880,717 | 27 | 2012-01-16T13:32:37Z | [
"python",
"amazon-ec2",
"pyqt4",
"xvfb"
] | My task is crawling the google search results using headless webkit(PyQt4.QtWebkit) in python.
The module was crawling the results fine using PyQt4.I should have to execute this script in amazon ec2.So,I should have to use [Xvfb](http://linux.about.com/cs/linux101/g/xvfb.htm) (no x server in ec2).
At the same time my ... | You need to add `--auto-servernum` parameter for `xvfb-run`. Otherwise, it tries to spawn `Xvfb` on the same display (by default `:99`), which will fail if you already have one running. |
xvfb run error in ubuntu 11.04 | 8,805,032 | 13 | 2012-01-10T14:40:21Z | 9,166,132 | 10 | 2012-02-06T19:37:59Z | [
"python",
"amazon-ec2",
"pyqt4",
"xvfb"
] | My task is crawling the google search results using headless webkit(PyQt4.QtWebkit) in python.
The module was crawling the results fine using PyQt4.I should have to execute this script in amazon ec2.So,I should have to use [Xvfb](http://linux.about.com/cs/linux101/g/xvfb.htm) (no x server in ec2).
At the same time my ... | Run like this,
```
xvfb-run --auto-servernum --server-num=1 python webpage_scrapper.py http://google.com
``` |
Efficiently create 2d histograms from large datasets | 8,805,601 | 8 | 2012-01-10T15:18:57Z | 8,805,988 | 12 | 2012-01-10T15:42:05Z | [
"python",
"numpy",
"matplotlib"
] | I'd like to create 2d histograms in python from large datasets (100000+ samples) stored in a HDF5 file. I came up with the following code:
```
import sys
import h5py
import numpy as np
import matplotlib as mpl
import matplotlib.pylab
f = h5py.File(sys.argv[1], 'r')
A = f['A']
T = f['T']
at_hist, xedges, yedges = np... | I would try a few different things.
1. Load your data from the hdf file instead of passing in what are effectively memory-mapped arrays.
2. If that doesn't fix the problem, you can exploit a `scipy.sparse.coo_matrix` to make the 2D histogram. With older versions of numpy, `digitize` (which all of the various `histogra... |
Accessing the default argument values in Python | 8,806,530 | 5 | 2012-01-10T16:15:46Z | 8,806,617 | 14 | 2012-01-10T16:21:35Z | [
"python"
] | How can I programmatically access the default argument values of a method in Python? For example, in the following
```
def test(arg1='Foo'):
pass
```
how can I access the string `'Foo'` inside `test`? | They are stored in `test.func_defaults` |
Why is "No" as raw_input in the following python code returning TRUE? | 8,806,641 | 4 | 2012-01-10T16:23:40Z | 8,806,663 | 23 | 2012-01-10T16:25:12Z | [
"python",
"boolean"
] | I cannot for the life of me understand why I can't get to the "else" statement no matter what I type. Any insight would be much appreciated. Am I not allowed to use more than one "or"?
```
print "Do you want to go down the tunnel? "
tunnel = raw_input ("> ")
if tunnel == "Y" or "Yes" or "Yea" or "Si" or "go" or "Aye... | Because in python
```
if tunnel == "Y" or "Yes" or "Yea" or "Si" or "go" or "Aye" or "Sure":
```
is equivalent to
```
if (tunnel == "Y") or ("Yes") or ("Yea") or ("Si") or ("go") or ("Aye") or ("Sure"):
```
and a nonempty string is true.
You should change your code to
```
if tunnel in ("Y", "Yes", "Yea", "Si", "g... |
Python import class from local folder | 8,807,581 | 3 | 2012-01-10T17:22:24Z | 8,807,644 | 7 | 2012-01-10T17:27:27Z | [
"python",
"pydev"
] | I have 2 classes. The first is named test and goes as following:
```
import textbox
class test:
a=textbox("test")
a.run()
```
---
the second class is textbox and goes as following:
```
class textbox():
def __init__(self, string):
self.string=string
def run(self):
print string
```
i... | Try
```
a = textbox.textbox("test")
```
or alternatively use
```
from textbox import textbox
``` |
Cython buffer declarations for object members | 8,808,216 | 18 | 2012-01-10T18:09:00Z | 18,673,027 | 10 | 2013-09-07T11:55:31Z | [
"python",
"numpy",
"cython"
] | I want to have a Cython "cdef" object with a NumPy member, and be able to use fast buffer access. Ideally, I would do something like:
```
import numpy as np
cimport numpy as np
cdef class Model:
cdef np.ndarray[np.int_t, ndim=1] A
def sum(self):
cdef int i, s=0, N=len(self.A)
for 0 <= i < N:
s += s... | There is the option to work with memory slices or cython arrays
<http://docs.cython.org/src/userguide/memoryviews.html>
```
import numpy as np
cimport numpy as np
cdef class Model:
cdef int [:] A
def sum(self):
for 0 <= i < N:
s += self.A[i]
return s
def __init__(self):
... |
How do I do this array indexing in numpy | 8,808,597 | 5 | 2012-01-10T18:36:01Z | 8,808,649 | 10 | 2012-01-10T18:41:01Z | [
"python",
"arrays",
"numpy"
] | Given an index array `I`, how to I set the values of a data array `D` whose indices don't exist in `I`?
Example: How to I get `A` from `I` and `D`?
```
I = array( [[1,1], [2,2], [3,3]] )
D = array( [[ 1, 2, 3, 4, 5, 6],
[ 7, 8, 9, 1, 2, 3],
[ 4, 5, 6, 7, 8, 9],
[ 1, 2, 3, 4, 5, 6]... | Simple solution:
```
A = zeros(D.shape)
for i, j in I:
A[i, j] = D[i, j]
```
Vectorized:
```
A = zeros(D.shape)
i, j = I.T
A[i, j] = D[i, j]
``` |
need to convert UTC (aws ec2) to PST in python | 8,809,765 | 6 | 2012-01-10T20:02:54Z | 8,809,969 | 8 | 2012-01-10T20:21:23Z | [
"python"
] | I need to convert UTC time, (on ec2 instance) to PST. I am trying to do this.
```
from datetime import datetime
from pytz import timezone
import pytz
date_format='%m/%d/%Y %H:%M:%S %Z'
date = datetime.now()
print 'Current date & time is:', date.strftime(date_format)
my_timezone=timezone('US/Pacific')
date = my_time... | ```
from datetime import datetime
from pytz import timezone
import pytz
date_format='%m/%d/%Y %H:%M:%S %Z'
date = datetime.now(tz=pytz.utc)
print 'Current date & time is:', date.strftime(date_format)
date = date.astimezone(timezone('US/Pacific'))
print 'Local date & time is :', date.strftime(date_format)
```
seems... |
Vectorized implementation to get index of minimum element in each row | 8,810,042 | 4 | 2012-01-10T20:26:50Z | 8,810,081 | 11 | 2012-01-10T20:30:11Z | [
"python",
"numpy"
] | I have a numpy.ndarray like this:
```
array([[ 11.18033989, 0. ],
[ 8.24621125, 3. ],
[ 13.03840481, 5. ],
[ 6. , 5.38516481],
[ 11.18033989, 3.16227766],
[ 0. , 11.18033989],
[ 8.06225775, 4.24264069]])
```
I want to get a ... | If `X` is your array,
```
X.argmin(axis=1)
``` |
How to join links in Python to get a cycle? | 8,810,122 | 9 | 2012-01-10T20:34:16Z | 8,810,917 | 7 | 2012-01-10T21:42:13Z | [
"python",
"list",
"functional-programming",
"iterator",
"reduce"
] | I have a list of links and want to know the joined path/cycle.
My links look like this:
```
[[0, 3], [1, 0], [3, 1]]
```
And I want the answer to be a cycle like that (or any other matching cycle):
```
[0,3,1]
```
So you take the first element of the first sublist, then you take the second element and you look for... | Consider using the [networkx](http://networkx.lanl.gov/) package:
```
import networkx as nx
G = nx.DiGraph() #creates directed graph
G.add_edges_from([[0, 3], [1, 0], [3, 1]])
print nx.simple_cycles(G).pop()[:-1]
```
The output:
```
>> [0, 3, 1]
``` |
How to join links in Python to get a cycle? | 8,810,122 | 9 | 2012-01-10T20:34:16Z | 8,811,096 | 8 | 2012-01-10T21:56:35Z | [
"python",
"list",
"functional-programming",
"iterator",
"reduce"
] | I have a list of links and want to know the joined path/cycle.
My links look like this:
```
[[0, 3], [1, 0], [3, 1]]
```
And I want the answer to be a cycle like that (or any other matching cycle):
```
[0,3,1]
```
So you take the first element of the first sublist, then you take the second element and you look for... | There is a very elegant way to do it using a generator:
```
def cycle(lst, val, stop=None):
d = dict(lst)
stop = stop if stop is not None else val
while True:
yield val
val = d.get(val, stop)
if val == stop: break
```
Firstly, it allows natural iteration:
```
>>> for x in cycle([[... |
main method in Python | 8,810,765 | 3 | 2012-01-10T21:29:23Z | 8,810,797 | 23 | 2012-01-10T21:32:23Z | [
"python"
] | I have the following code, which has the following two problems:
```
Traceback (most recent call last):
File "C:\Users\v\workspace\first\src\tests.py", line 1, in <module>
class Animal:
File "C:\Users\v\workspace\first\src\tests.py", line 39, in Animal
File "C:\Users\v\workspace\first\src\tests.py", line 31,... | This code:
```
def main():
dog = Animal()
dog.set_owner('Sue')
print dog.get_owner()
dog.noise()
if __name__ =='__main__':main()
```
should not be in the class. When you take it outside (no indent) it should work.
So after taking that into account it should look like this:
```
class Animal:
... |
main method in Python | 8,810,765 | 3 | 2012-01-10T21:29:23Z | 8,811,219 | 21 | 2012-01-10T22:07:02Z | [
"python"
] | I have the following code, which has the following two problems:
```
Traceback (most recent call last):
File "C:\Users\v\workspace\first\src\tests.py", line 1, in <module>
class Animal:
File "C:\Users\v\workspace\first\src\tests.py", line 39, in Animal
File "C:\Users\v\workspace\first\src\tests.py", line 31,... | To understand *why* what you wrote failed, you need to know a little bit about how class definitions work in Python. As you may know, Python is an interpreted language: there is a program which reads through Python files and executes them as it goes. When the interpreter encounters a class definition, it does the follo... |
SciPy "lfilter" returns only NaNs | 8,811,518 | 4 | 2012-01-10T22:32:42Z | 8,812,737 | 7 | 2012-01-11T00:48:23Z | [
"python",
"numpy",
"signal-processing",
"scipy"
] | All -
I am trying to use SciPy's `signal.lfilter` function to filter a vector of samples - unfortunately, all that is returned is a vector of *NaN*.
I have plotted the frequency response of the filter, and the filter coefficients look correct; I'm fairly certain the issue is with the actual call to `lfilter`.
It's a... | An IIR filter is stable if the absolute values of the roots of the denominator of the discrete transfer function a(z) are all less than one. So, you can detect the instability by following code:
```
from scipy import signal
import numpy as np
b1, a1 = signal.iirdesign(wp = 0.11, ws= 0.1, gstop= 60, gpass=1, ftype='che... |
Convert JSON to SQLite in Python - How to map json keys to database columns properly? | 8,811,783 | 24 | 2012-01-10T22:59:47Z | 8,812,069 | 25 | 2012-01-10T23:25:33Z | [
"python",
"json",
"sqlite",
"database-design"
] | I want to convert a JSON file I created to a SQLite database.
My intention is to decide later which data container and entry point is best, json (data entry via text editor) or SQLite (data entry via spreadsheet-like GUIs like SQLiteStudio).
My json file is like this (containing traffic data from some crossroads in m... | You have this python code:
```
c.execute("insert into medicoes values(?,?,?,?,?,?,?)" % keys)
```
which I think should be
```
c.execute("insert into medicoes values (?,?,?,?,?,?,?)", keys)
```
since the [`%` operator](http://docs.python.org/tutorial/inputoutput.html#old-string-formatting) expects the string to its ... |
pymssql versus pyodbc versus adodbapi versus... | 8,812,631 | 13 | 2012-01-11T00:35:07Z | 9,739,020 | 11 | 2012-03-16T14:22:53Z | [
"python",
"sql-server"
] | I am relatively new to databases, performing SQL queries, etc. At the moment I am exclusively using MS SQL Server for my DBs (that's what we use at my work), but hopefully answers to my question can be more general than just for that particular DB.
I do a good chunk of my work using the DB interface app itself (in thi... | **pyodbc** (recommended)
I've started using this module a few months ago and have no complaints so far. The development community seems more active than pymssql. I had no installation issues so far (32bit Win XP and 64bit Server 2008 R2). You'll have the additional advantage that you are not limited to MS SQL Servers.... |
pymssql versus pyodbc versus adodbapi versus... | 8,812,631 | 13 | 2012-01-11T00:35:07Z | 21,564,000 | 7 | 2014-02-04T21:37:13Z | [
"python",
"sql-server"
] | I am relatively new to databases, performing SQL queries, etc. At the moment I am exclusively using MS SQL Server for my DBs (that's what we use at my work), but hopefully answers to my question can be more general than just for that particular DB.
I do a good chunk of my work using the DB interface app itself (in thi... | From my experience, PYODBC is a bit problematic these days. Firstly, it does not seem to manage unicode strings properly or reliably. Secondly, the API is a bit out of date and specific and less Python DB-API ([PEP-249](http://www.python.org/dev/peps/pep-0249/)) compliant.
I am in the midst of migrating project code t... |
Using a simple python generator as a co-routine in a Tornado async handler? | 8,812,715 | 14 | 2012-01-11T00:45:47Z | 8,821,914 | 15 | 2012-01-11T15:30:25Z | [
"python",
"asynchronous",
"web",
"generator",
"tornado"
] | I have a python generator function which yields chunks of text. I would like to write a `get` method for a `tornado.web.RequestHandler` subclass that will iterate over the generator, writing the chunks out to the response as it goes.
Since this is Tornado, and since the generator may take over a second to process, I t... | Here's a basic version of what you are describing. To avoid blocking you can pass your generator to the IOLoop via a callback function. The trick here is since you are not using a process that does actual IO and so has no os level process/file handler to add to the IOLoop via `add_handler`, you can instead use a simple... |
Using a simple python generator as a co-routine in a Tornado async handler? | 8,812,715 | 14 | 2012-01-11T00:45:47Z | 8,824,513 | 13 | 2012-01-11T18:19:03Z | [
"python",
"asynchronous",
"web",
"generator",
"tornado"
] | I have a python generator function which yields chunks of text. I would like to write a `get` method for a `tornado.web.RequestHandler` subclass that will iterate over the generator, writing the chunks out to the response as it goes.
Since this is Tornado, and since the generator may take over a second to process, I t... | It is also possible to use the new [tornado's gen](http://www.tornadoweb.org/documentation/gen.html) interface to async processes:
```
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.gen
class TextHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
@tornado.gen.en... |
Matrix as dictionary key | 8,813,226 | 6 | 2012-01-11T01:59:14Z | 8,813,577 | 8 | 2012-01-11T02:51:53Z | [
"python",
"dictionary",
"numpy"
] | I've just started using `numpy` and its `matrix` module (very very useful!), and I wanted to use a matrix object as the key of a dictionary, so I checked if `matrix` had the `__hash__` method implemented:
```
>>> from numpy import matrix
>>> hasattr(matrix, '__hash__')
True
```
And it does! Nice, so it means that it ... | It would be wrong to use a mutable object as a key of a dictionary because its hash should change as soon as you change the data, but the value used on insertion will be kept.
On my tests, numpy at Python 3.2.2 raise a TypeError:
```
TypeError: unhashable type: 'matrix'
```
But on Python 2.7 it still allows hashing ... |
Why doesn't ignorecase flag (re.I) work in re.sub() | 8,813,265 | 14 | 2012-01-11T02:04:45Z | 8,813,281 | 28 | 2012-01-11T02:06:53Z | [
"python",
"regex"
] | From pydoc:
> re.sub = sub(pattern, repl, string, count=0, flags=0)
> Return the string obtained by replacing the leftmost
> non-overlapping occurrences of the pattern in string by the
> replacement repl. repl can be either a string or a callable;
> if a string, backslash escapes in it are processed. If it is
> a ca... | Seems to me that you should be doing:
```
import re
print re.sub('class', 'function', 'Class object', flags=re.I)
```
Without this, the `re.I` argument is passed to the `count` argument. |
How do I compare dates from Twitter data stored in MongoDB via PyMongo? | 8,813,539 | 7 | 2012-01-11T02:46:23Z | 8,825,799 | 16 | 2012-01-11T19:59:26Z | [
"python",
"mongodb",
"twitter",
"pymongo"
] | Are the dates stored in the 'created\_at' fields marshaled to Python datetime objects via PyMongo, or do I have to manually replace the text strings with Python Date objects? i.e.
[How do I convert a property in MongoDB from text to date type?](http://stackoverflow.com/questions/2900674/how-do-i-convert-a-property-in-... | you can parse Twitter's created\_at timestamps to Python datetimes like so:
```
import datetime, pymongo
created_at = 'Mon Jun 8 10:51:32 +0000 2009' # Get this string from the Twitter API
dt = datetime.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y')
```
and insert them into your Mongo collection like this:
```
c... |
How to implement a Python virtual filesystem using shelve | 8,813,847 | 5 | 2012-01-11T03:39:07Z | 8,814,180 | 7 | 2012-01-11T04:31:27Z | [
"python",
"filesystems",
"shelve"
] | I have set up a Python script that simulates an OS. It has a command prompt and a virtual file system. I am using the shelve module to simulate the file system, being multi-dimensional in order to support a hierarchy of directories. However, I am having trouble implementing a 'cd' command. I don't know how to get in an... | I provide some code to help you out below, but first, some overall advice that should help you with your design:
* The reason you're having difficulty with changing directories is that you are representing the current directory variable the wrong way. Your current directory should be something like a list, from your t... |
make variable global to multiple files in python | 8,814,316 | 2 | 2012-01-11T04:51:59Z | 8,814,409 | 8 | 2012-01-11T05:04:53Z | [
"python",
"global-variables"
] | I want to make a variable global to more than 2 files so that operating in any file reflects in the file containing the variable.
what I am doing is:
**b.py**
```
import a
x = 0
def func1():
global x
x = 1
if __name__ == "__main__":
print x
func1()
print x
a.func2()
print x
```
**a.p... | Let me start by saying that I think globals like this (using the global keyword) are evil.
But one way to restructure it is to put your globals into a class in a SEPARATE module to avoid circular imports.
**a.py**
```
from c import MyGlobals
def func2():
print MyGlobals.x
MyGlobals.x = 2
```
**b.py**
```
i... |
PyQt - how to add separate UI widget to QMainWindow | 8,814,452 | 10 | 2012-01-11T05:10:26Z | 8,815,111 | 15 | 2012-01-11T06:33:21Z | [
"python",
"layout",
"pyqt"
] | I've only recently started programming and Python (PyQt) in particular. I have my main `QMainWindow` class. But I wanted to separate it from UI widgets, so that all windows stuff (menus, toolbars, common buttons) are in `QMainWindow`, but all program/UI specific widgets (pusgbuttons, comboboxes, images, checkboxes etc.... | Are you looking for something like this? I'm not really sure what your `main_widget` is
```
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class MyMainWindow(QMainWindow):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
self.form_widget = FormWidget... |
python: [Errno 10054] An existing connection was forcibly closed by the remote host | 8,814,802 | 19 | 2012-01-11T05:54:15Z | 8,814,832 | 7 | 2012-01-11T05:58:20Z | [
"python",
"twitter",
"web-crawler"
] | I am writing python to crawl Twitter space using Twitter-py. I have set the crawler to sleep for a while (2 seconds) between each request to api.twitter.com. However, after some times of running (around 1), when the Twitter's rate limit not exceeded yet, I got this error.
```
[Errno 10054] An existing connection was f... | This can be caused by the two sides of the connection disagreeing over whether the connection timed out or not during a keepalive. (Your code tries to reused the connection just as the server is closing it because it has been idle for too long.) You should basically just retry the operation over a new connection. (I'm ... |
Django - Unitest or Doctest? | 8,815,179 | 4 | 2012-01-11T06:40:54Z | 8,815,414 | 9 | 2012-01-11T07:04:48Z | [
"python",
"django",
"unit-testing",
"doctest"
] | I'm about to begin my third medium-sized project and would like (for the first time in my life i admit) to start using unittests.
I have no idea though, which method to use, unitests or doctests.
Which of the methods is the most efficient, or which should a beginner choose to implement?
Thanks | I happen to prefer unittests, but both are excellent and well developed methods of testing, and both are well-supported by Django (see [here](https://docs.djangoproject.com/en/dev/topics/testing/) for details). In short, there are some key advantages and disadvantages to each:
**Pros of unittests**
* **`unittests` al... |
Convert bytes to bits in python | 8,815,592 | 10 | 2012-01-11T07:23:19Z | 8,815,667 | 7 | 2012-01-11T07:31:06Z | [
"python",
"hex",
"byte",
"bits"
] | I am working with Python3.2. I need to take a hex stream as an input and parse it at bit-level. So I used
`bytes.fromhex(input_str)`
to convert the string to actual bytes. Now how do I convert these bytes to bits? | What about something like this?
```
>>> bin(int('ff', base=16))
'0b11111111'
```
This will convert the hexadecimal string you have to an integer and that integer to a string in which each byte is set to 0/1 depending on the bit-value of the integer.
As pointed out by a comment, if you need to get rid of the `0b` pre... |
Convert bytes to bits in python | 8,815,592 | 10 | 2012-01-11T07:23:19Z | 8,816,011 | 12 | 2012-01-11T08:04:55Z | [
"python",
"hex",
"byte",
"bits"
] | I am working with Python3.2. I need to take a hex stream as an input and parse it at bit-level. So I used
`bytes.fromhex(input_str)`
to convert the string to actual bytes. Now how do I convert these bytes to bits? | Operations are much faster when you work at the integer level. In particular, converting to a string as suggested here is really slow.
If you want bit 7 and 8 only, use e.g.
```
val = (byte >> 6) & 3
```
(this is: shift the byte 6 bits to the right - dropping them. Then keep only the last two bits `3` is the number ... |
Convert bytes to bits in python | 8,815,592 | 10 | 2012-01-11T07:23:19Z | 8,816,027 | 14 | 2012-01-11T08:06:00Z | [
"python",
"hex",
"byte",
"bits"
] | I am working with Python3.2. I need to take a hex stream as an input and parse it at bit-level. So I used
`bytes.fromhex(input_str)`
to convert the string to actual bytes. Now how do I convert these bytes to bits? | Another way to do this is by using the [`bitstring`](http://packages.python.org/bitstring/index.html#) module:
```
>>> from bitstring import BitArray
>>> input_str = '0xff'
>>> c = BitArray(hex=input_str)
>>> c.bin
'0b11111111'
```
And if you need to strip the leading `0b`:
```
>>> c.bin[2:]
'11111111'
```
The `bit... |
Random number with specific variance in Python | 8,815,706 | 2 | 2012-01-11T07:34:33Z | 8,815,748 | 8 | 2012-01-11T07:38:23Z | [
"python",
"random",
"variance"
] | In a Python program, I need to generate normally-distributed random numbers with a specific, user-controlled variance. How can I do this? | Use [`random.normalvariate`](http://docs.python.org/library/random.html#random.normalvariate) (or `random.gauss` if you don't need thread-safety), and set the `sigma` argument to the square root of the variance. |
create file of particular size in python | 8,816,059 | 18 | 2012-01-11T08:09:24Z | 8,816,144 | 26 | 2012-01-11T08:17:11Z | [
"python",
"file"
] | I want to create a file of particular size (say, 1GiB).
The content is not important since I will fill stuff into it.
What I am doing is:
```
f = open("E:\\sample", "wb")
size = 1073741824 # bytes in 1 GiB
f.write("\0" * size)
```
But this takes too long to finish. It spends me roughly 1 minute.
What can be done to ... | **WARNING** This solution gives the result that you might not expect. See UPD ...
1 Create new file.
2 seek to size-1 byte.
3 write 1 byte.
4 profit :)
```
f = open('newfile',"wb")
f.seek(1073741824-1)
f.write("\0")
f.close()
import os
os.stat("newfile").st_size
1073741824
```
**UPD:**
Seek and truncate both cre... |
create file of particular size in python | 8,816,059 | 18 | 2012-01-11T08:09:24Z | 8,816,154 | 16 | 2012-01-11T08:18:11Z | [
"python",
"file"
] | I want to create a file of particular size (say, 1GiB).
The content is not important since I will fill stuff into it.
What I am doing is:
```
f = open("E:\\sample", "wb")
size = 1073741824 # bytes in 1 GiB
f.write("\0" * size)
```
But this takes too long to finish. It spends me roughly 1 minute.
What can be done to ... | The question has been [answered](http://stackoverflow.com/questions/6497722/how-to-create-a-very-large-file-cheaply-using-python-in-windows-7/6497779#6497779) before. Not sure whether the solution is cross platform, but it works in Windows (NTFS file system) flawlessly.
```
with open("file.to.create", "wb") as out:
... |
Invalid block tag: 'pay_pal', expected 'endblock' or 'endblock content' | 8,816,171 | 2 | 2012-01-11T08:19:10Z | 8,816,205 | 8 | 2012-01-11T08:22:41Z | [
"python",
"django",
"django-templates"
] | does anyone has an idea about this and how can i deal with it?
> Invalid block tag: 'pay\_pal', expected 'endblock' or 'endblock content'
in my `views.py`, i have this
```
pay_pal = get_integration("pay_pal")
pay_pal.add_fields({
"business": "test@gmail.com",
"item_name": product.name,
"invoice"... | Probably, you have to move `{% load billing_tags %}` to the top of the `pay_pay.html`. |
Output of True and [] | 8,816,736 | 10 | 2012-01-11T09:14:56Z | 8,816,768 | 17 | 2012-01-11T09:17:27Z | [
"python",
"syntactic-sugar"
] | I was wondering why
`True and []`
returns [] instead of False
Is the expression a syntactic sugar ? | The answer is found at [5.10. Boolean Expressions](http://docs.python.org/reference/expressions.html#boolean-operations):
> The expression `x and y` first evaluates *x*; if *x* is false, its value is returned; otherwise, *y* is evaluated and the resulting value is returned. |
dup, dup2, tmpfile and stdout in python | 8,817,993 | 3 | 2012-01-11T10:50:21Z | 8,825,434 | 10 | 2012-01-11T19:29:11Z | [
"python",
"stdout",
"io-redirection",
"dup2",
"dup"
] | This is a follow up question from [here](http://stackoverflow.com/q/8804893/572616).
---
### Where I want do go
I would like to be able to temporarily redirect the stdout into a temp file, while python still is able to print to stdout. This would involve the following steps:
1. Create a copy of stdout (`new`)
2. Cr... | The reason you get a "bad file descriptor" is that the garbage collector closes the stdout FD for you. Consider these two lines:
```
sys.stdout = os.fdopen(1, 'w', 0) # from first part of your script
...
sys.stdout = os.fdopen(new, 'w', 0) # from second part of your script
```
Now when the second of those two are... |
Pass empty/noop function/lambda as default argument | 8,818,197 | 6 | 2012-01-11T11:07:16Z | 8,818,266 | 9 | 2012-01-11T11:13:44Z | [
"python"
] | This is my code:
```
def execute(f, *args):
f(args)
```
I sometimes want to pass no function `f` to `execute`, so I want `f` to default to the empty function. | > The problem is that sometimes want to pass no argument to execute, so I want function to default to the empty function.
Works fine for me:
```
>>> def execute(function = lambda x: x, *args):
... print function, args
... function(args)
...
>>> execute()
<function <lambda> at 0x01DD1A30> ()
>>>
```
I do note tha... |
Styling long chains in Python | 8,818,484 | 11 | 2012-01-11T11:29:51Z | 8,818,593 | 17 | 2012-01-11T11:38:30Z | [
"python"
] | I've written a Python API that is "chain based" (similar to jQuery). So I can write:
```
myObject.doStuff().doMoreStuf().goRed().goBlue().die()
```
The problem is that I haven't found a way to keep the syntax clean with long chains. In JavaScript I could simply do
```
myOjbect
.doStuf()
.doMoreStuf()
.goRed... | # PEP8-compliant solution: formatting the line
Actually [PEP8](http://www.python.org/dev/peps/pep-0008/) says:
> Long lines can be
> broken over multiple lines by wrapping expressions in **parentheses. These
> should be used in preference to using a backslash for line continuation**.
> Make sure to indent the continu... |
Python: printing elements from a list till a specific element | 8,819,321 | 3 | 2012-01-11T12:33:39Z | 8,819,389 | 12 | 2012-01-11T12:37:43Z | [
"python",
"list",
"printing"
] | I have a list of strings with different numbers of words, eg.
```
abc = ['apple', 'apple ball', 'cat ', 'ball apple', 'dog cat apple',
'apple ball cat dog', 'cat', 'ball apple']
```
What I have done is that I have counted the number of spaces in each element. What I want to do now is to print all the elements ... | Try [`itertools.takewhile()`](http://docs.python.org/library/itertools.html#itertools.takewhile):
```
from itertools import takewhile
for s in takewhile(lambda x: x.count(" ") < 3, abc):
print s
```
For a list of lists, just add another for loop:
```
for abc in list_of_lists:
for s in takewhile(lambda x: x.c... |
why does this function not fire in the __init__ method? | 8,819,625 | 4 | 2012-01-11T12:53:55Z | 8,819,633 | 15 | 2012-01-11T12:54:47Z | [
"python"
] | ```
class test:
def __init__(self, val):
self.val = val
self.val.lower()
```
Why doesn't lower() operate on the contents of val in this code? | You probably mean:
```
self.val = self.val.lower()
```
Or, more concisely:
```
class test:
def __init__(self, val):
self.val = val.lower()
```
To elaborate, [`lower()`](http://docs.python.org/library/stdtypes.html#str.lower) doesn't modify the string in place (it can't, since strings are immutable). Ins... |
Django: Getting complement of queryset | 8,820,113 | 5 | 2012-01-11T13:31:30Z | 8,820,162 | 9 | 2012-01-11T13:34:41Z | [
"python",
"django",
"orm"
] | I get a queryset for a certain model and I'd like to get its complement, i.e. all instances of that model that are *not* in the aforementioned queryset.
How can I do that? | ```
qs = Model.objects.filter(...) # qs with objects to exclude
result = Model.objects.exclude(pk__in=qs.values_list('pk', flat=True))
``` |
Docstring for variable | 8,820,276 | 29 | 2012-01-11T13:42:52Z | 8,820,636 | 27 | 2012-01-11T14:07:22Z | [
"python"
] | Is it posible to use docstring for plain variable? For example I have module called `t`
```
def f():
"""f"""
l = lambda x: x
"""l"""
```
and I do
```
>>> import t
>>> t.f.__doc__
'f'
```
but
```
>>> t.l.__doc__
>>>
```
Example is similar to [PEP 258](http://www.python.org/dev/peps/pep-0258/#ast-mining)'s (se... | No, and it wouldn't be useful if you could.
The docstring is always an attribute of an object (module, class or function), not tied to a specific variable.
That means if you *could* do:
```
t = 42
t.__doc__ = "something"
```
you would be setting the documentation for the integer 42 not for the variable `t`. As soon... |
Python Imaging: load jpeg from memory | 8,821,259 | 7 | 2012-01-11T14:50:01Z | 8,821,393 | 10 | 2012-01-11T14:57:44Z | [
"python",
"image",
"jpeg"
] | The problem is to load jpeg-encoded image from memory.
I receive a string from socket:
```
jpgdata = self.rfile.read(sz)
```
and I know that this is jpeg-encoded image.
I need to decode it.
The most stupid solution is:
```
o = open("Output/1.jpg","wb")
o.write(jpgdata)
o.close()
dt = Image.open("Output/1.jpg")
```... | PIL's Image.open object accepts any file-like object. That means you can wrap your Image data on a StringIO object, and pass it to Image.Open
```
from cStringIO import StringIO
file_jpgdata = StringIO(jpgdata)
dt = Image.open(file_jpgdata)
```
Or, try just passing `self.rfile` as an argument to Image.open - it might ... |
Substitutions in Sphinx code blocks | 8,821,511 | 17 | 2012-01-11T15:05:48Z | 12,644,533 | 14 | 2012-09-28T17:17:56Z | [
"python",
"python-sphinx",
"restructuredtext"
] | In this reST example meant to be rendered by Sphinx, |yaco\_url| doesn't get replaced because it's in a code-block:
```
.. |yaco_url| replace:: http://yaco.es/
You can use wget to download it:
.. code-block:: console
$ wget |yaco_url|package.tar.gz
```
I wonder if there is some way to force the replacement of ... | Use the "parsed-literal" directive.
```
.. parsed-literal::
./home/user/somecommand-|version|
```
Source: <https://groups.google.com/forum/?fromgroups=#!topic/sphinx-dev/ABzaUiCfO_8>: |
What do the python file extensions, .pyc .pyd .pyo stand for? | 8,822,335 | 207 | 2012-01-11T15:54:55Z | 8,822,377 | 238 | 2012-01-11T15:57:58Z | [
"python"
] | What do these python file extensions mean?
* .pyc
* .pyd
* .pyo
What are the differences between them and how are they generated from a \*.py file? | 1. `.py`: This is normally the input source code that you've written.
2. `.pyc`: This is the compiled bytecode. If you import a module, python will build a `*.pyc` file that contains the bytecode to make importing it again later easier (and faster).
3. `.pyo`: This is a `*.pyc` file that was created while optimizations... |
What do the python file extensions, .pyc .pyd .pyo stand for? | 8,822,335 | 207 | 2012-01-11T15:54:55Z | 18,032,741 | 96 | 2013-08-03T12:12:11Z | [
"python"
] | What do these python file extensions mean?
* .pyc
* .pyd
* .pyo
What are the differences between them and how are they generated from a \*.py file? | **.py** - Regular scripts
**.py3** - (rarely used) Python3 script. Python3 scripts usually end with ".py" not ".py3", but I have seen that a few times
**.pyc** - compiled script (Bytecode)
**.pyo** - optimized pyc file (As of Python3.5, Python will only use pyc rather than pyo and pyc)
**.pyw** - Python script ... |
Plot line graph from histogram data in matplotlib | 8,822,370 | 16 | 2012-01-11T15:57:19Z | 8,822,554 | 21 | 2012-01-11T16:09:18Z | [
"python",
"numpy",
"matplotlib"
] | I have a numpy array of ints representing time periods, which I'm currently plotting in a histogram to get a nice distribution graph, using the following code:
```
ax.hist(data,bins=100,range=(minimum,maximum),facecolor="r")
```
However I'm trying to modify this graph to represent the exact same data using a line ins... | You can save the output of `hist` and then plot it.
```
import numpy as np
import pylab as p
data=np.array(np.random.rand(1000))
y,binEdges=np.histogram(data,bins=100)
bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
p.plot(bincenters,y,'-')
p.show()
``` |
Plot line graph from histogram data in matplotlib | 8,822,370 | 16 | 2012-01-11T15:57:19Z | 10,721,901 | 18 | 2012-05-23T14:19:45Z | [
"python",
"numpy",
"matplotlib"
] | I have a numpy array of ints representing time periods, which I'm currently plotting in a histogram to get a nice distribution graph, using the following code:
```
ax.hist(data,bins=100,range=(minimum,maximum),facecolor="r")
```
However I'm trying to modify this graph to represent the exact same data using a line ins... | I am very late to the party - but maybe this will be useful to someone else. I think what you need to do is set the histtype parameter to 'step', i.e.
```
ax.hist(data,bins=100,range=(minimum,maximum),facecolor="r", histtype = 'step')
```
See also <http://matplotlib.sourceforge.net/examples/pylab_examples/histogram_d... |
How to print Docstring of python function from inside the function itself? | 8,822,701 | 28 | 2012-01-11T16:17:03Z | 8,825,773 | 32 | 2012-01-11T19:57:20Z | [
"python",
"function",
"printing",
"docstring"
] | I want to print the docstring of a python function from inside the function itself.
for eg.
```
def my_function(self):
"""Doc string for my function."""
# print the Docstring here.
```
At the moment I am doing this directly after `my_function` has been defined.
```
print my_function.__doc__
```
But would rather... | ```
def my_func():
"""Docstring goes here."""
print my_func.__doc__
```
This will work as long as you don't change the object bound to the name `my_func`.
```
new_func_name = my_func
my_func = None
new_func_name()
# doesn't print anything because my_func is None and None has no docstring
```
Situations in w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.