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 |
|---|---|---|---|---|---|---|---|---|---|
Python - Ensuring a variable holds a positive number | 7,122,535 | 3 | 2011-08-19T13:48:41Z | 7,122,613 | 18 | 2011-08-19T13:53:50Z | [
"python",
"variables",
"numbers"
] | I am looking for an elegant way to ensure that a given variable remains positive.
I have two variables that hold positive float numbers and I decrement them according to certain conditions. At the end I want to guarantee that I still have positive numbers (or 0 at most). The pseudo code looks something like this:
```... | I am unclear as to what you want to do -- either the variables can be negative, or they can't.
* If you are decrementing a variable repeatedly and after doing so you want to check whether they are negative, do so with an `if` -- that's what it's for!
```
if value < 0: # do stuff
```
* If you think the variables... |
Should I create pipeline to save files with scrapy? | 7,123,387 | 10 | 2011-08-19T14:51:46Z | 7,169,241 | 10 | 2011-08-24T00:50:09Z | [
"python",
"scrapy",
"web-crawler",
"pipeline"
] | I need to save a file (.pdf) but I'm unsure how to do it. I need to save .pdfs and store them in such a way that they are organized in a directories much like they are stored on the site I'm scraping them off.
From what I can gather I need to make a pipeline, but from what I understand pipelines save "Items" and "item... | Yes and no[1]. If you fetch a pdf it will be stored in memory, but if the pdfs are not big enough to fill up your available memory so it is ok.
You could save the pdf in the spider callback:
```
def parse_listing(self, response):
# ... extract pdf urls
for url in pdf_urls:
yield Request(url, callback=... |
python "help" function: printing docstrings | 7,123,660 | 7 | 2011-08-19T15:12:38Z | 7,124,485 | 9 | 2011-08-19T16:17:13Z | [
"python",
"docstring"
] | Is there an option to print the output of help('myfun'). The behaviour I'm seeing is that output is printed to std.out and the script waits for user input (i.e. type 'q' to continue).
There must be a setting to set this to just dump docstrings.
Alternatively, if I could just dump the docstring PLUS the "def f(args):"... | To get exactly the help that's printed by `help(str)` into the variable `strhelp`:
```
import pydoc
strhelp = pydoc.render_doc(str, "Help on %s")
```
Of course you can then easily print it without paging, etc. |
In python shell, "b" letter does not work, what the? | 7,124,035 | 13 | 2011-08-19T15:39:09Z | 7,124,455 | 7 | 2011-08-19T16:14:19Z | [
"python",
"shell"
] | Well hello, this is the most interesting bug/conflict I've ever faced.
In python shell, I cannot type lowercase "b". At first I thought something was under the key, but no, in everywhere else it functions very well. Also `ctrl+b` `shift+b` even with `capslock b` works.
Yet more, when I run the shell with `sudo` (ie. ... | My money is that the readline on your shell is messed up. Perhaps the 'b' key is bound to auto-complete. Look in your `PYTHONSTARTUP` variable and see what file it refers to. If that file has something like `readline.parse_and_bind` ...
I'm betting there's some connection between the fact that it's 'b' (instead of som... |
In python shell, "b" letter does not work, what the? | 7,124,035 | 13 | 2011-08-19T15:39:09Z | 8,695,404 | 10 | 2012-01-01T20:43:59Z | [
"python",
"shell"
] | Well hello, this is the most interesting bug/conflict I've ever faced.
In python shell, I cannot type lowercase "b". At first I thought something was under the key, but no, in everywhere else it functions very well. Also `ctrl+b` `shift+b` even with `capslock b` works.
Yet more, when I run the shell with `sudo` (ie. ... | The problematic line in your `.pythonstartup` is something like:
```
readline.parse_and_bind("bind ^I rl_complete") # darwin libedit
```
This `.pythonstartup` will fix it...
```
try:
import readline
except ImportError:
print "Module readline not available."
else:
import rlcompleter
if 'libedit' in r... |
How to prevent a for loop from advancing in Python? | 7,124,733 | 2 | 2011-08-19T16:41:24Z | 7,124,850 | 8 | 2011-08-19T16:51:58Z | [
"python",
"for-loop"
] | Is it possible to prevent the `for` loop from proceeding to the next value in the list/iterator if a certain condition is satisfied?
```
lst = list('abcde')
for alphabet in lst:
if some_condition:
# somehow prevent the for loop from advancing so that in the
# next iteration, the value of alphabet remains t... | What you seem to want is a nested `while` loop. Only when the `while` loop exits will the `for` loop continue to the next value.
```
alphabet = "abcdefghijklmnopqrstuvwxyz"
for letter in alphabet:
while some_condition:
# do something
``` |
How to change legend size with matplotlib.pyplot | 7,125,009 | 129 | 2011-08-19T17:06:33Z | 7,125,095 | 31 | 2011-08-19T17:16:50Z | [
"python",
"size",
"matplotlib",
"legend"
] | Simple question here: I'm just trying to get the size of my legend using matplotlib.pyplot to be smaller (ie, the text to be smaller). The code I'm using goes something like this:
```
plot.figure()
plot.scatter(k,sum_cf, color = 'black', label='Sum of Cause Fractions')
plot.scatter(k, data[:, 0], color = 'b', label =... | This should do
```
import pylab as plot
params = {'legend.fontsize': 20,
'legend.linewidth': 2}
plot.rcParams.update(params)
```
Then do the plot afterwards.
There are a ton of other rcParams, they can also be set in the matplotlibrc file.
Also presumably you can change it passing a `matplotlib.font_manag... |
How to change legend size with matplotlib.pyplot | 7,125,009 | 129 | 2011-08-19T17:06:33Z | 7,125,157 | 236 | 2011-08-19T17:24:13Z | [
"python",
"size",
"matplotlib",
"legend"
] | Simple question here: I'm just trying to get the size of my legend using matplotlib.pyplot to be smaller (ie, the text to be smaller). The code I'm using goes something like this:
```
plot.figure()
plot.scatter(k,sum_cf, color = 'black', label='Sum of Cause Fractions')
plot.scatter(k, data[:, 0], color = 'b', label =... | You can set an individual font size for the legend by adjusting the 'prop' keyword.
```
plot.legend(loc=2,prop={'size':6})
```
This takes a dictionary of keywords corresponding to `matplotlib.font_manager.FontProperties` properties. See the [documentation for legend](http://matplotlib.sourceforge.net/api/pyplot_api.h... |
How to change legend size with matplotlib.pyplot | 7,125,009 | 129 | 2011-08-19T17:06:33Z | 12,257,688 | 7 | 2012-09-04T06:09:04Z | [
"python",
"size",
"matplotlib",
"legend"
] | Simple question here: I'm just trying to get the size of my legend using matplotlib.pyplot to be smaller (ie, the text to be smaller). The code I'm using goes something like this:
```
plot.figure()
plot.scatter(k,sum_cf, color = 'black', label='Sum of Cause Fractions')
plot.scatter(k, data[:, 0], color = 'b', label =... | There are multiple settings for adjusting the legend size. The two I find most useful are:
* labelspacing: which sets the spacing between label entries in multiples of the font size. For instance with a 10 point font, `legend(..., labelspacing=0.2)` will reduce the spacing between entries to 2 points. The default on m... |
How to change legend size with matplotlib.pyplot | 7,125,009 | 129 | 2011-08-19T17:06:33Z | 29,694,950 | 12 | 2015-04-17T09:09:23Z | [
"python",
"size",
"matplotlib",
"legend"
] | Simple question here: I'm just trying to get the size of my legend using matplotlib.pyplot to be smaller (ie, the text to be smaller). The code I'm using goes something like this:
```
plot.figure()
plot.scatter(k,sum_cf, color = 'black', label='Sum of Cause Fractions')
plot.scatter(k, data[:, 0], color = 'b', label =... | There are also a few named [fontsizes](http://matplotlib.org/api/text_api.html#matplotlib.text.Text.set_size), apart from the size in points:
```
xx-small
x-small
small
medium
large
x-large
xx-large
```
Usage:
```
pyplot.legend(loc=2, fontsize = 'x-small')
``` |
Find object in list that has attribute equal to some value (that meets any condition) | 7,125,467 | 57 | 2011-08-19T17:52:25Z | 7,125,547 | 131 | 2011-08-19T18:01:12Z | [
"python",
"django",
"list"
] | I've got list of objects. I want to find one (first or whatever) object in this list that has attribute (or method result - whatever) equal to `value`.
What's is the best way to find it?
Here's test case:
```
class Test:
def __init__(self, value):
self.value = value
import random
value = 5
... | ```
next((x for x in test_list if x.value == value), None)
```
This gets the first item from the list that matches the condition, and returns `None` if no item matches. It's my preferred single-expression form.
However,
```
for x in test_list:
if x.value == value:
print "i found it!"
break
```
T... |
Matplotlib errors result in a memory leak. How can I free up that memory? | 7,125,710 | 8 | 2011-08-19T18:20:20Z | 7,125,856 | 8 | 2011-08-19T18:33:15Z | [
"python",
"memory-leaks",
"matplotlib"
] | I am running a django app that includes matplotlib and allows the user to specify the axes of the graph. This can result in **'Overflow Error: Agg complexity exceeded'**
When that happens up to 100MB of RAM get tied up. Normally I free that memory up using `fig.gcf()`, `plot.close()`, and `gc.collect()`, but the memor... | I assume you can run the code you posted at least once. The problem only manifests itself after running the posted code many times. Correct?
If so, the following avoids the problem without really identifying the source of the problem.
Maybe that is a bad thing, but this works in a pinch: Simply use `multiprocessing` t... |
Matplotlib errors result in a memory leak. How can I free up that memory? | 7,125,710 | 8 | 2011-08-19T18:20:20Z | 12,300,012 | 8 | 2012-09-06T12:20:42Z | [
"python",
"memory-leaks",
"matplotlib"
] | I am running a django app that includes matplotlib and allows the user to specify the axes of the graph. This can result in **'Overflow Error: Agg complexity exceeded'**
When that happens up to 100MB of RAM get tied up. Normally I free that memory up using `fig.gcf()`, `plot.close()`, and `gc.collect()`, but the memor... | I find here
<http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg11809.html>
, it gives an interesting answer that may help
try replacing :
```
import matplotlib.pyplot as plt
fig = plt.figure()
```
with
```
from matplotlib import figure
fig = figure.Figure()
``` |
Python with statements | 7,125,727 | 3 | 2011-08-19T18:22:23Z | 7,125,764 | 19 | 2011-08-19T18:24:53Z | [
"python",
"raii",
"with-statement"
] | I'm experimenting with Python's `with` statements, and I've found that in the following code listing my `__init__` method gets called twice, while my `__exit__` method gets called once. This presumably means that there will be a resource leak if this code did anything useful.
```
class MyResource:
def __enter__(se... | You shouldn't return a new instance from `__enter__`. Instead, return `self` (the instance for which `__enter__` is being called. That's why `__init__()` is called twice -- you call it twice, once in your with statement, once in `__enter__()`. Here's a correct version:
```
def __enter__(self):
print 'Entering MyRe... |
Standard error in non-linear regression | 7,126,190 | 7 | 2011-08-19T19:04:09Z | 7,129,528 | 9 | 2011-08-20T03:50:26Z | [
"python",
"numpy",
"scipy",
"gnuplot"
] | I have been doing some Monte Carlo physics simulations with Python and I am in unable to determine the standard error for the coefficients of a non-linear least square fit.
Initially, I was using SciPy's `scipy.stats.linregress` for my model since I thought it would be a linear model but noticed it is actually some so... | Finally found the answer to this long asked question! I'm hoping this can at least save someone a few hours of hopeless research for this topic. Scipy has a special function called curve\_fit under its optimize section. It uses the least square method to determine the coefficients and best of all, it gives you the cova... |
Perform a string operation for every element in a Python list | 7,126,916 | 17 | 2011-08-19T20:14:11Z | 7,126,928 | 7 | 2011-08-19T20:16:10Z | [
"python"
] | I have an list of string elements in python `elements` and would like edit each element in elements with so I have a new element. See code below (it doesn't work but you'll get the idea):
```
for element in elements:
element = "%" + element + "%"
```
Is there a way to do this? | You can use list comprehension:
```
elements = ["%" + e + "%" for e in elements]
``` |
Perform a string operation for every element in a Python list | 7,126,916 | 17 | 2011-08-19T20:14:11Z | 7,126,937 | 35 | 2011-08-19T20:16:42Z | [
"python"
] | I have an list of string elements in python `elements` and would like edit each element in elements with so I have a new element. See code below (it doesn't work but you'll get the idea):
```
for element in elements:
element = "%" + element + "%"
```
Is there a way to do this? | ```
elements = ['%{0}%'.format(element) for element in elements]
``` |
Python: Find location of data within JSON object, parse the corresponding data | 7,127,053 | 2 | 2011-08-19T20:29:40Z | 7,127,475 | 10 | 2011-08-19T21:12:32Z | [
"python",
"json"
] | I am getting this JSON object from a Simplegeo request. For certain areas, you will not have Address data. In those cases, I want to be able to find the part in the data with "subcategory":"County" and then query the corresponding name.
What is the best way to find the location of data within a JSON response and grab ... | First you will need to convert your JSON string into a Python dictionary using the [`json`](http://docs.python.org/library/json.html) module.
If `data` is your new dictionary, the information you are looking for is in the list `data["features"]`. You will need to iterate over this list and filter out any entries that ... |
what exactly the python's file.flush() is doing? | 7,127,075 | 72 | 2011-08-19T20:32:23Z | 7,127,162 | 120 | 2011-08-19T20:40:36Z | [
"python",
"io",
"output-buffering",
"fsync"
] | I found this in the Python [documentation for File Objects](http://docs.python.org/2/library/stdtypes.html?highlight=file%20flush#file.flush):
> flush() does not necessarily write the fileâs data to disk. Use flush() followed by os.fsync() to ensure this behavior.
So my question is: what exactly is Python's `flush`... | There's typically two levels of buffering involved:
1. Internal buffers
2. Operating system buffers
The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file objec... |
Multiple 'in' operators in Python? | 7,128,153 | 9 | 2011-08-19T22:41:40Z | 7,128,175 | 24 | 2011-08-19T22:44:53Z | [
"python"
] | **Is there a shorthand way of checking for keys in a dictionary?**
Something that I can use instead of using multiple `in` and `and` operators - instead of the following:
```
('somekey' in d) and ('someotherkey' in d) and ('somekeyggg' in d)
``` | ```
all( word in d for word in [ 'somekey', 'someotherkey', 'somekeyggg' ] )
``` |
How to properly install Python on OSX for use with OpenCV? | 7,128,761 | 4 | 2011-08-20T00:39:07Z | 13,574,015 | 7 | 2012-11-26T22:10:11Z | [
"python",
"osx",
"opencv",
"homebrew"
] | I spent the past couple of days trying to get opencv to work with my Python 2.7 install. I kept getting an error saying that opencv module was not found whenever I try "import cv".
I then decided to try installing opencv using Macports, but that didn't work.
Next, I tried Homebrew, but that didn't work either.
Event... | I spent a couple days on this myself. For me, the problem was that that OpenCV installer was not finding the right python installation. It was defaulting to the MacOS-installed version despite the fact that I had upgraded python with homebrew and was using a virtualenv for python. I have collected most of my setup in a... |
Python: How to suppress the output of os.system | 7,129,107 | 6 | 2011-08-20T01:58:39Z | 7,129,187 | 15 | 2011-08-20T02:15:38Z | [
"python"
] | In Python , If I am using "wget" to download a file using os.system("wget ), it shows on the screen like:
```
Resolving...
Connecting to ...
HTTP request sent, awaiting response...
100%[==============================================================================================================================... | The `os.system` functions runs the command via a shell, so you can put any stdio redirects there as well. You should also use the `-q` flag (quiet) to wget.
```
cmd = "wget -q " + theurl + " >/dev/null 2>&1"
```
However, there are better ways of doing this in python, such as the pycurl wrapper for libcurl, or the "st... |
Why would you use the return statement in Python? | 7,129,285 | 18 | 2011-08-20T02:44:34Z | 7,129,293 | 41 | 2011-08-20T02:47:19Z | [
"python",
"printing",
"return"
] | What is the simple basic explanation of what the return statement is, how to use it in Python?
And what is the difference between it and the `print` statement? | The `print()` function writes, i.e., "prints", a string in the console. The `return` statement causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. The `return` statement is used when a function is ready to return a value to its c... |
Why would you use the return statement in Python? | 7,129,285 | 18 | 2011-08-20T02:44:34Z | 7,156,385 | 11 | 2011-08-23T04:47:35Z | [
"python",
"printing",
"return"
] | What is the simple basic explanation of what the return statement is, how to use it in Python?
And what is the difference between it and the `print` statement? | I think the *dictionary* is your best reference here
[Return](http://dictionary.reference.com/browse/return) and [Print](http://dictionary.reference.com/browse/print)
In short:
**return** *gives something back* or *replies* to the caller of the function while **print** *produces text* |
Why would you use the return statement in Python? | 7,129,285 | 18 | 2011-08-20T02:44:34Z | 7,156,533 | 10 | 2011-08-23T05:12:14Z | [
"python",
"printing",
"return"
] | What is the simple basic explanation of what the return statement is, how to use it in Python?
And what is the difference between it and the `print` statement? | Think of the print statement as causing a ***side-effect***, it makes your function write some text out to the user, but it can't be **used by another function.**
I'll attempt to explain this better with some examples, and a couple definitions from Wikipedia.
Here is the definition of a function from Wikipedia
*A fu... |
User defined __mul__ method is not commutative | 7,129,441 | 16 | 2011-08-20T03:30:26Z | 7,129,520 | 19 | 2011-08-20T03:48:20Z | [
"python",
"extend",
"built-in"
] | I wrote a class to represent vectors in Python (as an exercise) and I'm having problems with extending the built-in operators.
I defined a `__mul__` method for the vector class. The problem is that in the expression `x * y` the interpreter calls the `__mul__` method of x, not y.
So `vector(1, 2, 3) * 2` returns a vec... | If you want commutativity *for different types* you need to implement [`__rmul__()`](http://docs.python.org/reference/datamodel.html#object.__rmul__). If implemented, it is called, like all `__r*__()` special methods, if the operation would otherwise raise a `TypeError`. Beware that the arguments are swapped:
```
clas... |
python variable method name | 7,129,736 | 7 | 2011-08-20T04:50:37Z | 7,129,749 | 8 | 2011-08-20T04:54:13Z | [
"python",
"function",
"variables",
"methods"
] | How can you execute a method by giving its name, from another method that is in the same class with the called method? Like this:
```
class Class1:
def __init__(self):
pass
def func1(self, arg1):
# some code
def func2(self):
function = getattr(sys.modules[__name__], "func1") # appar... | how about `getattr(self, "func1")`? Also, avoid using the name function
For example:
```
>>> class C:
... def f1(self, arg1): print arg1
... def f2(self): return getattr(self, "f1")
...
>>> x=C()
>>> x.f2()(1)
1
``` |
UnboundLocalError- local variable referenced before assignment - Django | 7,129,795 | 2 | 2011-08-20T05:04:58Z | 7,129,846 | 7 | 2011-08-20T05:16:31Z | [
"python",
"django",
"django-forms",
"django-views"
] | You guys have helped me out so much this week it has been awesome.Hopefully you can help me out with this one. I tried looking at the other posts on the site about this type of error, but none of them really helped me out. Basically I am submitting a form on one page and the POST data is going to the same view that it ... | This is happening because `request.method == 'POST'` is True (first condition passes) but `form.is_valid()` is False (second nested condition fails), which means the final return after the else is run but ctxt is not defined.
Perhaps you intended that final return to be indented as a part of the `else` clause? |
In Ubuntu Python 2.7 reading output of an os.system() command | 7,129,928 | 2 | 2011-08-20T05:33:52Z | 7,129,953 | 7 | 2011-08-20T05:41:15Z | [
"python",
"ubuntu",
"ubuntu-11.04",
"python-2.7",
"os.system"
] | So I am running code that looks like this on Ubuntu 11.4 and Python 2.7:
```
p_scan_command = "sudo nmap -sC -sV -PN -O 192.168.0.1/24"
time.sleep(1.5)
os.system(p_scan_command)
f = open('nmapscan1.log', 'r')
print f.read()
f.close()
```
What is happening is that I end up with no results, and the scan is not being ru... | 1. Are you sure that the log file is even created? I cannot see where this name is mentionned - but maybe it is created by default.
2. Are you asked for the password by `sudo`?
This could tell you if sudo is really run.
3. `os.system` is kind of deprecated or at least frowned upon; better use `subprocess.call()`, `s... |
3D vector field in matplotlib | 7,130,474 | 14 | 2011-08-20T07:37:09Z | 24,576,593 | 19 | 2014-07-04T14:36:08Z | [
"python",
"vector",
"3d",
"matplotlib"
] | Is there a way to plot a 3D vector field in matplotlib? I have seen [quiver](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.quiver), but it only talks about a "2-D vector field of arrows". Is there a 3D counterpart somewhere?
LMGTFY:
I figured a documentation for the 3D counterpart would be ... | As of matplotlib 1.4.x, quiver can now plot in 3d.
quiver3d\_demo.py in the examples directory:
```
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),
np.aran... |
What are some lightweight alternatives to django-sentry for logging? | 7,130,985 | 6 | 2011-08-20T09:44:25Z | 7,579,467 | 9 | 2011-09-28T07:05:26Z | [
"python",
"django",
"sentry"
] | Are there any lightweight alternatives to `django-sentry` for error logging in a Django environment?
I used `django-db-log` earlier which now known as `django-sentry`. Some of the others I found were pretty much dead as they had no commits in the last two years almost.
Thanks. | Sentry being overkill and Djangodblog being deprecated, I rolled my own, cannibalising the necessary parts from both.
How it works is by catching the error signal. Then it uses Django's inbuilt exception reporter to generate the fancy 500 error page that Django displays when debugging is enabled. We store this in the ... |
Is "with" monadic? | 7,131,027 | 27 | 2011-08-20T09:53:31Z | 7,131,142 | 8 | 2011-08-20T10:11:43Z | [
"python",
"functional-programming",
"monads"
] | Like many a foolhardy pioneer before me, I'm endeavoring to cross the trackless wasteland that is Understanding Monads.
I'm still staggering through, but I can't help noticing a certain monad-like quality about Python's `with` statement. Consider this fragment:
```
with open(input_filename, 'r') as f:
for line in ... | **Yes.**
Right below the definition, [Wikipedia says](https://secure.wikimedia.org/wikipedia/en/wiki/Monad_%28functional_programming%29):
> In object-oriented programming terms, the type construction would correspond to the declaration of the monadic type, the unit function takes the role of a constructor method, and... |
Is "with" monadic? | 7,131,027 | 27 | 2011-08-20T09:53:31Z | 7,131,291 | 18 | 2011-08-20T10:49:53Z | [
"python",
"functional-programming",
"monads"
] | Like many a foolhardy pioneer before me, I'm endeavoring to cross the trackless wasteland that is Understanding Monads.
I'm still staggering through, but I can't help noticing a certain monad-like quality about Python's `with` statement. Consider this fragment:
```
with open(input_filename, 'r') as f:
for line in ... | It's almost too trivial to mention, but the first problem is that `with` isn't a function and doesn't take a function as an argument. You can easily get around this by writing a function wrapper for `with`:
```
def withf(context, f):
with context as x:
f(x)
```
Since this is so trivial, you could not both... |
building full path filename in python, | 7,132,861 | 56 | 2011-08-20T15:53:08Z | 7,132,886 | 12 | 2011-08-20T15:57:21Z | [
"python",
"join",
"filenames"
] | I need to pass a file path name to a module which creates a report document as pdf,html etc.How do I build the file path name from a directory name,base file name and a fileformat string ?
The directory may or may not exist at the time of call
for example
```
dir_name='/home/me/dev/my_reports'
base_filename='daily_r... | Um, why not just:
```
>>>> import os
>>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'
```
? |
building full path filename in python, | 7,132,861 | 56 | 2011-08-20T15:53:08Z | 7,133,204 | 75 | 2011-08-20T16:49:41Z | [
"python",
"join",
"filenames"
] | I need to pass a file path name to a module which creates a report document as pdf,html etc.How do I build the file path name from a directory name,base file name and a fileformat string ?
The directory may or may not exist at the time of call
for example
```
dir_name='/home/me/dev/my_reports'
base_filename='daily_r... | This works fine:
```
os.path.join(dir_name, base_filename + "." + filename_suffix)
```
Keep in mind that `os.path.join()` exists to smooth over the different path separator characters used by different operating systems. File name "extensions" only have significant meaning on one major operating system (they're simpl... |
sqlalchemy: get max/min/avg values from a table | 7,133,007 | 5 | 2011-08-20T16:15:02Z | 11,846,873 | 10 | 2012-08-07T13:15:47Z | [
"python",
"sqlalchemy"
] | I have this query:
```
mps = (
session.query(mps) .filter_by(idc = int(c.idc))
.filter_by(idmp = int(m.idmp))
.group_by(func.day(mps.tschecked))
).all()
```
My problem is, that I don't know how to extract (with sqlalchemy) the max/... | The following functions are available with `from sqlalchemy import func`:
* `func.min`
* `func.max`
* `func.avg`
Documentation is available [here](http://docs.sqlalchemy.org/en/latest/core/sqlelement.html?highlight=func#sqlalchemy.sql.expression.func).
You can use them i.e. in the query() method.
Example:
```
sess... |
Python: yield-and-delete | 7,133,179 | 9 | 2011-08-20T16:44:23Z | 7,133,220 | 7 | 2011-08-20T16:52:14Z | [
"python"
] | How do I yield an object from a generator and forget it immediately, so that it doesn't take up memory?
For example, in the following function:
```
def grouper(iterable, chunksize):
"""
Return elements from the iterable in `chunksize`-ed lists. The last returned
element may be smaller (if length of collec... | After `yield chunk`, the variable value is never used again in the function, so a good interpreter/garbage collector will already free `chunk` for garbage collection (note: cpython 2.7 seems *not* do this, pypy 1.6 with default gc does). Therefore, you don't have to change anything but your code example, which is missi... |
Generate alphanumeric strings sequentially | 7,133,676 | 4 | 2011-08-20T18:12:39Z | 7,133,704 | 14 | 2011-08-20T18:17:34Z | [
"python",
"string",
"algorithm"
] | I'm trying to create a loop to generate and print strings as follows:
1. Alphanumeric characters only:
2. 0-9 are before A-Z, which are before a-z,
3. Length goes up to 4 characters.
So, it would print:
1. all strings from 0-z
2. then from 00-zz
3. then from 000-zzz
4. then from 0000-zzzz
then it stops. | ```
from string import digits, ascii_uppercase, ascii_lowercase
from itertools import product
chars = digits + ascii_uppercase + ascii_lowercase
for n in range(1, 4 + 1):
for comb in product(chars, repeat=n):
print ''.join(comb)
```
This first makes a string of all the numbers, uppercase letters, and low... |
Fastest way to grow a numpy numeric array | 7,133,885 | 29 | 2011-08-20T18:45:03Z | 7,134,033 | 28 | 2011-08-20T19:08:28Z | [
"python",
"performance",
"numpy"
] | Requirements:
* I need to grow an array arbitrarily large from data.
* I can guess the size (roughly 100-200) with no guarantees that the array will fit every time
* Once it is grown to its final size, I need to perform numeric computations on it, so I'd prefer to eventually get to a 2-D numpy array.
* Speed is critic... | I tried a few different things, with timing.
```
import numpy as np
```
1. The method you mention as slow: (32.094 seconds)
```
class A:
def __init__(self):
self.data = np.array([])
def update(self, row):
self.data = np.append(self.data, row)
def finalize(self):
... |
Fastest way to grow a numpy numeric array | 7,133,885 | 29 | 2011-08-20T18:45:03Z | 7,135,303 | 10 | 2011-08-20T23:10:29Z | [
"python",
"performance",
"numpy"
] | Requirements:
* I need to grow an array arbitrarily large from data.
* I can guess the size (roughly 100-200) with no guarantees that the array will fit every time
* Once it is grown to its final size, I need to perform numeric computations on it, so I'd prefer to eventually get to a 2-D numpy array.
* Speed is critic... | np.append() copy all the data in the array every time, but list grow the capacity by a factor (1.125). list is fast, but memory usage is larger than array. You can use array module of the python standard library if you care about the memory.
Here is a discussion about this topic:
[How to create a dynamic array](http:... |
datetime: print as seconds | 7,133,977 | 3 | 2011-08-20T18:59:52Z | 7,134,020 | 12 | 2011-08-20T19:06:54Z | [
"python",
"datetime",
"python-3.x"
] | I have a `datetime` object. I want to print it as just number of seconds (i.e., 1 min 30.5 sec should print as 90.5 s). Can't seem to find a way to do it with `strftime`. | I think that for your situation you'd be better off using a datetime.timedelta object. It has a function that will do exactly what you want, datetime.timedelta.total\_seconds(). |
Can't use pip anymore | 7,134,071 | 4 | 2011-08-20T19:15:11Z | 7,134,192 | 7 | 2011-08-20T19:37:29Z | [
"python",
"pip"
] | When I try to use pip, I met this error:
```
Traceback (most recent call last):
File "/usr/local/bin/pip", line 9, in <module>
load_entry_point('pip==1.0.2', 'console_scripts', 'pip')()
File "/usr/local/lib/python2.6/dist-packages/distribute-0.6.21-py2.6.egg/pkg_resources.py", line 337, in load_entry_point
... | I note that distribute is installed in `/usr/local` but pip is in `/usr/lib`, so I'm guessing that you have an older version of pip installed system wide that is somehow overriding what you're `easy_install`ed or `pip`ed. I'd start looking there. |
Max size of a file Python can open? | 7,134,338 | 5 | 2011-08-20T20:05:49Z | 7,134,355 | 10 | 2011-08-20T20:08:08Z | [
"python",
"string",
"limit"
] | I opened an 8 MB file in Python, because I wanted to batch change various types of file names. I went through and loaded the file into a string and used the string method replace to replace everything. I then noticed that only half of the file was being replaced; as if Python wasn't fully opening the file.
Is there so... | No, there is no reachable maximum on the size of a file Python can open. 8 MB is *tiny* in modern terms. You made a mistake somewhere.
People regularly load *gigabytes* of data into memory. Depending on your computer's RAM, whether it's 64- or 32- bit OS and processor, the practical maximum for you may be anywhere fro... |
Python (yield): all paths from leaves to root in a tree | 7,134,742 | 5 | 2011-08-20T21:16:49Z | 7,134,763 | 7 | 2011-08-20T21:19:20Z | [
"python",
"yield"
] | I want to generate all paths from every leaf to root in a tree. I'd like to do that with generators, to save memory (tree can be big). Here's my code:
```
def paths(self, acc=[]):
if self.is_leaf():
yield [self.node]+acc
for child in self.children:
child.paths([self.node]+acc)
```
But it does... | This code only yields leaves that are (immediate) children of the root. The other ones get visited, they yield to the upper function, but the upper function does nothing with them. What you need is to yield them from the lower function to the upper one:
```
def paths(self, acc=[]):
if self.is_leaf():
yield... |
Sort python list by function | 7,135,836 | 12 | 2011-08-21T01:43:14Z | 7,135,846 | 10 | 2011-08-21T01:46:23Z | [
"python",
"list",
"sorting"
] | I have a function that takes an object as an argument and gives me a number. I wish to use this number as the key to sort my list.
If I were to iterate over the list I would do something like:
```
sorted_list = []
for object in my_list_of_objects:
i = my_number_giving_function(object)
sorted_list.insert(i, ob... | ```
sort(my_list_of_objects, key=my_number_giving_function)
```
same for sorted, [see the Python Sorting HOWTO](http://docs.python.org/howto/sorting.html) |
Python For Loop Slowing With Time | 7,136,200 | 6 | 2011-08-21T03:47:59Z | 7,136,226 | 13 | 2011-08-21T03:55:55Z | [
"python",
"performance",
"for-loop",
"python-3.x",
"range"
] | So I'm having a little trouble dealing with for loops in Python - as far as I can tell, they're getting slower with time. I'm looping over a range inside of a range, and as time passes, the loop noticeably slows. This is done inside of a game engine, if it matters. Could anyone tell me what the issue is?
Here's a quic... | This is another case of "need more information". However, Python has a standard way of constructing nested loops like this efficiently, [`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product):
```
from itertools import product
for x, y, z in product(xrange(xs), xrange(zs), xrange(ys)):
... |
data table in Python | 7,136,432 | 3 | 2011-08-21T04:48:28Z | 7,136,489 | 7 | 2011-08-21T05:03:33Z | [
"python",
"formatting"
] | I've got a 2D list in Python like this:
```
[['Something', 'Something else', 'Another thing'],
['Other things', 'More data', 'Element'],
['Stuff', 'data', 'etc']]
```
I want it to be printed out like this:
```
Something Something else Another thing
Other things More data Element
Stuff da... | ```
l = [['Something', 'Something else', 'Another thing'],
['Other things', 'More data', 'Element'],
['Stuff', 'data', 'etc']]
sub1 = [
[s.ljust(max(len(i) for i in column)) for s in column]
for column in zip(*l)]
for p in [" ".join(row) for row in zip(*sub1)]: print p
```
Here, first the list gets t... |
How can I create a tuple where each of the members are compared by an expression? | 7,136,921 | 8 | 2011-08-21T07:12:16Z | 7,136,955 | 12 | 2011-08-21T07:21:04Z | [
"python",
"ruby",
"haskell"
] | Well, here is the thing:
I have the following Haskell code, this one:
```
[ (a, b, c) | c <- [1..10], b <- [1..10], a <- [1..10], a ^ 2 + b ^ 2 == c ^ 2 ]
```
Which will returns
```
[(4,3,5),(3,4,5),(8,6,10),(6,8,10)]
```
For those who aren't familiar with this, I'll explain:
* It returns a `tuple` (a,b,c), where... | It's possible in Python with one long line and with no import. Python's list comprehensions can be used with multiple variables:
```
>>> [ (a, b, c) for c in range(1, 11) for b in range(1, 11) for a in range(1, 11) if a*a + b*b == c*c ]
[(4, 3, 5), (3, 4, 5), (8, 6, 10), (6, 8, 10)]
``` |
How can I create a tuple where each of the members are compared by an expression? | 7,136,921 | 8 | 2011-08-21T07:12:16Z | 7,136,965 | 11 | 2011-08-21T07:23:26Z | [
"python",
"ruby",
"haskell"
] | Well, here is the thing:
I have the following Haskell code, this one:
```
[ (a, b, c) | c <- [1..10], b <- [1..10], a <- [1..10], a ^ 2 + b ^ 2 == c ^ 2 ]
```
Which will returns
```
[(4,3,5),(3,4,5),(8,6,10),(6,8,10)]
```
For those who aren't familiar with this, I'll explain:
* It returns a `tuple` (a,b,c), where... | Ruby solution:
```
(1..10).to_a.repeated_permutation(3).select { |a, b, c| a*a + b*b == c*c }
# => [[3, 4, 5], [4, 3, 5], [6, 8, 10], [8, 6, 10]]
``` |
How can I create a tuple where each of the members are compared by an expression? | 7,136,921 | 8 | 2011-08-21T07:12:16Z | 7,137,074 | 9 | 2011-08-21T07:48:29Z | [
"python",
"ruby",
"haskell"
] | Well, here is the thing:
I have the following Haskell code, this one:
```
[ (a, b, c) | c <- [1..10], b <- [1..10], a <- [1..10], a ^ 2 + b ^ 2 == c ^ 2 ]
```
Which will returns
```
[(4,3,5),(3,4,5),(8,6,10),(6,8,10)]
```
For those who aren't familiar with this, I'll explain:
* It returns a `tuple` (a,b,c), where... | Python solution, using [`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product), which is equivalent to nested for-loops in a generator expression:
```
[(a,b,c) for c,b,a in product(range(1,11), repeat=3) if a*a + b*b == c*c]
``` |
Python C API: Modify search path | 7,137,412 | 2 | 2011-08-21T09:21:24Z | 7,137,484 | 7 | 2011-08-21T09:37:59Z | [
"python",
"c"
] | How can I add a speciific directory to the search path using the C API? And a related question: will the changes be local to the application, or is the search path global? | Use [`PySys_GetObject("path")`](http://docs.python.org/c-api/sys.html#PySys_GetObject) to retrieve `sys.path`, then manipulate it as you would [any other sequence](http://docs.python.org/c-api/sequence.html) or [list](http://docs.python.org/c-api/list.html). Changes will be local to the Python interpreter/VM. |
How to match '-' literally inside [..] in regular expression | 7,137,817 | 3 | 2011-08-21T10:54:39Z | 7,137,834 | 9 | 2011-08-21T10:56:57Z | [
"python",
"regex"
] | I am trying to match a '-' inside a [..] block using regular expressions in python, but, I am not sure how to make that happen, since '-' denotes ranges in that block.
Edit: my failing regex:
```
regex = re.compile("^[0-9+-*/]+$")
``` | From [the docs](http://docs.python.org/library/re.html):
> If you want to include a `']'` or a `'-'` inside a set, precede it with a backslash, or place it as the first character. |
Vim autocomplete for Python | 7,138,039 | 32 | 2011-08-21T11:42:25Z | 12,581,140 | 38 | 2012-09-25T10:33:37Z | [
"python",
"vim"
] | I am trying to incorporate an autocomplete feature in [Vim](http://en.wikipedia.org/wiki/Vim_%28text_editor%29). I have used the omnicompletion of Vim as well as [Pydiction](http://www.vim.org/scripts/script.php?script_id=850). But in both the cases this message pops up:
**Omni completion (^O^N^P) Pattern not found**
... | Try [Jedi](https://github.com/davidhalter/jedi)! There's a Vim plugin at <https://github.com/davidhalter/jedi-vim>.
It works just much better than anything else for Python in Vim. It even has support for renaming, goto, etc. The best part is probably that it really tries to understand your code (decorators, generators... |
Vim autocomplete for Python | 7,138,039 | 32 | 2011-08-21T11:42:25Z | 20,093,355 | 10 | 2013-11-20T10:29:00Z | [
"python",
"vim"
] | I am trying to incorporate an autocomplete feature in [Vim](http://en.wikipedia.org/wiki/Vim_%28text_editor%29). I have used the omnicompletion of Vim as well as [Pydiction](http://www.vim.org/scripts/script.php?script_id=850). But in both the cases this message pops up:
**Omni completion (^O^N^P) Pattern not found**
... | This can be a good option if you want python completion as well as other languages. <https://github.com/Valloric/YouCompleteMe>
The python completion is jedi based same as jedi-vim. |
is OverflowError actually raised? | 7,138,387 | 5 | 2011-08-21T12:52:49Z | 7,138,407 | 7 | 2011-08-21T12:56:05Z | [
"python"
] | According to the python documentation
```
exception OverflowError
Raised when the result of an arithmetic operation is too large to
be represented. This cannot occur for long integers (which would
rather raise MemoryError than give up) and for most operations with
plain integers, which return a long ... | ```
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> float(10**1000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: long int too large to co... |
How to write a list to a file with newlines in Python3 | 7,138,686 | 7 | 2011-08-21T13:59:31Z | 7,138,705 | 14 | 2011-08-21T14:03:11Z | [
"python",
"python-3.x"
] | I'm trying to write an array (list?) to a text file using Python 3. Currently I have:
```
def save_to_file(*text):
with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile:
for lines in text:
print(lines, file = myfile)
myfile.close
```
This writes what looks like the arr... | `myfile.close` -- get rid of that where you use `with`. `with` automatically closes `myfile`, and you have to call `close` like `close()` anyway for it to do anything when you're not using `with`. You should just always use `with` on Python 3.
```
with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfi... |
python extension methods | 7,139,111 | 11 | 2011-08-21T15:14:36Z | 7,139,148 | 10 | 2011-08-21T15:21:21Z | [
"python",
"extension-methods"
] | OK, in c# we have something like:
```
public static string Destroy(this string s) {
return "";
}
```
So basically, when you have a string you can do:
```
str = "This is my string to be destroyed";
newstr = str.Destroy()
# instead of
newstr = Destroy(str)
```
Now this is cool because in my opinion it's more re... | You can just modify the class directly, sometimes known as monkey patching.
```
def MyMethod(self):
return self + self
MyClass.MyMethod = MyMethod
del(MyMethod)#clean up namespace
```
I'm not 100% sure you can do this on a special class like str, but it's fine for your user-defined classes.
**Update**
You co... |
TypeError: 'str' does not support the buffer interface | 7,139,225 | 6 | 2011-08-21T15:37:01Z | 7,139,297 | 17 | 2011-08-21T15:47:02Z | [
"python",
"file-io",
"md5"
] | ```
import hashlib
infile = open("P:\\r.mp3", 'r+b')
data = infile.readline()
hash = hashlib.md5()
hash.update(data)
hash_digest = hash.hexdigest()
print(hash_digest)
#hash_digest = hash_digest.encode('utf-8')
print(hash_digest)
with open("lt.txt", 'ab') as outfile:
outfile.write(hash_digest + '\n') #error here... | You're using Python 3, where there is a strict division between text (`str`) and data (`bytes`). Text can't be written to a file if you don't explicitly encode it first.
There are two ways to do this:
1) Open the file in text mode (possibly with an encoding specified) so that strings are automatically encoded for you... |
Python: SSH into Cisco device and run show commands | 7,140,817 | 11 | 2011-08-21T20:09:29Z | 7,140,956 | 14 | 2011-08-21T20:31:13Z | [
"python",
"ssh",
"cisco"
] | I have read over this post extensively and have researched Exscript, paramiko, Fabric and pxssh and I am still lost [Persistent ssh session to Cisco router](http://stackoverflow.com/questions/5238000/persistent-ssh-session-to-cisco-router) . I am new to python scripting.
I am attempting to write a script in Python tha... | Try executing `terminal length 0` before running `show version`. For example:
```
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
account = read_login()
conn = SSH2()
conn.connect('192.168.1.11')
conn.login(account)
conn.execute('terminal ... |
Python-Like "Classes" in Javascript | 7,140,980 | 4 | 2011-08-21T20:33:53Z | 7,141,051 | 9 | 2011-08-21T20:46:01Z | [
"javascript",
"python",
"class"
] | I was wondering how one would go about making "classes" similar to those in Python in Javascript. Take the Python classes and functions listed here:
```
class one:
def foo(bar):
# some code
```
The function "foo" would be called with `one.foo(bar)`.
What would the JS equivalent be? I suspect it would be... | The native way to create classes in Javascript is to first define the constructor:
```
function MyClass() {
}
```
and a prototype:
```
MyClass.prototype = {
property: 1,
foo: function(bar) {
}
};
```
Then you can create instance of MyClass:
```
var object = new MyClass;
object.foo();
```
Add static me... |
Parsing binary files with Python | 7,141,091 | 6 | 2011-08-21T20:51:35Z | 7,141,107 | 11 | 2011-08-21T20:53:05Z | [
"python",
"binaryfiles"
] | As a side project I would like to try to parse binary files (Mach-O files specifically). I know tools exist for this already (otool) so consider this a learning exercise.
The problem I'm hitting is that I don't understand how to convert the binary elements found into a python representation. For example, the Mach-O fi... | Take a look at the [`struct`](http://docs.python.org/library/struct.html) module:
```
In [1]: import struct
In [2]: magic = b'\xcf\xfa\xed\xfe'
In [3]: decoded = struct.unpack('<I', magic)[0]
In [4]: hex(decoded)
Out[4]: '0xfeedfacf'
``` |
Python simple if or logic statement | 7,141,208 | 38 | 2011-08-21T21:11:32Z | 7,141,226 | 77 | 2011-08-21T21:13:27Z | [
"python",
"if-statement",
"logic"
] | How would you write, in python:
```
if key < 1 or key > 34:
```
I've tried every way I can think of, and am finding it very frustrating. | If `key` isn't an `int` or `float` but a `str`ing, you need to convert it to an `int` first by doing
```
key = int(key)
```
or to a `float` by doing
```
key = float(key)
```
Otherwise, what you have in your question should work, but
```
if (key < 1) or (key > 34):
```
or
```
if not (1 <= key <= 34):
```
would b... |
Pipe input to Python program and later get input from user | 7,141,331 | 13 | 2011-08-21T21:34:33Z | 7,141,375 | 10 | 2011-08-21T21:45:07Z | [
"python",
"bash",
"stdin"
] | Let's say I want to pipe input to a Python program, and then later get input from the user, on the command line.
```
echo http://example.com/image.jpg | python solve_captcha.py
```
and the contents of `solve_captcha.py` are:
```
import sys
image_url = sys.stdin.readline()
# Download and open the captcha...
captch... | There isn't a general solution to this problem. The best resource seems to be [this mailing list thread](http://mail.python.org/pipermail/python-list/2000-March/048890.html).
Basically, piping into a program connects the program's `stdin` to that pipe, rather than to the terminal.
The mailing list thread has a couple... |
Tkinter: Wait for item in queue | 7,141,509 | 9 | 2011-08-21T22:12:27Z | 7,198,960 | 10 | 2011-08-26T00:54:58Z | [
"python",
"multithreading",
"event-handling",
"tkinter"
] | Iâm using a queue to exchange messages between a background thread and a Tk GUI application. Currently, this is done by calling a query method every now and then.
```
def read_queue(self):
try:
self.process(self.queue.get(False)) # non-blocking
except Queue.Empty:
pass
finally:
se... | One option might be mtTkinter <http://tkinter.unpythonic.net/wiki/mtTkinter>
Here is another example of using event\_generate from a background thread:
```
##The only secure way I found to make Tkinter mix with threads is to never
##issue commands altering the graphical state of the application in another
##threa... |
Python standard library function for rearranging a list | 7,141,577 | 7 | 2011-08-21T22:28:24Z | 7,141,833 | 9 | 2011-08-21T23:26:07Z | [
"python",
"list",
"function",
"order",
"standards"
] | I am wondering if there is a standard library function in Python which will rearrange the elements of a list like below:
```
a = [1,2,3,4,5,6,7]
function(a)
print a
a = [1,7,2,6,3,5,4]
```
It should get one element from beginning of original list, then one from end, then second from beginning and so on. Then rearr... | You could build a fast, memory efficient [generator](http://wiki.python.org/moin/Generators) using [`itertools`](http://docs.python.org/library/itertools.html) which does what you want:
```
from itertools import chain, izip
def reorder(a):
gen = chain.from_iterable(izip(a, reversed(a)))
for _ in a:
yi... |
Multithreading with Pygame | 7,141,665 | 3 | 2011-08-21T22:49:31Z | 7,147,274 | 8 | 2011-08-22T12:13:07Z | [
"python",
"multithreading",
"pygame"
] | I'm having some trouble writing a simple Pygame application that uses threads. Please keep in mind that this is the first multithreaded code I've ever written.
Here's the situation. I'm writing a simple app that will draw some funky lines to the screen. My problem is that while I'm drawing the lines, the app can't han... | Although I have never used pygame, I doubt that you can (or should) call its API from different threads. All your drawing should be done in the main event loop.
I guess you have to change the way you are thinking for game development. Instead of using `time.sleep()` to pause the drawing, create an object that can be u... |
use of python super function in django model | 7,141,820 | 8 | 2011-08-21T23:21:38Z | 7,141,837 | 19 | 2011-08-21T23:27:15Z | [
"python",
"django",
"super"
] | Here's some code in a django tutorial that I'm going through. I've never come across the super function in python before and the way it's used here is different from the examples I've seen online. I.e., usually when you use super, don't you have multiple classes? It's in the last line: `super(Snippet, self).save(force_... | `super(Snippet, self)` causes Python to look in the [MRO](http://www.python.org/download/releases/2.3/mro/) of the class of self (i.e. `self.__class__.mro()` for the *next* class listed after `Snippet`. It returns a `super` object which acts as a proxy for that class. That is, calling a method on the `super` object act... |
How do I sort a zipped list in Python? | 7,142,227 | 8 | 2011-08-22T00:58:55Z | 7,142,240 | 12 | 2011-08-22T01:01:57Z | [
"python",
"list",
"sorting",
"zip"
] | What's the Pythonic way to sort a zipped list?
code :
```
names = list('datx')
vals = reversed(list(xrange(len(names))))
zipped = zip(names, vals)
print zipped
```
The code above prints **[('d', 3), ('a', 2), ('t', 1), ('x', 0)]**
I want to sort **zipped** by the values. So ideally it would end up looking like th... | ```
zipped.sort(key = lambda t: t[1])
``` |
Get window position & size with python | 7,142,342 | 11 | 2011-08-22T01:24:51Z | 7,142,360 | 13 | 2011-08-22T01:29:05Z | [
"python",
"windows"
] | How can I get and set the window (any windows program) position and size with python? | Assuming you're on Windows, try using `pywin32`'s `win32gui` module with its `EnumWindows` and `GetWindowRect` functions.
If you're using Mac OS X, you could try using `appscript`.
For Linux, you can try one of the many interfaces to X11.
**Edit:** Example for Windows (not tested):
```
import win32gui
def callback... |
Parse FB Graph API date string into python datetime | 7,142,618 | 5 | 2011-08-22T02:28:42Z | 7,142,731 | 10 | 2011-08-22T02:51:30Z | [
"python",
"facebook-graph-api"
] | Here's an example of how the Facebook Graph API is returning date strings for me:
2011-03-06T03:36:45+0000
how would I parse this into a python datetime class? I'm aware of the datetime.strptime function, which takes in a second parameter that contains some googly-eyed format string, but don't know which letters and ... | Here it is with time & [strptime](http://docs.python.org/library/time.html#time.strptime):
```
>>> time.strptime('2011-03-06T03:36:45+0000', '%Y-%m-%dT%H:%M:%S+0000')
time.struct_time(tm_year=2011, tm_mon=3, tm_mday=6, tm_hour=3, tm_min=36, tm_sec=45, tm_wday=6, tm_yday=65, tm_isdst=-1)
```
or with datetime:
```
>>>... |
How can I install packages in my $HOME folder with pip? | 7,143,077 | 193 | 2011-08-22T04:10:25Z | 7,143,349 | 13 | 2011-08-22T05:03:02Z | [
"python",
"pip"
] | Is it possible? When installing [`pip`](http://pip.readthedocs.org/en/latest/installing.html), install the python packages inside my `$HOME` folder. (for example, I want to install `mercurial`, using `pip`, but inside `$HOME` instead of `/usr/local`)
I'm with a mac machine and just thought about this possibility, inst... | I would use virtualenv at your HOME directory.
```
$ sudo easy_install -U virtualenv
$ cd ~
$ virtualenv .
$ bin/pip ...
```
You could then also alter `~/.(login|profile|bash_profile)`, whichever is right for your shell to add ~/bin to your PATH and then that `pip|python|easy_install` would be the one used by default... |
How can I install packages in my $HOME folder with pip? | 7,143,077 | 193 | 2011-08-22T04:10:25Z | 7,143,496 | 236 | 2011-08-22T05:27:59Z | [
"python",
"pip"
] | Is it possible? When installing [`pip`](http://pip.readthedocs.org/en/latest/installing.html), install the python packages inside my `$HOME` folder. (for example, I want to install `mercurial`, using `pip`, but inside `$HOME` instead of `/usr/local`)
I'm with a mac machine and just thought about this possibility, inst... | While you can use a `virtualenv`, you don't need to. The trick is passing the PEP370 `--user` argument to the `setup.py` script. With the latest version of `pip`, one way to do it is:
```
pip install --user mercurial
```
This should result in the `hg` script being installed in `$HOME/.local/bin/hg` and the rest of th... |
How to use avg and sum in SQLAlchemy query | 7,143,235 | 20 | 2011-08-22T04:39:48Z | 7,143,355 | 33 | 2011-08-22T05:03:34Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | I'm trying to return a totals/averages row from my dataset which contains the SUM of certain fields and the AVG of others.
I could do this in SQL via:
```
SELECT SUM(field1) as SumFld, AVG(field2) as AvgFld
FROM Rating WHERE url=[url_string]
```
My attempt to translate this into SQLAlchemy is as follows:
```
total... | You should use something like:
```
from sqlalchemy.sql import func
session.query(func.avg(Rating.field2).label('average')).filter(Rating.url==url_string.netloc)
```
You cannot use `MyObject.query` here, because SqlAlchemy tries to find a field to put result of `avg` function to, and it fails. |
How to use avg and sum in SQLAlchemy query | 7,143,235 | 20 | 2011-08-22T04:39:48Z | 17,435,020 | 18 | 2013-07-02T20:13:51Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | I'm trying to return a totals/averages row from my dataset which contains the SUM of certain fields and the AVG of others.
I could do this in SQL via:
```
SELECT SUM(field1) as SumFld, AVG(field2) as AvgFld
FROM Rating WHERE url=[url_string]
```
My attempt to translate this into SQLAlchemy is as follows:
```
total... | > You cannot use MyObject.query here, because SqlAlchemy tries to find a field to put result of avg function to, and it fails.
This isn't exactly true. `func.avg(Rating.field2).label('average')` returns a `Column` object (the same type object that it was given to be precise). So you can use it with the `with_entities`... |
Applying SVD throws a Memory Error instantaneously? | 7,143,723 | 4 | 2011-08-22T06:08:46Z | 7,155,189 | 7 | 2011-08-23T00:44:20Z | [
"python",
"memory",
"numpy",
"nlp",
"scipy"
] | I am trying to apply SVD on my matrix (3241 x 12596) that was obtained after some text processing (with the ultimate goal of performing Latent Semantic Analysis) and I am unable to understand why this is happening as my 64-bit machine has 16GB RAM. The moment `svd(self.A)` is called, it throws an error. The precise err... | Yes, the `full_matrices` parameter to `scipy.linalg.svd` is important: your input is highly rank-deficient (rank max 3,241), so you don't want to allocate the entire 12,596 x 12,596 matrix for `V`!
More importantly, matrices coming from text processing are likely **very sparse**. The `scipy.linalg.svd` is dense and do... |
Difference between memcache and python dictionary | 7,143,746 | 6 | 2011-08-22T06:13:24Z | 7,143,766 | 8 | 2011-08-22T06:17:15Z | [
"python",
"memcached"
] | In my current project, I am using Memcache to store key-value pairs, but since the communication happens over the socket between my process and the Memcache causing the huge latencies. We went with memcache because we had a requirement of storing large amount of key-value pairs. But now I want to store the dictionary a... | The usual reason to use memcached is that you would like to *distribute* the cache among multiple machines, with the goal of both having data *available* on all the machines, while also utilizing the *storage* of all the machines. If those requirements don't apply to you, and you only need the cached data on a single m... |
Loading QtDesigner's .ui files in PySide | 7,144,313 | 26 | 2011-08-22T07:27:17Z | 7,148,097 | 33 | 2011-08-22T13:19:47Z | [
"python",
"qt",
"pyside"
] | I am looking for a simple example of how to directly load a QtDesigner generated .ui file into a Python application.
I simply would like to avoid using pyuic4. | PySide, unlike PyQt, has implemented the [QUiLoader](https://deptinfo-ensip.univ-poitiers.fr/ENS/pyside-docs/PySide/QtUiTools/QUiLoader.html) class to directly read in .ui files.
From the linked documentation,
```
loader = QUiLoader()
file = QFile(":/forms/myform.ui")
file.open(QFile.ReadOnly)
myWidget = loader.load(f... |
Loading QtDesigner's .ui files in PySide | 7,144,313 | 26 | 2011-08-22T07:27:17Z | 18,293,756 | 33 | 2013-08-17T22:11:03Z | [
"python",
"qt",
"pyside"
] | I am looking for a simple example of how to directly load a QtDesigner generated .ui file into a Python application.
I simply would like to avoid using pyuic4. | For the complete noobs at PySide and .ui files, here is a complete example:
```
from PySide import QtCore, QtGui, QtUiTools
def loadUiWidget(uifilename, parent=None):
loader = QtUiTools.QUiLoader()
uifile = QtCore.QFile(uifilename)
uifile.open(QtCore.QFile.ReadOnly)
ui = loader.load(uifile, parent)
... |
Why am I getting a UnicodeDecodeError in Python's JSON encoding? | 7,146,000 | 2 | 2011-08-22T10:20:01Z | 7,146,199 | 14 | 2011-08-22T10:35:13Z | [
"python",
"json"
] | I am using Solr 3.3 to index stuff from my database. I compose the JSON content in Python. I manage to **upload 2126 records which add up to 523246 chars (approx 511kb)**. But when I try 2027 records, Python gives me the error:
```
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\T... | Simple, just don't use utf-8 encoding if your data is not in utf-8
```
>>> json.loads('["\x96"]')
....
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 0: invalid start byte
>>> json.loads('["\x96"]', encoding="latin-1")
[u'\x96']
```
> **json.loads**
>
> If `s` is a `str` instance and is encoded ... |
Python - how to delete hidden signs from string? | 7,147,396 | 5 | 2011-08-22T12:22:48Z | 7,147,446 | 9 | 2011-08-22T12:27:00Z | [
"python"
] | Sometimes I have a strings with strange characters. They are not visible in browser, but are part of the string and are counted in len().
How can I get rid of it? Strip() deletes normal space but not that signs. | Use the character categories from the `string` module. If you want to allow all printable characters, you can do
```
from string import printable
new_string = ''.join(char for char in the_string if char in printable)
```
Building on YOU's answer, you can do this with `re.sub` too:
```
new_string = re.sub("[^{}]+".fo... |
How to show column headers in a GtkTreeView inside a gtk.ScrolledWindow? | 7,147,489 | 6 | 2011-08-22T12:30:09Z | 7,150,850 | 11 | 2011-08-22T16:58:36Z | [
"python",
"gtk",
"pygtk",
"gtktreeview",
"scrolledwindow"
] | I have a problem with `Gtk.Treeview` indide a `Gtk.ScrolledWindow`. I have a large amount of data, which doesnt fit inside my normal window geometrics, so i put my Treeview inside a `ScrolledWindow`, which seems to be the normal way. The problem with this solution is, that my Column Headers disapear, when I scroll. Thi... | Change `self.scrolledwindow.add_with_viewport` to `self.scrolledwindow.add` and it will work. From [the documentation](http://www.pygtk.org/docs/pygtk/class-gtkscrolledwindow.html#method-gtkscrolledwindow--add-with-viewport):
> The add\_with\_viewport() method is used to add a widget (specified by child) without nativ... |
nested dictionaries or tuples for key? | 7,147,785 | 15 | 2011-08-22T12:56:17Z | 7,148,107 | 9 | 2011-08-22T13:20:25Z | [
"python",
"optimization",
"dictionary"
] | Suppose there is a structure like this:
```
{'key1' : { 'key2' : { .... { 'keyn' : 'value' } ... } } }
```
Using python, I'm trying to determine advantages/disadvantages of two different approaches:
```
{'key1' : { 'key2' : { .... { 'keyn' : 'value' } ... } } } # A. nested dictionary
{('key1', 'key2', ...., 'keyn') ... | Without going into details (which are highly implementation-dependent anyway and may be invalidated by the next genius to come along and tweak the dictionary implementation):
* For memory overhead: Each object has some overhead (e.g. refcount and type; an empty object is 8 bytes and an empty tuple is 28 bytes), but ha... |
[python]: use re to find consecutively repeated chars | 7,147,796 | 7 | 2011-08-22T12:57:00Z | 7,147,979 | 7 | 2011-08-22T13:11:10Z | [
"python",
"regex"
] | I want to find all the consecutively repeated char-block in a string.
Code goes below:
```
s = r'http://www.google.com/search=ooo-jjj'
```
then what I want to find is, 'www', 'ooo' and 'jjj'.
I tried to do it by this:
```
m = re.search(r'(\w)\1\1', s)
```
But it can't seem to work as I expect.
Any better idea?
PS... | `((\w)\2{2,})` matches 3 or more consecutive characters:
```
In [71]: import re
In [72]: s = r'http://www.google.com/search=ooo-jjjj'
In [73]: re.findall(r'((\w)\2{2,})', s)
Out[73]: [('www', 'w'), ('ooo', 'o'), ('jjjj', 'j')]
In [78]: [match[0] for match in re.findall(r'((\w)\2{2,})', s)]
Out[78]: ['www', 'ooo', 'jj... |
Subclass dict: UserDict, dict or ABC? | 7,148,419 | 28 | 2011-08-22T13:44:29Z | 7,148,602 | 27 | 2011-08-22T13:58:51Z | [
"python",
"subclass"
] | What's the difference between `UserDict`, `dict` and `ABC` and which one is recommended? The docs seem to deprecate `UserDict`?
Also it seems UserDict's `update()` would use my `setitem` method whereas `dict` doesn't? Which methods are really essential to override given I want custom `setitem` and `getitem` function?
... | If you want a custom collection that actually holds the data, subclass *dict*. This is especially useful if you want to *extend* the interface (e.g., add methods).
None of the built-in methods will call your custom `__getitem__` / `__setitem__`, though. If you need total control over these, create a custom class that ... |
Regex to match letters, numbers and some specific characters? | 7,148,860 | 6 | 2011-08-22T14:17:23Z | 7,148,917 | 9 | 2011-08-22T14:22:27Z | [
"python",
"regex",
"django"
] | I'm trying to match a Django URL bit that can contain:
`_`, `%`, `&`, `+`, `0-9`, `a-z`, `A-Z`, (space)
How can I do it so it is picked up by Django's URL matcher, in form of a parameter?
```
(r'^(?P<chararg>\w+)/IT_NEEDS_TO_BE_HERE/(?P<intarg>\d+)', 'dest')
``` | I am not so sure about % char, but regex would be `[_%&+0-9a-zA-Z ]+` |
Send an authenticated POST request to tastypie | 7,149,866 | 4 | 2011-08-22T15:33:39Z | 7,152,067 | 9 | 2011-08-22T18:47:31Z | [
"python",
"django",
"curl",
"tastypie"
] | I am trying to send an ApiKey-autheticated POST request to a tastypie API
### my Model:
```
class Thing(models.Model):
name = models.TextField()
def __unicode__(self):
return u'%s'%self.name
```
### my ModelResource
```
class ThingResource(ModelResource):
class Meta:
queryset = Thing.ob... | Using the `-d` and `--data` with curl is mangling the POSTed data.
Including the `username` and `api_key` params in the GET should solve this, like so:
```
curl --dump-header - -H "Accept: application/json"\
-H "Content-Type: application/json" -X POST\
--data "{\"name\":\"arrrg\"}"\
"http://localhost... |
Python hash_ring not distributing uniformly, what are consistent hashing alternatives? | 7,150,159 | 3 | 2011-08-22T15:56:21Z | 7,151,807 | 7 | 2011-08-22T18:23:57Z | [
"python",
"hashtable",
"consistent-hashing"
] | I'm using [`hash_ring` package](http://pypi.python.org/pypi/hash_ring) for distributing objects among servers. I've assumed that distribution would be uniform, as it's based on MD5 hashes. Unfortunately it's not the case.
I'm using random keys which are generated using `uuid.uuid4()`. I've verified, that MD5 itself in... | the hash ring sacrifices the "eveness" of your md5 test code to maintain mappings when the number of entries changes. see <http://www.lexemetech.com/2007/11/consistent-hashing.html>. so the differences you see are not because of uuid4, or because of an error, but because the library uses a different algorithm from your... |
Where is module being imported from? | 7,150,998 | 14 | 2011-08-22T17:13:49Z | 7,151,129 | 13 | 2011-08-22T17:25:36Z | [
"python"
] | Assuming I have two Python modules and path\_b is in the import path:
```
# file: path_b/my_module.py
print "I was imported from ???"
#file: path_a/app.py
import my_module
```
Is it possible to see where the module is imported from? I want an output like "I was imported from path\_a/app.py", if I start app.py (becau... | Try this:
```
>>> import my_module
>>> my_module.__file__
'/Users/myUser/.virtualenvs/foobar/lib/python2.7/site-packages/my_module/__init__.pyc'
```
*Edit*
In that case write into the `__init__.py` file of your module:
```
print("%s: I was imported from %s" %(__name__, __file__))
``` |
Decoding html content and HTMLParser | 7,152,111 | 3 | 2011-08-22T18:51:22Z | 7,152,455 | 9 | 2011-08-22T19:21:30Z | [
"python"
] | I'm creating a sub-class based on 'HTMLParser' to pull out html content. Whenever I have character refs such as
```
' ' '&' '–' '…'
```
I'd like to replace them with their English counterparts of
```
' ' (space), '&', '-', '...', and so on.
```
What's the best way to convert some of the simple... | Your question has two parts. The easy part is decoding the HTML entities. The easiest way to do that is to grab this undocumented but long-stable method from the `HTMLParser` module:
```
>>> HTMLParser.HTMLParser().unescape('a < é – …')
u'a < é â â¦'
```
The second part, converting Unicode ... |
python __str__ for an object | 7,152,312 | 15 | 2011-08-22T19:08:46Z | 7,152,355 | 14 | 2011-08-22T19:13:21Z | [
"python"
] | While trying to figure out how BeautifulSoup works, I incidentally learnt the `__str__` method (I'm new to python). So if I did not misperceived then the `__str__` method helps to shape how the class will be represented if printed out. For instance:
```
class Foo:
def __str__(self):
return "bar"
>>> x = F... | You need to subclass the item you're pretty-printing.
```
from itertools import chain
class PrintableList(list): # for a list of dicts
def __str__(self):
return '. '.join(' '.join(str(x) for x in
chain.from_iterable(zip((item[0], 'is', 'and'), item[1])))
for item in (item.items... |
using python subprocess call to invoke python script | 7,152,340 | 9 | 2011-08-22T19:12:06Z | 22,258,715 | 8 | 2014-03-07T19:12:06Z | [
"python",
"subprocess"
] | I have a python script that needs to invoke another python script in the same directory.
I did this:
```
from subprocess import call
call('somescript.py')
```
I get the following error
```
call('somescript.py')
File "/usr/lib/python2.6/subprocess.py", line 480, in call
return Popen(*popenargs, **... | If 'somescript.py' isn't something you could normally execute directly from the command line (I.E. `$: somescript.py` works), then you can't call it directly using call.
Remember that the way Popen works is that the first argument is the program that it executes, and the rest are the arguments passed to that program. ... |
Python: if not val, vs if val is None | 7,152,441 | 16 | 2011-08-22T19:20:25Z | 7,152,491 | 13 | 2011-08-22T19:24:42Z | [
"python",
"comparison",
"boolean",
"readability"
] | I've always coded in the style of `if not value`, however, a few guides have brought to my attention that while this style works, it seems to have 2 potential problems:
1. It's not completely readable; `if value is None` is surely more understandable.
2. This can have implications later (and cause subtle bugs), since ... | No. If you want to run code when the value is false but isn't `None`, this would fail horribly.
Use `is None` if you're checking for identity with the `None` object. Use `not value` if you just want the value to be False. |
Making a python user-defined class sortable, hashable | 7,152,497 | 31 | 2011-08-22T19:25:06Z | 7,152,650 | 7 | 2011-08-22T19:38:18Z | [
"python",
"class",
"sorting",
"hash",
"magic-methods"
] | What methods need to be overridden/implemented when making user-defined classes sortable and/or hashable in python?
What are the gotchas to watch out for?
I type `dir({})` into my interpreter to get a list of methods on built-in dicts. Of those, I assume I need to some implement some subset of
```
['__cmp__', '__eq_... | There isn't any difference between Python 2 and 3.
**For sortability:**
You should define comparision methods. This makes your items sortable. Generally, you shouldn't prefer `__cmp__()`.
I usually use functools.total\_ordering decorator.
> functools.total\_ordering(cls) Given a class defining one or more rich
> co... |
Making a python user-defined class sortable, hashable | 7,152,497 | 31 | 2011-08-22T19:25:06Z | 7,152,796 | 37 | 2011-08-22T19:50:51Z | [
"python",
"class",
"sorting",
"hash",
"magic-methods"
] | What methods need to be overridden/implemented when making user-defined classes sortable and/or hashable in python?
What are the gotchas to watch out for?
I type `dir({})` into my interpreter to get a list of methods on built-in dicts. Of those, I assume I need to some implement some subset of
```
['__cmp__', '__eq_... | I almost posted this as a comment to the other answers but it's really an answer in and of itself.
To make your items sortable, they only need to implement `__lt__`. That's the only method used by the built in sort.
The other comparisons or `functools.total_ordering` are only needed if you actually want to use the co... |
Methods which return values vs methods which directly set attributes in Python | 7,152,617 | 3 | 2011-08-22T19:36:31Z | 7,152,685 | 8 | 2011-08-22T19:41:02Z | [
"python",
"oop",
"coding-style"
] | Which of the following classes would demonstrate the best way to set an instance attribute? Should they be used interchangeably based on the situation?
```
class Eggs(object):
def __init__(self):
self.load_spam()
def load_spam(self):
# Lots of code here
self.spam = 5
```
or
```
clas... | I would prefer the second method.
Here's why:
Procedures with side effects tend to introduce temporal coupling. Simply put, changing the order in which you execute these procedures might break your code. Returning values and passing them to other methods in need of them makes inter-method communication explicit and th... |
How to redirect 'print' output to a file using python? | 7,152,762 | 30 | 2011-08-22T19:47:26Z | 7,152,869 | 19 | 2011-08-22T19:56:33Z | [
"python"
] | I want to redirect the print to a .txt file using python. I have a 'for' loop, which will 'print' the output for each of my .bam file; while I want to redirect ALL these output to one file. So I tried to put
```
f = open('output.txt','w'); sys.stdout = f
```
at the beginning of my script. However I get nothing in th... | You can redirect print with the `>>` operator.
```
f = open(filename,'w')
print >>f, 'whatever'
```
In most cases, you're better off just writing to the file normally.
```
f.write('whatever')
```
or, if you have several items you want to write with spaces between, like `print`:
```
f.write(' '.join(('whatever', st... |
How to redirect 'print' output to a file using python? | 7,152,762 | 30 | 2011-08-22T19:47:26Z | 7,152,903 | 54 | 2011-08-22T20:00:19Z | [
"python"
] | I want to redirect the print to a .txt file using python. I have a 'for' loop, which will 'print' the output for each of my .bam file; while I want to redirect ALL these output to one file. So I tried to put
```
f = open('output.txt','w'); sys.stdout = f
```
at the beginning of my script. However I get nothing in th... | The most obvious way to do this would be to print to a file object:
```
f = open('out.txt', 'w')
print >> f, 'Filename:', filename # or f.write('...\n')
f.close()
```
However, redirecting stdout also works for me. It is probably fine for a one-off script such as this:
```
import sys
orig_stdout = sys.stdout
f = fi... |
How to redirect 'print' output to a file using python? | 7,152,762 | 30 | 2011-08-22T19:47:26Z | 31,138,047 | 8 | 2015-06-30T12:15:25Z | [
"python"
] | I want to redirect the print to a .txt file using python. I have a 'for' loop, which will 'print' the output for each of my .bam file; while I want to redirect ALL these output to one file. So I tried to put
```
f = open('output.txt','w'); sys.stdout = f
```
at the beginning of my script. However I get nothing in th... | This works perfectly:
```
import sys
sys.stdout=open("test.txt","w")
print ("hello")
sys.stdout.close()
```
Now the hello will be written to the test.txt file. Make sure to close the `stdout` with a `close`, without it the content will not be save in the file |
How can I un-shorten a URL using python? | 7,153,096 | 4 | 2011-08-22T20:17:50Z | 7,153,185 | 14 | 2011-08-22T20:25:44Z | [
"python",
"curl",
"youtube",
"hyperlink",
"urllib"
] | I have seen this thread already - [How can I unshorten a URL using python?](http://stackoverflow.com/questions/4201062/how-can-i-unshorten-a-url-using-python)
My issue with the resolved answer (that is using the unshort.me API) is that I am focusing on unshortening youtube links. Since unshort.me is used readily, this... | Use the best rated answer (not the accepted answer) in that question:
```
# This is for Py2k. For Py3k, use http.client and urllib.parse instead, and
# use // instead of / for the division
import httplib
import urlparse
def unshorten_url(url):
parsed = urlparse.urlparse(url)
h = httplib.HTTPConnection(parsed... |
dict.get() method returns a pointer | 7,153,893 | 9 | 2011-08-22T21:35:05Z | 7,153,919 | 16 | 2011-08-22T21:38:15Z | [
"python",
"dictionary",
"pass-by-reference"
] | Let's say I have this code:
```
my_dict = {}
default_value = {'surname': '', 'age': 0}
# get info about john, or a default dict
item = my_dict.get('john', default_value)
# edit the data
item[surname] = 'smith'
item[age] = 68
my_dict['john'] = item
```
The problem becomes clear, if we now check the value of default... | ```
item = my_dict.get('john', default_value.copy())
```
You're *always* passing a reference in Python.
This doesn't matter for immutable objects like `str`, `int`, `tuple`, etc. since you can't change them, only point a name at a different object, but it does for mutable objects like `list`, `set`, and `dict`. You n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.