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 |
|---|---|---|---|---|---|---|---|---|---|
Reading Space separated input in python | 7,637,957 | 5 | 2011-10-03T16:39:36Z | 7,637,999 | 16 | 2011-10-03T16:42:22Z | [
"python",
"input"
] | Here is the Input Specification
The program has to read t lines of inputs. Each line consist of 2 space separated values first one is the name and second is the age. An Example of Input
```
Mike 18
Kevin 35
Angel 56
```
How to read this kind of input in python? If i use raw\_input(), both name and age are read in t... | ```
the_string = raw_input()
name, age = the_string.split()
``` |
Python TK with MVC pattern | 7,638,139 | 9 | 2011-10-03T16:54:21Z | 17,236,698 | 10 | 2013-06-21T13:38:19Z | [
"python",
"model-view-controller",
"tk"
] | I need a basic example where MVC pattern is used with Python TK. I have made a Python TK code , however I would like to transform it into an MVC pattern. | I know this is quite old but I was able to find some decent examples using the MVC pattern with both Tk and wxPython, hopefully they provide some help for anyone stumbling upon this question.
wxPython: <http://wiki.wxpython.org/ModelViewController>
Tk: <http://tkinter.unpythonic.net/wiki/ToyMVC> |
Execute Python Script as Root (seteuid vs c-wrapper) | 7,639,141 | 12 | 2011-10-03T18:33:23Z | 7,639,535 | 13 | 2011-10-03T19:12:35Z | [
"python",
"c",
"django",
"freebsd"
] | I have a quick one off task in a python script that I'd like to call from Django (www user), that's going to need to root privileges.
At first I thought I would could use Python's os.seteuid() and set the setuid bit on the script, but then I realized that I would have to set the setuid bit on Python itself, which I as... | sudo does not require setuid bit on Python. You can enable sudo for one command only, no arguments:
```
www ALL=(ALL) NOPASSWD: /root/bin/reload-stuff.py ""
```
This would be secure if your script does not take any arguments, cannot be overridden by www user, and sudo does "env\_reset" (the default i... |
Webapp2 for Authentication and Login | 7,641,110 | 26 | 2011-10-03T21:55:00Z | 7,689,555 | 18 | 2011-10-07T15:38:31Z | [
"python",
"google-app-engine",
"webapp2"
] | I would like to roll my own login system for my python Google App Engine application (rather than using Google's [users api](http://code.google.com/appengine/docs/python/users/)).
I am using webapp2, and I noticed that there is a [webapp2\_extras.auth](http://webapp-improved.appspot.com/api/webapp2_extras/auth.html) m... | I found this **example code**, which covers:
<http://code.google.com/p/webapp-improved/issues/detail?id=20>
* It just covers the basics. Creating a user, login, logout and a decorator for protecting certain handlers.
It also makes sense to **search the webapp2 google group for 'auth'**:
<https://groups.google.com/f... |
Webapp2 for Authentication and Login | 7,641,110 | 26 | 2011-10-03T21:55:00Z | 15,321,401 | 11 | 2013-03-10T10:49:19Z | [
"python",
"google-app-engine",
"webapp2"
] | I would like to roll my own login system for my python Google App Engine application (rather than using Google's [users api](http://code.google.com/appengine/docs/python/users/)).
I am using webapp2, and I noticed that there is a [webapp2\_extras.auth](http://webapp-improved.appspot.com/api/webapp2_extras/auth.html) m... | You can check this blog post: [User authentication with webapp2 on Google App Engine](http://blog.abahgat.com/2013/01/07/user-authentication-with-webapp2-on-google-app-engine/).
It describes the steps you need to take in order to build your own authentication layer by leverage functionalities already included in webap... |
Fastest way to store large files in Python | 7,641,592 | 7 | 2011-10-03T22:55:10Z | 7,641,643 | 7 | 2011-10-03T23:02:10Z | [
"python",
"compression",
"pickle"
] | I [recently asked a question](http://stackoverflow.com/questions/7626848/maximum-python-object-which-can-be-passed-to-write) regarding how to save large python objects to file. I had previously run into problems converting massive Python dictionaries into string and writing them to file via `write()`. Now I am using pi... | You can compress the data with [bzip2](http://docs.python.org/library/bz2.html):
```
from __future__ import with_statement # Only for Python 2.5
import bz2,json,contextlib
hugeData = {'key': {'x': 1, 'y':2}}
with contextlib.closing(bz2.BZ2File('data.json.bz2', 'wb')) as f:
json.dump(hugeData, f)
```
Load it like t... |
Elegant way to remove contiguous repeated elements in a list? | 7,641,955 | 4 | 2011-10-03T23:54:54Z | 7,641,976 | 8 | 2011-10-03T23:58:54Z | [
"python",
"list",
"idioms",
"python-2.x"
] | I'm looking for a clean, Pythonic, way to eliminate from the following list:
```
li = [0, 1, 2, 3, 3, 4, 3, 2, 2, 2, 1, 0, 0]
```
all **contiguous repeated elements** (runs longer than one number) so as to obtain:
```
re = [0, 1, 2, 4, 3, 1]
```
but although I have working code, it feels un-Pythonic and I am quite ... | Here is a version based on Karl's which doesn't requires copies of the list (`tmp`, the slices, and the zipped list). `izip` is significantly faster than (Python 2) `zip` for large lists. `chain` is slightly slower than slicing but doesn't require a `tmp` object or copies of the list. `islice` plus making a `tmp` is a ... |
Is there a way to implement methods like __len__ or __eq__ as classmethods? | 7,642,434 | 17 | 2011-10-04T01:32:46Z | 7,642,535 | 19 | 2011-10-04T01:52:04Z | [
"python",
"class"
] | It is pretty easy to implement `__len__(self)` method in Python so that it handles `len(inst)` calls like this one:
```
class A(object):
def __len__(self):
return 7
a = A()
len(a) # gives us 7
```
And there are plenty of alike methods you can define (`__eq__`, `__str__`, `__repr__` etc.).
I know that Python c... | What you're looking for is called a "metaclass"... just like `a` is an instance of class `A`, `A` is an instance of class as well, referred to as a metaclass. By default, Python classes are instances of the `type` class (the only exception is under Python 2, which has some legacy "old style" classes, which are those wh... |
Modify the width of a tab in a format string | 7,643,579 | 6 | 2011-10-04T05:19:29Z | 7,644,193 | 11 | 2011-10-04T06:49:08Z | [
"python"
] | Is it possible to redefine the space width of a tab when printing a `\t` character in python? | Try `pydoc string.expandtabs`, I think it will do what you want. |
Atomic file replacement in Python | 7,645,338 | 6 | 2011-10-04T08:47:46Z | 7,645,393 | 10 | 2011-10-04T08:53:32Z | [
"python",
"filesystems",
"rename",
"atomic",
"fwrite"
] | What's the recommended way to replace a file atomically in Python?
i.e. if the Python script is interrupted, there is a power outage etc. files do not have a high probability of ending up in an inconsistent state (half written to the disk).
A solution for Linux/UNIX platforms is preferred.
(I know getting 100% atomi... | Create a new file and os.rename() it over the existing file. This is atomic on [most platforms](http://www.weirdnet.nl/apple/rename.html) under [most conditions](http://linux.die.net/man/2/rename). |
sqlalchemy exists for query | 7,646,173 | 18 | 2011-10-04T10:00:52Z | 7,647,500 | 9 | 2011-10-04T11:54:17Z | [
"python",
"sqlalchemy",
"exists",
"flask-sqlalchemy"
] | How to check that data in query is exists?
For example:
```
users_query = User.query.filter_by(email='x@x.com')
```
How I can check that users with that email exists?
Now i check this with
```
users_query.count()
```
but want check it with **exists**.
Thanks! | There is no way that I know of to do this using the orm query api. But you can drop to a level lower and use [exists](http://docs.sqlalchemy.org/en/rel_0_9/core/selectable.html#sqlalchemy.sql.expression.exists) from sqlalchemy.sql.expression:
```
from sqlalchemy.sql.expression import select, exists
users_exists_selec... |
sqlalchemy exists for query | 7,646,173 | 18 | 2011-10-04T10:00:52Z | 13,336,408 | 45 | 2012-11-11T23:01:44Z | [
"python",
"sqlalchemy",
"exists",
"flask-sqlalchemy"
] | How to check that data in query is exists?
For example:
```
users_query = User.query.filter_by(email='x@x.com')
```
How I can check that users with that email exists?
Now i check this with
```
users_query.count()
```
but want check it with **exists**.
Thanks! | The following solution is a bit simpler:
```
from sqlalchemy.sql import exists
print session.query(exists().where(User.email == '...')).scalar()
``` |
Is this an appropriate use of python's built-in hash function? | 7,646,520 | 10 | 2011-10-04T10:31:02Z | 7,646,681 | 23 | 2011-10-04T10:45:07Z | [
"python",
"hash",
"hash-collision"
] | I need to compare large chunks of data for equality, and I need to compare many per second, *fast*. Every object is guaranteed to be the same size, and it is possible/likely they may only be slightly different (in unknown positions).
I have seen, from the interactive session below, using `==` operator for byte strings... | Python's hash function is designed for speed, and maps into a 64-bit space. Due to the [birthday paradox](http://en.wikipedia.org/wiki/Birthday_problem), this means you'll likely get a collision at about 5 billion entries (probably way earlier, since the hash function is not cryptographical). Also, the precise definiti... |
Writing response body with BaseHTTPRequestHandler | 7,646,657 | 16 | 2011-10-04T10:43:04Z | 7,647,695 | 19 | 2011-10-04T12:12:36Z | [
"python",
"basehttprequesthandler"
] | I'm playing a little with Python 3.2.2 and want to write a simple web server to access some data remotely. This data will be generated by Python so I don't want to use the SimpleHTTPRequestHandler as it's a file server, but a handler of my own.
I copied some example from the internet but I'm stuck because **the respon... | In Python3 string is a different type than that in Python 2.x. Cast it into bytes using either
```
bytes(s, "utf-8")
```
or
```
s.encode("utf-8")
``` |
How I can set gap in Vertical BoxSizer? | 7,647,760 | 6 | 2011-10-04T12:17:23Z | 7,650,775 | 9 | 2011-10-04T16:03:21Z | [
"python",
"user-interface",
"wxpython",
"wxwidgets"
] | How can I set gap in Vertical BoxSizer? What's in the Vertival BoxSizer the similar or alternative method of `SetVGap` (which sets the vertical gap (in pixels) between the cells in the sizer) in GridSizer? | There are several ways to add blank space in a sizer.
```
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(widget, proportion=0, style=wx.ALL, border=5)
```
The code above will add the widget with a 5 pixel border on all sides of it. If you want to put some space between two widgets, you can do one of the following:
```
s... |
map lambda x,y with a constant x | 7,647,792 | 4 | 2011-10-04T12:21:43Z | 7,647,837 | 15 | 2011-10-04T12:24:48Z | [
"python",
"map",
"lambda"
] | What would be an elegant way to `map` a two parameter `lambda` function to a list of values where the first parameter is constant and the second is taken from a `list`?
**Example:**
```
lambda x,y: x+y
x='a'
y=['2','4','8','16']
```
expected result:
```
['a2','a4','a8','a16']
```
Notes:
* This is just an example,... | You can use `itertools.starmap`
```
a = itertools.starmap(lambda x,y: x+y, zip(itertools.repeat(x), y))
a = list(a)
```
and you get your desired output.
BTW, both `itertools.imap` and Python3's `map` will accept the following:
```
itertools.imap(lambda x,y: x+y, itertools.repeat(x), y)
```
The default Python2's `m... |
map lambda x,y with a constant x | 7,647,792 | 4 | 2011-10-04T12:21:43Z | 7,647,852 | 10 | 2011-10-04T12:26:36Z | [
"python",
"map",
"lambda"
] | What would be an elegant way to `map` a two parameter `lambda` function to a list of values where the first parameter is constant and the second is taken from a `list`?
**Example:**
```
lambda x,y: x+y
x='a'
y=['2','4','8','16']
```
expected result:
```
['a2','a4','a8','a16']
```
Notes:
* This is just an example,... | **Python 2.x**
```
from itertools import repeat
map(lambda (x, y): x + y, zip(repeat(x), y))
```
**Python 3.x**
```
map(lambda xy: ''.join(xy), zip(repeat(x), y))
``` |
map lambda x,y with a constant x | 7,647,792 | 4 | 2011-10-04T12:21:43Z | 7,647,897 | 8 | 2011-10-04T12:30:44Z | [
"python",
"map",
"lambda"
] | What would be an elegant way to `map` a two parameter `lambda` function to a list of values where the first parameter is constant and the second is taken from a `list`?
**Example:**
```
lambda x,y: x+y
x='a'
y=['2','4','8','16']
```
expected result:
```
['a2','a4','a8','a16']
```
Notes:
* This is just an example,... | Also you could use closure for this
```
x='a'
f = lambda y: x+y
map(f, ['1', '2', '3', '4', '5'])
>>> ['a1', 'a2', 'a3', 'a4', 'a5']
``` |
Pygame water ripple effect | 7,648,072 | 31 | 2011-10-04T12:43:56Z | 7,910,136 | 7 | 2011-10-26T23:29:38Z | [
"python",
"opengl",
"image-processing",
"pygame",
"effect"
] | I have Googled for it but there are no ready scripts - as opposed to the same effect on Flash. I have checked the algorithm on [The Water Effect Explained](http://www.gamedev.net/page/resources/_/technical/graphics-programming-and-theory/the-water-effect-explained-r915) and also tested an implementation of the [Perlin ... | After doing homework (a.k.a. research) and trying to directly convert the Java code reference posted on the question into Python, and having a very, very sad experience while trying to have Python/Numpy update a humongous array of pixel colors based on their positions for the rippling of the ripple effect (sorry, my fi... |
When is a python object's hash computed and why is the hash of -1 different? | 7,648,129 | 17 | 2011-10-04T12:48:38Z | 7,648,538 | 12 | 2011-10-04T13:19:32Z | [
"python",
"hash"
] | Following on from [this](http://stackoverflow.com/questions/7646520/is-this-an-appropriate-use-of-pythons-built-in-hash-function) question, I'm interested to know when is a python object's hash *computed*?
1. At an instance's `__init__` time,
2. The first time `__hash__()` is called,
3. Every time `__hash__()` is call... | The hash is generally computed each time it's used, as you can quite easily check yourself (see below).
Of course, any particular object is free to cache its hash. For example, CPython strings do this, but tuples don't (see e.g. [this rejected bug report](http://bugs.python.org/issue1462796) for reasons).
The hash val... |
pip install PIL -E TICKETS-1 - No JPEG/PNG support | 7,648,200 | 25 | 2011-10-04T12:53:26Z | 7,648,348 | 8 | 2011-10-04T13:04:50Z | [
"python",
"python-imaging-library",
"virtualenv"
] | I'm using Ubuntu and VitualEnv for my Django project.
I have PIL library installed using Synaptic Package Manager and it is working fine. But when I create an VitrualEnv and try to install PIL using pip it installes but I get this strange behaviour:
```
----------------------------------------------------------------... | This [thread on ubuntu forums](http://ubuntuforums.org/showthread.php?t=1751455) covers this topic. |
Python multiprocessing - How to release memory when a process is done? | 7,648,967 | 12 | 2011-10-04T13:52:11Z | 7,650,252 | 13 | 2011-10-04T15:23:43Z | [
"python",
"memory",
"multiprocessing"
] | I encountered a weird problem while using python multiprocessing library.
My code is sketched below: I spawn a process for each "symbol, date" tuple. I combine the results afterwards.
I expect that when a process has done computing for a "symbol, date" tuple, it should release its memory? apparently that's not the ca... | Did you try to close pool by using [`pool.close`](http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.close) and then wait for process to finish by [`pool.join`](http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.join), because if pare... |
django serialize queryset.values() into json | 7,650,448 | 12 | 2011-10-04T15:39:08Z | 7,650,763 | 12 | 2011-10-04T16:02:14Z | [
"python",
"django",
"django-models"
] | I have a model that has many fields, however for this problem I only need 3 of those fields. When I try to serialize a `.values` set I get an exception
```
queryset = myModel.objects.filter(foo_icontains=bar).values('f1', 'f2', 'f3')
serialized_q = serializers.serialize('json', queryset, ensure_ascii=False)
``` | Look at this [SO question](http://stackoverflow.com/questions/6601174/converting-a-django-valuesqueryset-to-a-json-object/6601250#6601250) for example
```
objectQuerySet = ConventionCard.objects.filter(ownerUser = user)
data = serializers.serialize('json', list(objectQuerySet), fields=('fileName','id'))
```
Django se... |
django serialize queryset.values() into json | 7,650,448 | 12 | 2011-10-04T15:39:08Z | 31,994,176 | 11 | 2015-08-13T16:52:43Z | [
"python",
"django",
"django-models"
] | I have a model that has many fields, however for this problem I only need 3 of those fields. When I try to serialize a `.values` set I get an exception
```
queryset = myModel.objects.filter(foo_icontains=bar).values('f1', 'f2', 'f3')
serialized_q = serializers.serialize('json', queryset, ensure_ascii=False)
``` | As other people have said, Django's [serializers](https://docs.djangoproject.com/en/1.8/topics/serialization/) can't handle a ValuesQuerySet. However, you can serialize by using a standard `json.dumps()` and transforming your ValuesQuerySet to a list by using `list()`. If your set includes Django fields such as Decimal... |
Can't install PyDev for Eclipse Indigo | 7,651,072 | 6 | 2011-10-04T16:27:10Z | 9,346,735 | 11 | 2012-02-19T04:34:26Z | [
"python",
"eclipse",
"eclipse-plugin",
"installation",
"pydev"
] | I have problem with installation of PyDev in Eclipse Indigo. I used Help -> Install new software -> and <http://pydev.org/updates> repository. I try it for 3 days yet but it is still not work. First, I got error: unabled to read repository.

Today, re... | use <http://update-production-pydev.s3.amazonaws.com/pydev/updates/site.xml> |
Python: Use spaces in a function name? | 7,651,733 | 5 | 2011-10-04T17:25:39Z | 7,651,810 | 45 | 2011-10-04T17:33:11Z | [
"python",
"function"
] | I am writing a python scripts to call a function.
Normally function are called:
```
def myCall():
print "Hello World"
```
But I would like to name/use the function as:
```
def my Call():
print "I did it!"
```
I knew the world will start thinking why the programmer name the function this ways. Just replace ... | Do you need to call it in the conventional way?
Here's a function name with spaces (and punctuation!)
```
>>> def _func():
print "YOOOO"
>>> globals()['Da func name!!1'] = _func
>>> globals()['Da func name!!1']()
YOOOO
``` |
Is it possible to use Python based Unit Test frameworks and runners, to test C Code | 7,652,193 | 12 | 2011-10-04T18:08:43Z | 7,652,224 | 13 | 2011-10-04T18:11:51Z | [
"python",
"c",
"unit-testing"
] | Python based Unit test Frameworks like "nose" have a lot of rich features, i wonder if we can leverage them to test C Code. | Of course you can.... but you'll have to write a binding to call your C code in python (with [ctypes](http://docs.python.org/library/ctypes.html) for example), and write the tests in python (this is really possible and an easy way to do smart tests)
**Example :**
* Write a dummy C library.
*foolib.c*
```
int my_sum... |
Where can I find and install the dependencies for pygame? | 7,652,385 | 12 | 2011-10-04T18:26:59Z | 7,652,535 | 7 | 2011-10-04T18:38:53Z | [
"python",
"linux",
"debian",
"pygame"
] | I am relatively new to linux and am trying to install the pygame dev environment for python. When I run the setup.py it says that I need to install the following dependencies, one of which I found and installed (SDL). However, the others have been more elusive.
```
Hunting dependencies...
sh: smpeg-config: command not... | For debian, there is a pre-built package available. See [here](http://packages.qa.debian.org/p/pygame.html). You should be able to install it with `apt-get` or something similar. |
Where can I find and install the dependencies for pygame? | 7,652,385 | 12 | 2011-10-04T18:26:59Z | 15,368,766 | 12 | 2013-03-12T18:04:57Z | [
"python",
"linux",
"debian",
"pygame"
] | I am relatively new to linux and am trying to install the pygame dev environment for python. When I run the setup.py it says that I need to install the following dependencies, one of which I found and installed (SDL). However, the others have been more elusive.
```
Hunting dependencies...
sh: smpeg-config: command not... | `$ sudo apt-get install python-dev libsdl-image1.2-dev libsdl-mixer1.2-dev libsdl-ttf2.0-dev libsdl1.2-dev libsmpeg-dev python-numpy subversion libportmidi-dev ffmpeg libswscale-dev libavformat-dev libavcodec-dev` |
Where can I find and install the dependencies for pygame? | 7,652,385 | 12 | 2011-10-04T18:26:59Z | 16,754,335 | 9 | 2013-05-25T22:04:31Z | [
"python",
"linux",
"debian",
"pygame"
] | I am relatively new to linux and am trying to install the pygame dev environment for python. When I run the setup.py it says that I need to install the following dependencies, one of which I found and installed (SDL). However, the others have been more elusive.
```
Hunting dependencies...
sh: smpeg-config: command not... | Behold, one of the most useful tools on debian-based dsitros:
```
apt-get build-dep python-pygame
```
Installs all the dependences required to build pygame :)
On Fedora:
```
yum-builddep package_name
``` |
Python: escaping issue with ujson | 7,652,759 | 2 | 2011-10-04T18:59:39Z | 7,652,793 | 7 | 2011-10-04T19:02:14Z | [
"python",
"json"
] | I am using ujson to convert dictionary to json.
when I run the following line:
```
ujson.dumps({'key':'val\1'})
```
I get the following result:
```
[{"key": "val\\1"}]
```
while I expect/want it to be:
```
[{"key": "val\1"}]
```
any idea? | There is no problem, that's what `repr` looks like for this value. It *is* `\1`. |
Wait until a certain process (knowing the "pid") end | 7,653,178 | 9 | 2011-10-04T19:41:07Z | 7,654,102 | 7 | 2011-10-04T21:13:54Z | [
"python",
"linux",
"process",
"wait",
"pid"
] | I have this:
```
def get_process():
pids = []
process = None
for i in os.listdir('/proc'):
if i.isdigit():
pids.append(i)
for pid in pids:
proc = open(os.path.join('/proc', pid, 'cmdline'), 'r').readline()
if proc == "Something":
process = pid
retur... | I'm not really a Python programmer, but apparently Python does have [`os.waitpid()`](http://docs.python.org/release/2.5.2/lib/os-process.html#l2h-2774). That should consume less CPU time and provide a much faster response than, say, trying to kill the process at quarter-second intervals.
---
**Addendum:** As Niko poi... |
How to turn a list into nested dict in Python | 7,653,726 | 6 | 2011-10-04T20:36:26Z | 7,654,004 | 14 | 2011-10-04T21:04:11Z | [
"python",
"list",
"dictionary",
"nested"
] | Need to turn x:
```
X = [['A', 'B', 'C'], ['A', 'B', 'D']]
```
Into Y:
```
Y = {'A': {'B': {'C','D'}}}
```
More specifically, I need to create a tree of folders and files from a list of absolute paths, which looks like this:
```
paths = ['xyz/123/file.txt', 'abc/456/otherfile.txt']
```
where, each path is `split(... | ```
X = [['A', 'B', 'C'], ['A', 'B', 'D'],['W','X'],['W','Y','Z']]
d = {}
for path in X:
current_level = d
for part in path:
if part not in current_level:
current_level[part] = {}
current_level = current_level[part]
```
This leaves us with d containing `{'A': {'B': {'C': {}, 'D': {... |
indent python file (with pydev) in eclipse | 7,654,267 | 13 | 2011-10-04T21:29:09Z | 7,654,311 | 16 | 2011-10-04T21:33:32Z | [
"python",
"eclipse",
"pydev",
"code-formatting",
"indentation"
] | I'm a newbie in eclipse. I want to indent all the lines of my code and formatting the open file by pressing a shortcut or something like that...
I know the CTRL+SHIFT+F (as it actually doesn't work in pydev!!)
I've been searching for hours with no success. Is there any way to do that in eclipse. kind of like CTRL+K,D i... | I ... don't think this question makes sense. Indentation is syntax in Python. It doesn't make sense to have your IDE auto-indent your code. If it's not indented properly already, it doesn't work, and the IDE can't know where your indentation blocks begin and end. Take, for example:
```
# Valid Code
for i in range(10):... |
indent python file (with pydev) in eclipse | 7,654,267 | 13 | 2011-10-04T21:29:09Z | 10,738,859 | 11 | 2012-05-24T13:53:12Z | [
"python",
"eclipse",
"pydev",
"code-formatting",
"indentation"
] | I'm a newbie in eclipse. I want to indent all the lines of my code and formatting the open file by pressing a shortcut or something like that...
I know the CTRL+SHIFT+F (as it actually doesn't work in pydev!!)
I've been searching for hours with no success. Is there any way to do that in eclipse. kind of like CTRL+K,D i... | Although auto-indentation is not a feature of PyDev because of the language design you should be able to indent with a simple tab. Just select the lines you want to indent and press Tab. If you want to unindent lines you have to press Shift+Tab.
Thats all. |
indent python file (with pydev) in eclipse | 7,654,267 | 13 | 2011-10-04T21:29:09Z | 10,854,068 | 15 | 2012-06-01T16:27:23Z | [
"python",
"eclipse",
"pydev",
"code-formatting",
"indentation"
] | I'm a newbie in eclipse. I want to indent all the lines of my code and formatting the open file by pressing a shortcut or something like that...
I know the CTRL+SHIFT+F (as it actually doesn't work in pydev!!)
I've been searching for hours with no success. Is there any way to do that in eclipse. kind of like CTRL+K,D i... | If you want to change from 2 space to 4 space indentation (for instance), use "Source->Convert space to tab" with 2 spaces, then "Soruce->Convert tab to space" with 4 spaces. |
Good way to organize all sub classes into a dictionary in python? | 7,654,272 | 3 | 2011-10-04T21:29:31Z | 7,654,340 | 7 | 2011-10-04T21:36:59Z | [
"python",
"regex"
] | I have a base class and several subclasses. Each sub class has an attribute called "regex" containing a string:
```
# module level dictionary
action_types = {}
class Action():
regex = '.*'
@classmethod
def register_action(cls):
action_types[cls.regex] = cls
class Sing(Action):
regex = r'^SI... | That's not how you want to do it.
```
class ActionRegistry(type):
registry = {}
def __init__(cls, name, bases, dic):
if 'regex' in dic:
cls.registry[dic['regex']] = cls
super(ActionRegistry, cls).__init__(name, bases, dic)
class Action(object):
__metaclass__ = ActionRegistry
class Sing(Action):
... |
parsing a fasta file using a generator ( python ) | 7,654,971 | 7 | 2011-10-04T22:57:06Z | 7,655,072 | 8 | 2011-10-04T23:09:50Z | [
"python",
"file",
"parsing",
"fasta"
] | I am trying to parse a large fasta file and I am encountering out of memory errors. Some suggestions to improve the data handling would be appreciated. Currently the program correctly prints out the names however partially through the file I get a MemoryError
Here is the generator
```
def readFastaEntry( fp ):
na... | Have you considered using [BioPython](http://biopython.org/wiki/Main_Page). They have a [sequence reader](http://biopython.org/wiki/SeqIO) that can read fasta files. And if you are interested in coding one yourself, you can take a look at [BioPython's code](https://github.com/biopython/biopython/blob/master/Bio/SeqIO/F... |
parsing a fasta file using a generator ( python ) | 7,654,971 | 7 | 2011-10-04T22:57:06Z | 7,659,724 | 7 | 2011-10-05T10:11:06Z | [
"python",
"file",
"parsing",
"fasta"
] | I am trying to parse a large fasta file and I am encountering out of memory errors. Some suggestions to improve the data handling would be appreciated. Currently the program correctly prints out the names however partially through the file I get a MemoryError
Here is the generator
```
def readFastaEntry( fp ):
na... | A pyparsing parser for this format is only a few lines long. See the annotations in the following code:
```
data = """>1 (PB2)
AATATATTCAATATGGAGAGAATAAAAGAACTAAGAGATCTAATGTCACAGTCTCGCACTCGCGAGATAC
TCACCAAAACCACTGTGGACCACATGGCCATAATCAAAAAGTACACATCAGGAAGGCAAGAGAAGAACCC
TGCACTCAGGATGAAGTGGATGATG
>2 (PB1)
AACCATTTGA... |
What is the Pythonic way to use private variables? | 7,655,895 | 5 | 2011-10-05T01:42:39Z | 7,655,906 | 8 | 2011-10-05T01:46:26Z | [
"python"
] | I recently posted [a question](http://stackoverflow.com/questions/7622159/python-newbie-questions-not-printing-correct-values) on stackoverflow and I got a resolution.
Some one suggested to me about the coding style and I haven't received further input. I have the following question with reference to the prior query.
... | Everything is `public` in Python, the `__` is a suggestion by convention that you shouldn't use that function as it is an implementation detail.
This is not enforced by the language or runtime in any way, these names are decorated in a semi-obfuscated way, but they are still `public` and still visible to all code that... |
place a 0 in front of numbers in a list if they are less than ten (in python) | 7,656,754 | 5 | 2011-10-05T04:38:49Z | 7,656,773 | 8 | 2011-10-05T04:42:25Z | [
"python",
"list"
] | Write a Python program that will ask the user to enter a string of lower-case
characters and then print its corresponding two-digit code. For example, if the
input is "home", the output should be "08151305".
Currently I have my code working to make a list of all the number, but I cannot
get it to add a 0 in front of t... | `output.append("%02d" % number)` should do it. This uses Python [string formatting operations](http://docs.python.org/library/stdtypes.html#string-formatting-operations) to do left zero padding. |
place a 0 in front of numbers in a list if they are less than ten (in python) | 7,656,754 | 5 | 2011-10-05T04:38:49Z | 7,656,820 | 8 | 2011-10-05T04:49:59Z | [
"python",
"list"
] | Write a Python program that will ask the user to enter a string of lower-case
characters and then print its corresponding two-digit code. For example, if the
input is "home", the output should be "08151305".
Currently I have my code working to make a list of all the number, but I cannot
get it to add a 0 in front of t... | Or, use the built in function designed to do this - [`zfill()`](http://docs.python.org/library/stdtypes.html):
```
def word ():
# could just use a str, no need for a list:
  output = ""
  input = raw_input("please enter a string of lowercase characters: ").strip()
  for character in input:
    ... |
Finding key from value in Python dictionary: | 7,657,457 | 7 | 2011-10-05T06:27:03Z | 7,657,712 | 18 | 2011-10-05T06:56:18Z | [
"python",
"dictionary",
"key"
] | Fairly new to Python, still struggling with so much information.
All the documentation I've seen about dictionaries explain various ways of getting a value via a key - but I'm looking for a pythonic way to do the opposite - get a key via a value.
I know I can loop through the keys and inspect their values until I fin... | There is no direct route. It's pretty easy with list comprehensions, though;
```
[k for k, v in d.iteritems() if v == desired_value]
```
If you need to do this occasionally and don't think it's worth while indexing it the other way as well, you could do something like:
```
class bidict(dict):
def key_with_value(... |
virtualenvwrapper.sh error showing at terminal startup | 7,658,075 | 10 | 2011-10-05T07:33:54Z | 13,331,129 | 14 | 2012-11-11T12:29:30Z | [
"python",
"linux"
] | As I'm starting to learn Python programming, I installed virtualenvwrapper via these commands:
```
# Install distribute: http://pypi.python.org/pypi/distribute
wget http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py
# Install pip http://pypi.python.org/pypi/pip
sudo easy_install pip
# I... | [According to this](https://bitbucket.org/dhellmann/virtualenvwrapper/issue/95/error-on-opening-shell), it seems to be an error with the APT package on Debian/Ubuntu/Mint.
I have installed virtualenvwrapper through APT first, then removed it and installed it via pip.
```
apt-get install virtualenvwrapper
apt-get remo... |
Python - Xlwt more than 256 columns | 7,658,513 | 8 | 2011-10-05T08:21:50Z | 7,659,452 | 12 | 2011-10-05T09:47:31Z | [
"python"
] | I am importing text files into excel using xlwt module. But it allows only 256 columns to be stored. Are there any ways to solve this problem? | `xlwt` supports creation of XLS files of the kind created by Excel 97-2003 and read by Excel 97 onwards. The file format is limited to 256 columns and 65536 rows. No amount of changing 256 to some other number in the `xlwt` source code will change that.
You have 3 options, in increasing order of complexity:
(1) as su... |
Finding index of the same elements in a list | 7,658,932 | 7 | 2011-10-05T09:05:03Z | 7,658,955 | 13 | 2011-10-05T09:07:27Z | [
"python"
] | Suppose I have to find each index of letter 'e' in the word "internet":
```
letter = 'e'
word = 'internet'
idx = word.index(letter)
```
But this code gives only the first index. How can I find the rest of them? | Try using [enumerate](http://docs.python.org/library/functions.html#enumerate) in a [list comprehension](http://www.python.org/dev/peps/pep-0202/):
```
[index for (index, letter) in enumerate(word) if letter == 'e']
``` |
How to write alter column name migrations with sqlalchemy-migrate? | 7,659,957 | 4 | 2011-10-05T10:31:45Z | 7,672,864 | 10 | 2011-10-06T10:10:11Z | [
"python",
"sqlite",
"postgresql",
"heroku",
"sqlalchemy-migrate"
] | I'm trying to alter a column name. First attempt was with this script:
```
meta = MetaData()
users = Table('users', meta,
Column('id', Integer, primary_key=True),
Column('name', String(50), unique=True),
Column('email', String(120), unique=True)
)
def upgrade(migrate_engine):
meta.bind = migrate_... | Turns out there's an even DRY:er solution to this than I had hoped for. Introspection! Like so:
```
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
users = Table('users', meta, autoload=True)
users.c.user_id.alter(name='id')
def downgrade(migrate_engine):
meta = MetaData(bind=migrate... |
getting rid of characters in an output in python | 7,659,986 | 2 | 2011-10-05T10:35:35Z | 7,660,013 | 8 | 2011-10-05T10:38:02Z | [
"python"
] | If someone writes 'james', I want my program to style their name as j\*a\*m\*e\*s
I thought it would be simple:
```
for letter in name:
print letter+' *',
```
but I don't know how to get rid of the last asterix at the end.
I had a friend show me in C though...so I understand the underlying concept, just not how to ... | There is an easier way in Python:
```
>>> '*'.join('james')
'j*a*m*e*s'
```
This makes use of the fact that in Python, strings are iterable. |
cmake finds wrong python libs | 7,660,001 | 13 | 2011-10-05T10:36:52Z | 9,810,796 | 10 | 2012-03-21T18:37:47Z | [
"python",
"osx",
"cmake"
] | I'm new to CMake and have trouble understanding some usage concepts.
I'm calling a python script from a c++ program:
```
#include <Python.h>
...
Py_Initialize();
PyRun_SimpleFile(...);
Py_Finalize();
```
The corresponding cmake entries in my cmake file are:
```
FIND_PACKAGE(PythonLibs REQUIRED)
...
TARGET_LINK_LIBR... | you can tell cmake where to find this PythonLibs by specifying the path to your python libraries like this:
```
cmake -DPYTHON_LIBRARIES=/Library/Frameworks/Python.framework/Versions/2.7/lib/libpython2.7.dylib .
```
this will then set the ${PYTHON\_LIBRARIES} inside cmake to the right path.
To find out which other p... |
cmake finds wrong python libs | 7,660,001 | 13 | 2011-10-05T10:36:52Z | 19,223,779 | 8 | 2013-10-07T11:33:10Z | [
"python",
"osx",
"cmake"
] | I'm new to CMake and have trouble understanding some usage concepts.
I'm calling a python script from a c++ program:
```
#include <Python.h>
...
Py_Initialize();
PyRun_SimpleFile(...);
Py_Finalize();
```
The corresponding cmake entries in my cmake file are:
```
FIND_PACKAGE(PythonLibs REQUIRED)
...
TARGET_LINK_LIBR... | The best way to solve the problem that the wrong version is found (for instance 3.0 instead of 2.7) is to specify the minimum version to find\_package (this will choose any version >= 2.7):
```
FIND_PACKAGE(PythonLibs 2.7 REQUIRED)
```
or to get the exact version:
```
FIND_PACKAGE(PythonLibs 2.7.5 EXACT REQUIRED)
``... |
What are the different options for social authentication on Appengine - how do they compare? | 7,660,059 | 6 | 2011-10-05T10:42:23Z | 7,662,946 | 11 | 2011-10-05T14:30:50Z | [
"python",
"google-app-engine",
"oauth",
"openid",
"facebook-authentication"
] | *[This question is intended as a means to both capture my findings and sanity check them - I'll put up my answer toute suite and see what other answers and comments appear.]*
I spent a little time trying to get my head around the different social authentication options for (python) Appengine. I was particularly confus... | In my research on this question I found that there are essentially three options:
1. Use Google's authentication mechanisms (including their federated login via OpenID)
* Pros:
+ You can easily check who is logged in via the Users service provided with Appengine
+ Google handles the security so you can b... |
python: split string after a character | 7,660,847 | 3 | 2011-10-05T11:52:03Z | 7,660,920 | 13 | 2011-10-05T11:57:58Z | [
"python",
"regex",
"string"
] | I have a string with two "-"
```
467.2-123-hdxdlfow
```
I want to remove everything after the second "-" so that I get "467.2-123". What is the best way to do this? | ```
before, sep, after = theString.rpartition("-")
```
This splits the str about the last occurrence of "-" and your answer would be the variable `before`. |
Print the first two rows of a csv file to a standard output | 7,661,540 | 3 | 2011-10-05T12:49:47Z | 7,661,570 | 11 | 2011-10-05T12:52:16Z | [
"python"
] | I would like to print (stdout) the first two lines of a csv file:
```
#!/usr/bin/env python
import csv
afile = open('<directory>/*.csv', 'r+')
csvReader1 = csv.reader(afile)
for row in csvReader1:
print row[0]
print row[1]
```
however, my output using this code print the first two columns.
Any suggestions? | You want to print a row, but your code asks to print the first and second members of each row
Since you want to print the whole row - you can simply print it, and in addition, only read the first two
```
#!/usr/bin/env python
import csv
afile = open('<directory>/*.csv', 'r+')
csvReader1 = csv.reader(afile)
for i in r... |
how to check if you are at the end of a list in python? | 7,662,383 | 3 | 2011-10-05T13:52:59Z | 7,662,423 | 7 | 2011-10-05T13:55:11Z | [
"python",
"list"
] | if have a list, say a=[1,2,3], and I want to see if a[4] is null, is there a way to do that? without using an exception or assertion. | [`len`](http://docs.python.org/library/functions.html#len) will tell you the length of the list. To quote the docs:
> len(s)
> Return the length (the number of items) of an object. The argument may be a sequence
> (string, tuple or list) or a mapping (dictionary).
Of course, if you want to get the final... |
How to split an array according to a condition in numpy? | 7,662,458 | 7 | 2011-10-05T13:57:26Z | 7,662,502 | 14 | 2011-10-05T14:00:30Z | [
"python",
"numpy"
] | For example, I have a `ndarray` that is:
```
a = np.array([1, 3, 5, 7, 2, 4, 6, 8])
```
Now I want to split `a` into two parts, one is all numbers <5 and the other is all >=5:
```
[array([1,3,2,4]), array([5,7,6,8])]
```
Certainly I can traverse `a` and create two new array. But I want to know does numpy provide so... | ```
import numpy as np
def split(arr, cond):
return [arr[cond], arr[~cond]]
a = np.array([1,3,5,7,2,4,6,8])
print split(a, a<5)
a = np.array([[1,2,3],[4,5,6],[7,8,9],[2,4,7]])
print split(a, a[:,0]<3)
```
This produces the following output:
```
[array([1, 3, 2, 4]), array([5, 7, 6, 8])]
[array([[1, 2, 3],
... |
Python: clockwise polar plot | 7,664,153 | 9 | 2011-10-05T15:54:56Z | 18,486,470 | 10 | 2013-08-28T11:21:58Z | [
"python",
"plot",
"matplotlib",
"transpose"
] | How can I make a clockwise plot? Somebody ask a similar question [here](http://stackoverflow.com/questions/2417794/how-to-make-the-angles-in-a-matplotlib-polar-plot-go-clockwise-with-0-at-the-top): [How to make the angles in a matplotlib polar plot go clockwise with 0° at the top?](http://stackoverflow.com/questions/24... | add these strings:
```
ax.set_theta_direction(-1)
ax.set_theta_offset(pi/2.0)
``` |
Python: clockwise polar plot | 7,664,153 | 9 | 2011-10-05T15:54:56Z | 26,193,607 | 7 | 2014-10-04T14:08:47Z | [
"python",
"plot",
"matplotlib",
"transpose"
] | How can I make a clockwise plot? Somebody ask a similar question [here](http://stackoverflow.com/questions/2417794/how-to-make-the-angles-in-a-matplotlib-polar-plot-go-clockwise-with-0-at-the-top): [How to make the angles in a matplotlib polar plot go clockwise with 0° at the top?](http://stackoverflow.com/questions/24... | `ax.set_theta_direction(-1)
ax.set_theta_direction('N')`
is slightly more comprehensible. |
python built-in function to do matrix reduction | 7,664,246 | 10 | 2011-10-05T16:00:44Z | 7,664,451 | 12 | 2011-10-05T16:18:25Z | [
"python",
"matrix",
"scipy"
] | Does python have a built-in function that converts a matrix into row echelon form (also known as upper triangular)? | If you can use [`sympy`](http://code.google.com/p/sympy/), [`Matrix.rref()`](http://docs.sympy.org/0.7.1/modules/matrices.html#sympy.matrices.matrices.Matrix.rref) can do it:
```
In [8]: sympy.Matrix(np.random.random((4,4))).rref()
Out[8]:
([1, 1.42711055402454e-17, 0, -1.38777878078145e-17]
[0, 1.0,... |
Strip Trademark Symbol from string Python | 7,664,483 | 2 | 2011-10-05T16:21:13Z | 7,664,522 | 8 | 2011-10-05T16:24:02Z | [
"python",
"regex",
"string"
] | I'm trying to prep some data for a designer. I'm pulling data out of SQL Server with python on a Windows machine (not sure if OS is important). How would I make the string 'Official Trademarkâ¢' = 'Official Trademark'? Also, any further information/reading on unicode or the pertinent subject matter would help me becom... | The trademark symbol is Unicode character `U+2122`, or in Python notation `u"\u2122"`.
Just do a search and replace:
```
'string'.replace(u"\u2122", '')
``` |
Setup OpenCV 2.3 w/ python bindings in ubuntu | 7,664,803 | 12 | 2011-10-05T16:48:37Z | 7,664,844 | 12 | 2011-10-05T16:53:11Z | [
"python",
"linux",
"opencv"
] | How to install OpenCV (exactly 2.3.\*, not 2.1.\*) with python bindings in Ubuntu (or generally, in Linux)? I've seen few manuals on Windows installations, but none for Linux.
I've read and used [instructions from willow garage site](http://opencv.willowgarage.com/wiki/InstallGuide):
```
wget downloads.sourceforge.net... | Have you installed the Python development headers?
```
sudo apt-get install python-dev
```
Recompile it with those installed. |
How to get flat clustering corresponding to color clusters in the dendrogram created by scipy | 7,664,826 | 13 | 2011-10-05T16:51:17Z | 7,668,678 | 11 | 2011-10-05T22:52:23Z | [
"python",
"cluster-analysis",
"scipy",
"hierarchical",
"hierarchical-clustering"
] | Using the code posted [here](http://stackoverflow.com/questions/2455761/reordering-matrix-elements-to-reflect-column-and-row-clustering-in-naiive-python/3017704#3017704), I created a nice hierarchical clustering:

Let's say the the dendrogram on the left was crea... | I think you're on the right track. Let's try this:
```
import scipy
import scipy.cluster.hierarchy as sch
X = scipy.randn(100, 2) # 100 2-dimensional observations
d = sch.distance.pdist(X) # vector of (100 choose 2) pairwise distances
L = sch.linkage(d, method='complete')
ind = sch.fcluster(L, 0.5*d.max(), 'dist... |
Matplotlib imshow zoom function? | 7,665,076 | 9 | 2011-10-05T17:15:51Z | 7,665,819 | 7 | 2011-10-05T18:20:16Z | [
"python",
"image",
"matplotlib"
] | I have several (27) images represented in 2D arrays that I am viewing with imshow(). I need to zoom in on the exact same spot in every image. I know I can manually zoom, but this is tedious and not precise enough. Is there a way to programmatically specify a specific section of the image to show instead of the entire t... | You could use `plt.xlim` and `plt.ylim` to set the region to be plotted:
```
import matplotlib.pyplot as plt
import numpy as np
data=np.arange(9).reshape((3,3))
plt.imshow(data)
plt.xlim(0.5, 1.5)
plt.ylim(0.5,1.5)
plt.show()
``` |
Why use is_safe? | 7,665,512 | 4 | 2011-10-05T17:55:26Z | 7,665,559 | 11 | 2011-10-05T17:59:16Z | [
"python",
"django"
] | I'm reading Django documentation on custom filter.
and.. I don't see the reason of the existence of is\_safe.
<https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#filters-and-auto-escaping>
when I coded some examples and then tried them, the result were always same whether is\_safe is True or False.
**... | Using `is_safe` together with `mark_safe()` is redundant, which is probably why you don't see any differences.
As noted in the section you linked to, down where it talks about `mark_safe()`:
> There's no need to worry about the is\_safe attribute in this case (although including it wouldn't hurt anything). Whenever y... |
Python Mock object with method called multiple times | 7,665,682 | 33 | 2011-10-05T18:09:28Z | 7,665,754 | 48 | 2011-10-05T18:15:04Z | [
"python",
"unit-testing",
"mocking",
"python-mock"
] | I have a class that I'm testing which has as a dependency another class (an instance of which gets passed to the CUT's init method). I want to mock out this class using the Python Mock library.
What I have is something like:
```
mockobj = Mock(spec=MyDependencyClass)
mockobj.methodfromdepclass.return_value = "the val... | Try `side_effect`
```
def my_side_effect(*args, **kwargs):
if args[0] == 42:
return "Called with 42"
elif args[0] == 43:
return "Called with 43"
elif kwarg['foo'] == 7:
return "Foo is seven"
mockobj.mockmethod.side_effect = my_side_effect
``` |
Python Mock object with method called multiple times | 7,665,682 | 33 | 2011-10-05T18:09:28Z | 10,868,755 | 7 | 2012-06-03T07:58:02Z | [
"python",
"unit-testing",
"mocking",
"python-mock"
] | I have a class that I'm testing which has as a dependency another class (an instance of which gets passed to the CUT's init method). I want to mock out this class using the Python Mock library.
What I have is something like:
```
mockobj = Mock(spec=MyDependencyClass)
mockobj.methodfromdepclass.return_value = "the val... | I've ran into this when I was doing my own testing. If you don't care about capturing calls to your methodfromdepclass() but just need it to return something, then the following may suffice:
```
def makeFakeMethod(mapping={}):
def fakeMethod(inputParam):
return mapping[inputParam] if inputParam in mapping ... |
Python Mock object with method called multiple times | 7,665,682 | 33 | 2011-10-05T18:09:28Z | 13,636,416 | 37 | 2012-11-29T23:04:56Z | [
"python",
"unit-testing",
"mocking",
"python-mock"
] | I have a class that I'm testing which has as a dependency another class (an instance of which gets passed to the CUT's init method). I want to mock out this class using the Python Mock library.
What I have is something like:
```
mockobj = Mock(spec=MyDependencyClass)
mockobj.methodfromdepclass.return_value = "the val... | A little sweeter:
```
mockobj.method.side_effect = lambda x: {123: 100, 234: 10000}[x]
```
or for multiple arguments:
```
mockobj.method.side_effect = lambda *x: {(123, 234): 100, (234, 345): 10000}[x]
```
or with a default value:
```
mockobj.method.side_effect = lambda x: {123: 100, 234: 10000}.get(x, 20000)
```
... |
Tumblr API 2: Where is the "OAUTH_TOKEN" and "OAUTH_TOKEN_SECRET" | 7,665,818 | 12 | 2011-10-05T18:20:08Z | 11,975,984 | 23 | 2012-08-15T19:35:15Z | [
"python",
"api",
"oauth",
"tumblr"
] | I want to use Tumblr API 2, <http://www.tumblr.com/docs/en/api/v2>
I have already registered an Application here: <http://www.tumblr.com/oauth/apps>
But I only get the "OAuth Consumer Key" and "Secret Key". Where is the "OAUTH\_TOKEN" and "OAUTH\_TOKEN\_SECRET"?
One program <https://gist.github.com/1242662> needs th... | Probably this is old thread and you might have figured out how to work with it, Although I am trying to post the entire process for some newbies here, As it took a while for me to understand the entire process and work flow.
I have worked a lot with OAuth v2 and Tumblr API.
1. First and foremost we need to get regist... |
Tumblr API 2: Where is the "OAUTH_TOKEN" and "OAUTH_TOKEN_SECRET" | 7,665,818 | 12 | 2011-10-05T18:20:08Z | 18,292,055 | 12 | 2013-08-17T18:30:57Z | [
"python",
"api",
"oauth",
"tumblr"
] | I want to use Tumblr API 2, <http://www.tumblr.com/docs/en/api/v2>
I have already registered an Application here: <http://www.tumblr.com/oauth/apps>
But I only get the "OAuth Consumer Key" and "Secret Key". Where is the "OAUTH\_TOKEN" and "OAUTH\_TOKEN\_SECRET"?
One program <https://gist.github.com/1242662> needs th... | The steps given by @Shilpa are now [automated here](https://api.tumblr.com/console/calls/user/info). Go to that page and input your `consumer_key` & `consummer_secret`. You'll get back `oauth_token` & `oauth_token_secret`. |
Converting float.hex() value to binary in Python | 7,666,713 | 6 | 2011-10-05T19:36:09Z | 7,667,448 | 8 | 2011-10-05T20:40:40Z | [
"python"
] | I am wondering how to convert the result returned by `float.hex()` to binary, for example, from `0x1.a000000000000p+2` to `110.1`.
Can anyone please help? Thanks. | ```
def float_to_binary(num):
exponent=0
shifted_num=num
while shifted_num != int(shifted_num):
shifted_num*=2
exponent+=1
if exponent==0:
return '{0:0b}'.format(int(shifted_num))
binary='{0:0{1}b}'.format(int(shifted_num),exponent+1)
integer_part=binary[:-exponen... |
Can I patch a Python decorator before it wraps a function? | 7,667,567 | 25 | 2011-10-05T20:50:20Z | 7,667,621 | 27 | 2011-10-05T20:54:59Z | [
"python",
"unit-testing",
"mocking",
"decorator",
"monkeypatching"
] | I have a function with a decorator that I'm trying test with the help of the Python [Mock](http://www.voidspace.org.uk/python/mock/) library. I'd like to use mock.patch to replace the real decorator with a mock 'bypass' decorator which just calls the function. What I can't figure out is how to apply the patch before th... | Decorators are applied at function definition time. For most functions, this is when the module is loaded. (Functions that are defined in other functions have the decorator applied each time the enclosing function is called.)
So if you want to monkey-patch a decorator, what you need to do is:
1. Import the module tha... |
Numpy object arrays | 7,667,799 | 5 | 2011-10-05T21:11:48Z | 7,667,989 | 7 | 2011-10-05T21:31:01Z | [
"python",
"arrays",
"class",
"numpy"
] | I've recently run into issues when creating Numpy object arrays using e.g.
```
a = np.array([c], dtype=np.object)
```
where c is an instance of some complicated class, and in some cases Numpy tries to access some methods of that class. However, doing:
```
a = np.empty((1,), dtype=np.object)
a[0] = c
```
solves the ... | In the first case `a = np.array([c], dtype=np.object)`, numpy knows nothing about the shape of the intended array.
For example, when you define
```
d = range(10)
a = np.array([d])
```
Then you expect numpy to determine the shape based on the length of `d`.
So similarly in your case, numpy will attempt to see if `le... |
Pycurl keeps printing in terminal | 7,668,141 | 3 | 2011-10-05T21:45:58Z | 7,668,202 | 9 | 2011-10-05T21:52:23Z | [
"python",
"pycurl"
] | I am a beginner using Python and Pycurl for webpage stressing testing purposes. However, pycurl keeps printing out returned html in the terminal which makes the stress testing take even more time than it should. One such pycurl code I am using is posted below. Is there a way to just run pycurl without having to print o... | The Pycurl documentation is terrible, but I think you want to set WRITEFUNCTION to a function that does nothing, e.g.
```
p.setopt(pycurl.WRITEFUNCTION, lambda x: None)
```
Also, I wish to state for the record that I thought "SET does everything" APIs went out with VMS. Gaaah. |
Sending hex packets in python | 7,668,919 | 3 | 2011-10-05T23:27:20Z | 7,668,943 | 8 | 2011-10-05T23:29:45Z | [
"python",
"hex",
"packet"
] | How would I send hex data in a packet? I'm trying to copy a packet exactly by using the hex instead of ASCII. All I'm looking for is what the sendto argument would be if, say, the hex I needed to send was 00AD12. | Use [`struct`](http://docs.python.org/library/struct.html) to convert between bytes (typically expressed in hexadecimal fashion) and numbers:
```
>>> import struct
>>> struct.pack('!I', 0xAD12)
b'\x00\x00\xad\x12'
```
If you have a hex *string* and want to convert it to bytes, use [`binascii.unhexlify`](http://docs.p... |
How do you watch a variable in pdb | 7,668,979 | 30 | 2011-10-05T23:36:28Z | 7,669,165 | 20 | 2011-10-06T00:14:06Z | [
"python",
"pdb"
] | I'm debugging a python script, and I want to watch a variable for a change (much like you can watch a memory adress in gdb). Is there a way to do this? | Here is a really hacky way to do this with `pdb`. These commands can be put in your `~/.pdbrc` for automatic loading every time you use `pdb`.
```
!global __currentframe, __stack; from inspect import currentframe as __currentframe, stack as __stack
!global __copy; from copy import copy as __copy
!global __Pdb; from pd... |
How to implement OpenSSL functionality in Python? | 7,669,598 | 13 | 2011-10-06T01:48:33Z | 7,670,551 | 18 | 2011-10-06T05:20:43Z | [
"python",
"openssl",
"public-key-encryption",
"private-key"
] | I would like to encrypt a secret text by public-key and decrypt it by private-key in Python.
I can achieve that with the `openssl` command:
```
echo "secrettext/2011/09/14 22:57:23" | openssl rsautl -encrypt -pubin -inkey public.pem | base64 data.cry
base64 -D data.cry | openssl rsautl -decrypt -inkey private.pem
```... | ### Encrypt
```
#!/usr/bin/env python
import fileinput
from M2Crypto import RSA
rsa = RSA.load_pub_key("public.pem")
ctxt = rsa.public_encrypt(fileinput.input().read(), RSA.pkcs1_padding)
print ctxt.encode('base64')
```
### Decrypt
```
#!/usr/bin/env python
import fileinput
from M2Crypto import RSA
priv = RSA.load... |
Get the Olson TZ name for the local timezone? | 7,669,938 | 45 | 2011-10-06T03:04:28Z | 7,841,417 | 15 | 2011-10-20T19:49:20Z | [
"python",
"linux",
"datetime",
"timezone",
"localtime"
] | How do I get the [Olson timezone name](http://en.wikipedia.org/wiki/Tz_database#Names_of_time_zones) (such as `Australia/Sydney`) corresponding to the value given by C's [`localtime`](http://docs.python.org/py3k/library/time.html#time.localtime) call?
This is the value overridden via `TZ`, by symlinking `/etc/localtim... | This is kind of cheating, I know, but getting from `'/etc/localtime'` doesn't work for you?
Like following:
```
>>> import os
>>> '/'.join(os.readlink('/etc/localtime').split('/')[-2:])
'Australia/Sydney'
```
Hope it helps.
**Edit**: I liked @A.H.'s idea, in case `'/etc/localtime'` isn't a symlink. Translating that... |
Get the Olson TZ name for the local timezone? | 7,669,938 | 45 | 2011-10-06T03:04:28Z | 7,896,388 | 13 | 2011-10-25T21:57:29Z | [
"python",
"linux",
"datetime",
"timezone",
"localtime"
] | How do I get the [Olson timezone name](http://en.wikipedia.org/wiki/Tz_database#Names_of_time_zones) (such as `Australia/Sydney`) corresponding to the value given by C's [`localtime`](http://docs.python.org/py3k/library/time.html#time.localtime) call?
This is the value overridden via `TZ`, by symlinking `/etc/localtim... | One problem is that there are multiple "pretty names" , like "Australia/Sydney" , which point to the same time zone (e.g. CST).
So you will need to get all the possible names for the local time zone, and then select the name you like.
e.g.: for Australia, there are 5 time zones, but way more time zone identifiers:
`... |
Get the Olson TZ name for the local timezone? | 7,669,938 | 45 | 2011-10-06T03:04:28Z | 7,896,521 | 8 | 2011-10-25T22:11:40Z | [
"python",
"linux",
"datetime",
"timezone",
"localtime"
] | How do I get the [Olson timezone name](http://en.wikipedia.org/wiki/Tz_database#Names_of_time_zones) (such as `Australia/Sydney`) corresponding to the value given by C's [`localtime`](http://docs.python.org/py3k/library/time.html#time.localtime) call?
This is the value overridden via `TZ`, by symlinking `/etc/localtim... | If evaluating `/etc/localtime` is OK for you, the following trick might work - after translating it to python:
```
> md5sum /etc/localtime
abcdefabcdefabcdefabcdefabcdefab /etc/localtime
> find /usr/share/zoneinfo -type f |xargs md5sum | grep abcdefabcdefabcdefabcdefabcdefab
abcdefabcdefabcdefabcdefabcdefab /usr/share... |
Get the Olson TZ name for the local timezone? | 7,669,938 | 45 | 2011-10-06T03:04:28Z | 8,328,904 | 17 | 2011-11-30T15:58:02Z | [
"python",
"linux",
"datetime",
"timezone",
"localtime"
] | How do I get the [Olson timezone name](http://en.wikipedia.org/wiki/Tz_database#Names_of_time_zones) (such as `Australia/Sydney`) corresponding to the value given by C's [`localtime`](http://docs.python.org/py3k/library/time.html#time.localtime) call?
This is the value overridden via `TZ`, by symlinking `/etc/localtim... | I think best bet is to go thru all pytz timezones and check which one matches local timezone, each pytz timezone object contains info about utcoffset and tzname like CDT, EST, same info about local time can be obtained from `time.timezone/altzone` and `time.tzname`, and I think that is enough to correctly match local t... |
Finding a subimage inside a Numpy image | 7,670,112 | 12 | 2011-10-06T03:39:31Z | 7,697,929 | 7 | 2011-10-08T15:50:10Z | [
"python",
"image",
"numpy",
"python-imaging-library"
] | I have two Numpy arrays (3-dimensional uint8) converted from PIL images.
I want to find if the first image contains the second image, and if so, find out the coordinates of the top-left pixel inside the first image where the match is.
Is there a way to do that purely in Numpy, in a fast enough way, rather than using ... | This can be done using scipy's [correlate2d](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.correlate2d.html#scipy.signal.correlate2d) and then using [argmax](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html) to find the peak in the cross-correlation.
[Here's](http://www.fmwconce... |
Finding a subimage inside a Numpy image | 7,670,112 | 12 | 2011-10-06T03:39:31Z | 9,253,805 | 30 | 2012-02-12T23:40:02Z | [
"python",
"image",
"numpy",
"python-imaging-library"
] | I have two Numpy arrays (3-dimensional uint8) converted from PIL images.
I want to find if the first image contains the second image, and if so, find out the coordinates of the top-left pixel inside the first image where the match is.
Is there a way to do that purely in Numpy, in a fast enough way, rather than using ... | I'm doing this with [OpenCV](http://opencv.itseez.com/index.html)'s [`matchTemplate`](http://opencv.itseez.com/modules/imgproc/doc/object_detection.html?highlight=matchtemplate#cv2.matchTemplate) function. There is an excellent python binding to OpenCV which uses numpy internally, so images are just numpy arrays. For e... |
python/numpy: how to get 2D array column length? | 7,670,226 | 6 | 2011-10-06T04:07:42Z | 7,670,325 | 13 | 2011-10-06T04:34:07Z | [
"python",
"numpy"
] | How do i get the length of the column in a nD array?
example, i have a nD array called a. when i print a.shape, it returns (1,21).
I want to do a for loop, in the range of the column size of the array a. How do i get the value of | You can get the second dimension of the array as:
```
a.shape[1]
``` |
Tree plotting in Python | 7,670,280 | 15 | 2011-10-06T04:22:51Z | 7,673,423 | 11 | 2011-10-06T11:10:18Z | [
"python",
"tree",
"plot"
] | I want to plot trees using Python. Decision trees, Organizational charts, etc. Any library that helps me with that? | There's graphviz - <http://www.graphviz.org/>. It uses the "DOT" language to plot graphs. You can either generate the DOT code yourself, or use pydot - <https://code.google.com/p/pydot/>. You could also use networkx - <http://networkx.lanl.gov/tutorial/tutorial.html#drawing-graphs>, which make it easy to draw to either... |
Tree plotting in Python | 7,670,280 | 15 | 2011-10-06T04:22:51Z | 29,443,925 | 10 | 2015-04-04T07:34:57Z | [
"python",
"tree",
"plot"
] | I want to plot trees using Python. Decision trees, Organizational charts, etc. Any library that helps me with that? | I develop [ETE](http://etetoolkit.org), which is a python package intended, among other stuff, for programmatic tree rendering and visualization. You can create your own [layout functions](http://etetoolkit.org/docs/latest/tutorial/tutorial_drawing.html) and produce custom [tree images](http://etetoolkit.org/gallery/):... |
sqlite3.OperationalError: unable to open database file | 7,670,289 | 25 | 2011-10-06T04:25:20Z | 7,670,618 | 50 | 2011-10-06T05:37:15Z | [
"python",
"database",
"django",
"sqlite",
"django-settings"
] | I get this error when setting up a server in Django. It is sqlite3 which means it should create the .db file but it doesn't seem to be doing so. I've stipulated SQLite as the backend and an absolute file path for where to put it, but no luck.
Is this a bug or am I doing something incorrect? (Was just thinking, is the ... | [Django NewbieMistakes](https://code.djangoproject.com/wiki/NewbieMistakes#DjangosaysUnabletoOpenDatabaseFilewhenusingSQLite3)
> PROBLEM You're using SQLite3, your DATABASE\_NAME is set to the
> database file's full path, the database file is writeable by Apache,
> but you still get the above error.
>
> SOLUTION Make ... |
sqlite3.OperationalError: unable to open database file | 7,670,289 | 25 | 2011-10-06T04:25:20Z | 11,242,817 | 15 | 2012-06-28T10:37:37Z | [
"python",
"database",
"django",
"sqlite",
"django-settings"
] | I get this error when setting up a server in Django. It is sqlite3 which means it should create the .db file but it doesn't seem to be doing so. I've stipulated SQLite as the backend and an absolute file path for where to put it, but no luck.
Is this a bug or am I doing something incorrect? (Was just thinking, is the ... | I faced exactly same issue. Here is my setting which worked.
```
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/home/path/to/your/db/data.sqlite3'
```
Other setting in case of sqlite3 will be same/default.
And you need to create data.sqlite3. |
Purpose of #!/usr/bin/python3 | 7,670,303 | 24 | 2011-10-06T04:29:16Z | 7,670,334 | 8 | 2011-10-06T04:34:53Z | [
"python",
"scripting"
] | I have noticed this in a couple of scripting languages, but in this example, I am using python. In many tutorials, they would start with "#!/usr/bin/python3" on the first line. I don't understand why we have this.
* Shouldn't the operating system know it's a python script (obviously it's installed since you are making... | That's called a hash-bang. If you run the script from the shell, it will inspect the first line to figure out what program should be started to interpret the script.
A non Unix based OS will use its own rules for figuring out how to run the script. Windows for example will use the filename extension and the `#` will c... |
Purpose of #!/usr/bin/python3 | 7,670,303 | 24 | 2011-10-06T04:29:16Z | 7,670,338 | 49 | 2011-10-06T04:35:49Z | [
"python",
"scripting"
] | I have noticed this in a couple of scripting languages, but in this example, I am using python. In many tutorials, they would start with "#!/usr/bin/python3" on the first line. I don't understand why we have this.
* Shouldn't the operating system know it's a python script (obviously it's installed since you are making... | `#!/usr/bin/python3` is a **shebang line**.
A shebang line defines where the interpreter is located at. In this case, the `python3` interpreter is located in `/usr/bin/python3`. It could be a `bash`, `ruby`, `perl` or any other scripting languages' interpreter. The operating system does not know it's a python script i... |
Python 3 : Sharing variables between methods in a class | 7,670,415 | 2 | 2011-10-06T04:55:18Z | 7,670,452 | 8 | 2011-10-06T05:02:32Z | [
"python",
"oop",
"scope"
] | Looking for how to make a variable set by one Method/function in a class accessible to another method/function in that same class without having to do excess (and problematic code) outside.
Here is an example that doesn't work, but may show you what I'm trying to do :
```
#I just coppied this one to have an init meth... | You set it in one method and then look it up in another:
```
class TestClass(object):
def current(self, test):
"""Just a method to get a value"""
self.test = test
print(test)
def next_one(self):
"""Trying to get a value from the 'current' method"""
new_val = self.test
... |
Excel-like ceiling function in python? | 7,672,107 | 6 | 2011-10-06T08:54:32Z | 7,672,192 | 9 | 2011-10-06T09:03:28Z | [
"python",
"excel",
"math",
"ceil",
"ceiling"
] | I know about [math.ceil](http://docs.python.org/library/math.html) and [numpy.ceil](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ceil.html), but both of them lack of `significance` parameter.
For example in Excel:
`=Ceiling(210.63, 0.05)` -> `210.65`
numpy.ceil and math.ceil in other hand:
`numpy.ceil(2... | I don't know of any python function to do so, but you can easily code one :
```
import math
def ceil(x, s):
return s * math.ceil(float(x)/s)
```
The conversion to float is necessary in python 2 to avoid the integer division if both arguments are integers. You can also use `from __future__ import division`. This ... |
Python Function To Find String Between Two Markers | 7,672,432 | 2 | 2011-10-06T09:26:29Z | 7,672,492 | 9 | 2011-10-06T09:33:07Z | [
"python",
"regex",
"string"
] | I'm looking to build a string function to extract the string contents between two markers. It returns an extraction list
```
def extract(raw_string, start_marker, end_marker):
... function ...
return extraction_list
```
I know this can be done using regex but is this fast? This will be called billions of time... | You probably can't go faster than:
```
def extract(raw_string, start_marker, end_marker):
start = raw_string.index(start_marker) + len(start_marker)
end = raw_string.index(end_marker, start)
return raw_string[start:end]
```
But if you want to try regex, just try to benchmark it. There's a good timeit modu... |
Is there a Python function like Lua's string.sub? | 7,673,079 | 3 | 2011-10-06T10:30:39Z | 7,673,112 | 9 | 2011-10-06T10:33:31Z | [
"python",
"string",
"substring"
] | As per the title, I am looking for a Python function similar to Lua's string.sub, whether it be 3rd party or part of the Python Standard library. I've been searching all over the internet ( including stackoverflow ) for nearly an hour and haven't been able to find anything whatsoever. | Python doesn't require such a function. It's slicing syntax supports String.sub functionality (and more) directly:
```
>>> 'hello'[:2]
'he'
>>> 'hello'[-2:]
'lo'
>>> 'abcdefghijklmnop'[::2]
'acegikmo'
>>> 'abcdefghijklmnop'[1::2]
'bdfhjlnp'
>>> 'Reverse this!'[::-1]
'!siht esreveR'
``` |
Is there a Python function like Lua's string.sub? | 7,673,079 | 3 | 2011-10-06T10:30:39Z | 7,673,129 | 11 | 2011-10-06T10:35:16Z | [
"python",
"string",
"substring"
] | As per the title, I am looking for a Python function similar to Lua's string.sub, whether it be 3rd party or part of the Python Standard library. I've been searching all over the internet ( including stackoverflow ) for nearly an hour and haven't been able to find anything whatsoever. | **Lua:**
```
> = string.sub("Hello Lua user", 7) -- from character 7 until the end
Lua user
> = string.sub("Hello Lua user", 7, 9) -- from character 7 until and including 9
Lua
> = string.sub("Hello Lua user", -8) -- 8 from the end until the end
Lua user
> = string.sub("Hello Lua user", -8, 9) -- 8 from th... |
App Engine httplib.HTTPConnection deadline | 7,673,404 | 5 | 2011-10-06T11:07:50Z | 7,674,747 | 7 | 2011-10-06T13:16:45Z | [
"python",
"google-app-engine"
] | Since App Engine's **httplib** is simply wrapped around their own **urlfetch**, I'm wondering how to set the default urlfetch timeout to the allowed maximum 10 seconds **so that it will affect httplib.HTTPConnection**.
I can't directly set the timeout on HTTPConnection, as GAE uses 2.5. 2.6 added the timeout param. | Have you tried changing the default urlfetch deadline?
```
import urlfetch
urlfetch.set_default_fetch_deadline(10)
``` |
Python Mechanize select form FormNotFoundError | 7,673,905 | 10 | 2011-10-06T11:54:53Z | 7,677,051 | 23 | 2011-10-06T15:56:50Z | [
"python",
"mechanize",
"mechanize-python"
] | I want to select a form with mechanize. This is my code:
```
br = mechanize.Browser()
self.br.open(url)
br.select_form(name="login_form")
```
The form's code:
```
<form id="login_form" onsubmit="return Index.login_submit();" method="post" action="index.php?action=login&server_list=1">
```
But I'm getting this Error... | The problem is that your form does not have a name, only an id, and it is `login_form`. You can use a predicate:
```
br.select_form(predicate=lambda f: f.attrs.get('id', None) == 'login_form')
```
(where you se if `f.attrs` has the key `id` and, if so, the `id` value is equal to `login_form`). Alternatively, you can ... |
Django admin list_display property usage | 7,674,072 | 5 | 2011-10-06T12:12:00Z | 7,674,131 | 11 | 2011-10-06T12:17:22Z | [
"python",
"django",
"django-admin"
] | I have models and their admin code at below. The question is how can I show the first three `tag` of a book in its `list_display` property ?
I can show the tags while the book is editing but I would like to its 3 tags while the book are listed in the admin panel.
**models.py**
```
class Book(models.Model):
name =... | Use a custom method on the admin class.
```
class BookAdmin(admin.ModelAdmin):
list_display = ('name', 'three_tags')
def three_tags(self, obj):
return obj.booktag_set.all()[:3]
``` |
What's exactly happening in infinite nested lists? | 7,674,685 | 27 | 2011-10-06T13:10:48Z | 7,674,753 | 11 | 2011-10-06T13:17:10Z | [
"python",
"list",
"infinite"
] | It's possible to create an infinite nested list in Python. That's clear and, although not popular and definitely not useful is a known fact.
```
>>> a = [0]
>>> a[0] = a
>>> a
[[...]]
>>> a[0] == a
True
```
My question is, what is happening here:
```
>>> a = [0]
>>> b = [0]
>>> a[0], b[0] = b, a
>>> a
[[[...]]]
>>> ... | I *suspect* the following happens:
`a[0]==b`: Python looks up the value `a[0]` and finds some kind of reference to `b`, so it says `True`.
`a[0][0]==b`: Python looks up `a[0]`, finds `b` and now looks up `a[0][0]`, which is, (since `a[0]` holds `b`) `b[0]`. Now it sees, that `b[0]` holds some kind of reference to `a`... |
What's exactly happening in infinite nested lists? | 7,674,685 | 27 | 2011-10-06T13:10:48Z | 7,674,838 | 7 | 2011-10-06T13:23:39Z | [
"python",
"list",
"infinite"
] | It's possible to create an infinite nested list in Python. That's clear and, although not popular and definitely not useful is a known fact.
```
>>> a = [0]
>>> a[0] = a
>>> a
[[...]]
>>> a[0] == a
True
```
My question is, what is happening here:
```
>>> a = [0]
>>> b = [0]
>>> a[0], b[0] = b, a
>>> a
[[[...]]]
>>> ... | > I see, that a contains b, that contains a
They don't contain each other as such - A is a reference to a list, the first thing in this list is a reference to B, and vice versa
```
>>> a[0] == b
True
>>> a[0][0] == b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: maximum recurs... |
What's exactly happening in infinite nested lists? | 7,674,685 | 27 | 2011-10-06T13:10:48Z | 7,674,849 | 9 | 2011-10-06T13:24:24Z | [
"python",
"list",
"infinite"
] | It's possible to create an infinite nested list in Python. That's clear and, although not popular and definitely not useful is a known fact.
```
>>> a = [0]
>>> a[0] = a
>>> a
[[...]]
>>> a[0] == a
True
```
My question is, what is happening here:
```
>>> a = [0]
>>> b = [0]
>>> a[0], b[0] = b, a
>>> a
[[[...]]]
>>> ... | `a[0]` refers to `b` and `b[0]` refers to `a`. This is a circular reference. As glglgl has mentioned, when you try `==` operator it tries comparison of values.
Try this, which might make things more clear -
```
>>> id(a)
4299818696
>>> id(b)
4299818768
>>> id(a[0])
4299818768
>>>
>>> id(b[0])
4299818696
``` |
What's exactly happening in infinite nested lists? | 7,674,685 | 27 | 2011-10-06T13:10:48Z | 7,680,125 | 22 | 2011-10-06T20:32:19Z | [
"python",
"list",
"infinite"
] | It's possible to create an infinite nested list in Python. That's clear and, although not popular and definitely not useful is a known fact.
```
>>> a = [0]
>>> a[0] = a
>>> a
[[...]]
>>> a[0] == a
True
```
My question is, what is happening here:
```
>>> a = [0]
>>> b = [0]
>>> a[0], b[0] = b, a
>>> a
[[[...]]]
>>> ... | Disclaimer: I don't use Python, so some things I say may be wrong. Python experts, feel free to correct me.
Great question. I think the central misconception *(if I can't even call it that; it's perfectly reasonable how you arrived at the thought process you used)* you're having that prompts you to ask the question is... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.