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
List directory tree structure using Python
9,727,673
27
2012-03-15T20:29:30Z
9,728,478
42
2012-03-15T21:29:59Z
[ "python", "directory-structure" ]
I know that we can use os.walk() to list all sub-directories or all files in a directory. However, I would like to list the full directory tree content: * Subdirectory 1: + file11 + file12 + Sub-sub-directory 11: - file111 - file112 * Subdirectory 2: + file21 + sub-sub-directory 21 + sub-sub-direct...
Here's a function to do that with formatting: ``` import os def list_files(startpath): for root, dirs, files in os.walk(startpath): level = root.replace(startpath, '').count(os.sep) indent = ' ' * 4 * (level) print('{}{}/'.format(indent, os.path.basename(root))) subindent = ' ' * 4...
Is self.__dict__.update(**kwargs) good or poor style?
9,728,243
27
2012-03-15T21:12:14Z
9,728,406
19
2012-03-15T21:25:01Z
[ "python", "oop", "dictionary" ]
In Python, say I have some class, Circle, that inherits from Shape. Shape needs x- and y-coordinates, and, in addition, Circle needs a radius. I want to be able to initialize Circle by doing something like, ``` c = Circle(x=1., y=5., r=3.) ``` Circle inherits from shape, so I need to use named arguments to `__init__`...
``` class Shape(object): def __init__(self, x=None, y=None): self.x = x self.y = y class Circle(Shape): def __init__(self, r=None, **kwargs): super(Circle, self).__init__(**kwargs) self.r = r ``` And this is it. Don't use `**kwargs` when you don't really need them. > Is this c...
Is self.__dict__.update(**kwargs) good or poor style?
9,728,243
27
2012-03-15T21:12:14Z
9,728,469
14
2012-03-15T21:29:02Z
[ "python", "oop", "dictionary" ]
In Python, say I have some class, Circle, that inherits from Shape. Shape needs x- and y-coordinates, and, in addition, Circle needs a radius. I want to be able to initialize Circle by doing something like, ``` c = Circle(x=1., y=5., r=3.) ``` Circle inherits from shape, so I need to use named arguments to `__init__`...
I would say that the first method is definitely preferable, because [explicit is better than implicit](http://www.python.org/dev/peps/pep-0020/). Consider what would happen if you made a typo when initializing a Circle, something like `Circle(x=1., y=5., rr=3.)`. You want to see this error immediately, which would not...
Mocking a class method that is used via an instance
9,728,748
6
2012-03-15T21:52:48Z
9,736,127
10
2012-03-16T11:05:04Z
[ "python", "unit-testing", "mocking" ]
I'm trying to patch a class method using mock as described [in the documentation](http://www.voidspace.org.uk/python/mock/patch.html#patch). The Mock object itself works fine, but its methods don't: For example, their attributes like `call_count` aren't updated, even though the `method_calls` attribute of the class `Mo...
I have found my error: In order to configure the methods of my mock's instances, I have to use `mock().method` instead of `mock.method`. ``` class Lib: """In my actual program, a module that I import""" def method(self): return "real" class User: """The class I want to test""" def run(self): ...
How do I unpack a list with fewer variables?
9,729,252
11
2012-03-15T22:39:53Z
9,729,298
21
2012-03-15T22:44:37Z
[ "python" ]
``` k = [u'query_urls', u'"kick"', u'"00"', u'msg=1212', u'id=11'] >>> name, view, id, tokens = k Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack ``` I need to provide 5 variables to unpack this list. Is there a way to unpack with fewer, so that `tokens` ...
In Python 3 you can do this: (edit: this is called [extended iterable unpacking](http://www.python.org/dev/peps/pep-3132/)) ``` name, view, id, *tokens = k ``` In Python 2, you will have to do this: ``` (name, view, id), tokens = k[:3], k[3:] ```
Python's read and write add \x00 to the file
9,729,452
5
2012-03-15T22:58:15Z
9,729,482
10
2012-03-15T23:00:56Z
[ "python", "file-io" ]
I have come across a weird problem when working with files in python. Let's say I have a text file and a simple piece of code that reads the contents of the file and then rewrites it with unaltered contents. **File.txt** > This is a test file **Python code** ``` f=open(File.txt,'r+') data=f.read() f.truncate(0) f.w...
Suppose your file has 20 bytes in it. So `f.read()` reads 20 bytes. Now you truncate the file to 0 bytes. But your position-in-file pointer is still at 20. Why wouldn't it be? You haven't moved it. So when you write, you begin writing at the 21st byte. Your OS fills in the 20 missing bytes with zeroes. To avoid this, ...
gem/git-style command line arguments in Python
9,729,919
17
2012-03-15T23:49:38Z
9,729,939
26
2012-03-15T23:52:35Z
[ "python", "command-line-interface" ]
Is there a Python module for **doing** gem/git-style command line arguments? What I mean by gem/git style is: ``` $ ./MyApp.py The most commonly used MyApp commands are: add Add file contents to the index bisect Find by binary search the change that introduced a bug branch List, create, or delete ...
Yes, [`argparse`](http://docs.python.org/py3k/library/argparse.html) with [`add_subparser()`](http://docs.python.org/py3k/library/argparse.html#sub-commands). It's all well explained in the [Sub-commands](http://docs.python.org/py3k/library/argparse.html#sub-commands) section. Copying one of the examples from there: ...
Exiting from python Command Line
9,730,409
41
2012-03-16T00:57:56Z
9,730,463
15
2012-03-16T01:05:31Z
[ "python" ]
To exit from Python command line, I have to type exit(). If I type exit, it says ``` Use exit() or Ctrl-Z plus Return to exit ``` Usually when you type `exit`, you would want to exit the program. Why does the interpreter give me the above error when it knows I am trying to exit the command line? Why doesn't it just e...
This message is the `__str__` attribute of `exit` look at these examples : 1 ``` >>> print exit Use exit() or Ctrl-D (i.e. EOF) to exit ``` 2 ``` >>> exit.__str__() 'Use exit() or Ctrl-D (i.e. EOF) to exit' ``` 3 ``` >>> getattr(exit, '__str__')() 'Use exit() or Ctrl-D (i.e. EOF) to exit' ```
Exiting from python Command Line
9,730,409
41
2012-03-16T00:57:56Z
9,730,507
14
2012-03-16T01:10:44Z
[ "python" ]
To exit from Python command line, I have to type exit(). If I type exit, it says ``` Use exit() or Ctrl-Z plus Return to exit ``` Usually when you type `exit`, you would want to exit the program. Why does the interpreter give me the above error when it knows I am trying to exit the command line? Why doesn't it just e...
When you type `exit` in the command line, it finds the variable with that name and calls `__repr__` (or `__str__`) on it. Usually, you'd get a result like: ``` <function exit at 0x00B97FB0> ``` But they decided to redefine that function for the `exit` object to display a helpful message instead. Whether or not that's...
Exiting from python Command Line
9,730,409
41
2012-03-16T00:57:56Z
9,730,522
7
2012-03-16T01:13:13Z
[ "python" ]
To exit from Python command line, I have to type exit(). If I type exit, it says ``` Use exit() or Ctrl-Z plus Return to exit ``` Usually when you type `exit`, you would want to exit the program. Why does the interpreter give me the above error when it knows I am trying to exit the command line? Why doesn't it just e...
Because the interpreter is not a shell where you provide commands, it's - well - an interpreter. The things that you give to it are Python code. The syntax of Python is such that `exit`, by itself, cannot possibly be anything other than a name for an object. Simply referring to an object can't actually do anything (ex...
Is there a better way to mask a Credit Card number in python?
9,730,653
5
2012-03-16T01:30:51Z
9,730,785
11
2012-03-16T01:51:32Z
[ "python", "string" ]
So I have a csv file that contains full credit-card numbers.. We dont need the full number, and so I am writing a quick script to parse through the csv and replace the cc number with a masked representation. (all \*'s except the last four). I am pretty new to python and hacked this up, and it works, but in order to lea...
Neater still: ``` >>> s = "CREDITCARDNUMBER" >>> s[-4:].rjust(len(s), "*") '************MBER' ```
How to handle utf8 on the command line (using Perl or Python)?
9,730,835
14
2012-03-16T01:58:44Z
9,731,060
23
2012-03-16T02:32:32Z
[ "python", "perl", "utf-8" ]
How can I handle utf8 using Perl (or Python) on the command line? I am trying to split the characters in each word, for example. This is very easy for non-utf8 text, for example: ``` $ echo "abc def" | perl -ne 'my @letters = m/(.)/g; print "@letters\n"' | less a b c d e f ``` But with utf8 it doesn't work, of cou...
The "-C" flag controls some of the Perl Unicode features (see `perldoc perlrun`): ``` $ echo "одобрение за" | perl -C -pe 's/.\K/ /g' о д о б р е н и е з а ``` To specify encoding used for stdin/stdout you could use `PYTHONIOENCODING` environment variable: ``` $ echo "одобрение за"...
Retry Celery tasks with exponential back off
9,731,435
36
2012-03-16T03:28:48Z
9,752,811
58
2012-03-17T18:54:40Z
[ "python", "celery", "django-celery" ]
For a task like this: ``` from celery.decorators import task @task() def add(x, y): if not x or not y: raise Exception("test error") return self.wait_until_server_responds( ``` if it throws an exception and I want to retry it from the daemon side, how can apply an exponential back off algorithm, i.e....
The [`task.request.retries`](http://celery.readthedocs.org/en/latest/userguide/tasks.html#context) attribute contains the number of tries so far, so you can use this to implement exponential back-off: ``` from celery.task import task @task(bind=True, max_retries=3) def update_status(self, auth, status): try: ...
An unusual Python syntax element frequently used in Matplotlib
9,731,779
5
2012-03-16T04:11:56Z
9,731,791
16
2012-03-16T04:13:23Z
[ "python", "syntax", "reference", "matplotlib" ]
One proviso: The syntax element at the heart of my Question is in the Python language; however, this element appears frequently in the Matplotlib library, which is the only context i have seen it. So whether it's a general Python syntax question or a library-specific one, i am not sure. What i do know is that i could n...
It's [**sequence unpacking**](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences) for a single element. ``` >>> l = [3] >>> v, = l >>> v 3 ```
Running shell command from Python script
9,731,847
3
2012-03-16T04:22:22Z
9,731,891
9
2012-03-16T04:27:34Z
[ "python" ]
I'm trying to run a shell command from within a python script which needs to do several things 1. The shell command is 'hspice tran.deck >! tran.lis' 2. The script should wait for the shell command to complete before proceeding 3. I need to check the return code from the command and 4. Capture STDOUT if it comp...
Just use [`.returncode`](http://docs.python.org/library/subprocess.html#subprocess.Popen.returncode) after `.communicate()`. Also, tell Popen that [what you're trying to run is a shell command](http://docs.python.org/library/subprocess.html#popen-constructor), rather than a raw command line: ``` p = subprocess.Popen('...
What is the difference between keyword: is and == in python
9,733,257
3
2012-03-16T07:07:45Z
9,733,301
7
2012-03-16T07:12:22Z
[ "python", "syntax", "keyword" ]
the python keyword `is` is supposed to be used in place of the `==` operator according to python style guides. However they don't always do exactly the same thing as shown here. Why? What is the actual difference, and what is the proper usage? ``` import unittest class testIS(unittest.TestCase): def test_is(self...
`==` tests for equality. Two non-identical objects can be equal. `is` tests for identity, i.e. whether both refer to the same one object.
Post JSON using Python Requests
9,733,638
168
2012-03-16T07:46:49Z
9,952,774
199
2012-03-31T03:26:53Z
[ "python", "json", "python-requests", "cherrypy" ]
I need to POST a JSON from a client to a server. I'm using Python 2.7.1 and simplejson. The client is using Requests. The server is CherryPy. I can GET a hard-coded JSON from the server (code not shown), but when I try to POST a JSON to the server, I get "400 Bad Request". Here is my client code: ``` data = {'sender'...
It turns out I was missing the header information. The following works: ``` url = "http://localhost:8080" data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url, data=json.dumps(data), headers=headers) ```
Post JSON using Python Requests
9,733,638
168
2012-03-16T07:46:49Z
26,344,315
189
2014-10-13T16:08:06Z
[ "python", "json", "python-requests", "cherrypy" ]
I need to POST a JSON from a client to a server. I'm using Python 2.7.1 and simplejson. The client is using Requests. The server is CherryPy. I can GET a hard-coded JSON from the server (code not shown), but when I try to POST a JSON to the server, I get "400 Bad Request". Here is my client code: ``` data = {'sender'...
As of Requests version 2.4.2 and onwards, you can alternatively use 'json' parameter in the call which makes it simpler. ``` >>> import requests >>> r = requests.post('http://httpbin.org/post', json={"key": "value"}) >>> r.status_code 200 >>> r.json() {'args': {}, 'data': '{"key": "value"}', 'files': {}, 'form': {}...
Post JSON using Python Requests
9,733,638
168
2012-03-16T07:46:49Z
27,398,215
21
2014-12-10T10:08:59Z
[ "python", "json", "python-requests", "cherrypy" ]
I need to POST a JSON from a client to a server. I'm using Python 2.7.1 and simplejson. The client is using Requests. The server is CherryPy. I can GET a hard-coded JSON from the server (code not shown), but when I try to POST a JSON to the server, I get "400 Bad Request". Here is my client code: ``` data = {'sender'...
From requests 2.4.2 (<https://pypi.python.org/pypi/requests>), the "json" parameter is supported. No need to specify "Content-Type". So the shorter version: ``` requests.post('http://httpbin.org/post', json={'test': 'cheers'}) ```
Remove entries of a dictionary that are not in a set
9,735,504
2
2012-03-16T10:22:32Z
9,735,585
8
2012-03-16T10:27:53Z
[ "python", "python-2.7" ]
Given the following dictionary and set: ``` d = {1 : a, 2 : b, 3 : c, 4 : d, 5 : e } s = set([1, 4]) ``` I was wondering if it is possible to remove all dictionary entries that are not contained in the set (i.e. 2,3,5). I am aware that i can achieve this by iterating over the dictionary and check each key but since i...
``` d = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e' } s = set([1, 4]) ``` Since you should not modify a dictionary while itering over it, you have two possibilities to create a new dictionary. One is to create a new dictionary from the old one filtering values out: ``` d2 = dict((k,v) for k,v in d.iteritems() if k ...
Running a linux command from python
9,735,863
6
2012-03-16T10:47:14Z
9,736,031
7
2012-03-16T10:58:17Z
[ "python", "linux" ]
I need to run this linux command from python and assign the output to a variable. ``` ps -ef | grep rtptransmit | grep -v grep ``` I've tried using pythons commands library to do this. ``` import commands a = commands.getoutput('ps -ef | grep rtptransmit | grep -v grep') ``` But a gets the end of cut off. The outpu...
`ps` apparently limits its output to fit into the presumed width of the terminal. You can override this width with the `$COLUMNS` environment variable or with the `--columns` option to `ps`. The `commands` module is deprecated. Use `subprocess` to get the output of `ps -ef` and filter the output in Python. Do not use ...
Is if/else/if possible in list comprehension?
9,736,991
2
2012-03-16T12:11:15Z
9,737,013
12
2012-03-16T12:12:42Z
[ "python", "list-comprehension" ]
I'd like to know if it is possible to use a list comprehension with `if`/ `else` that need not result in a list of the same length as the length of the list being processed? (ie. without the final `else`) ``` >>> L = [0, 1, 2, 3, 4, 5, 6] >>> [v * 10 if v < 3 else v * 2 if v > 3 else v for v in L] #if/else/if/else [0,...
Yes, that's possible: ``` [foo for foo in bar if foo.something] ``` Or in your case: ``` [v * 10 if v < 3 else v * 2 for v in L if v != 3] ``` I's also mentioned in [the docs](http://docs.python.org/tutorial/datastructures.html#list-comprehensions).
How to use Websockets with Pyramid and socket.io?
9,738,009
5
2012-03-16T13:19:20Z
9,742,066
8
2012-03-16T17:46:00Z
[ "javascript", "python", "websocket", "socket.io", "pyramid" ]
I'm trying to create a simple WebSocket application using Pyramid and socket.io frameworks. Server-side code: ``` from pyramid.response import Response from pyramid_socketio.io import SocketIOContext, socketio_manage import gevent def includeme(config): ''' This method is called on the application startup. ...
You probably want to look at the latest release of gevent-socketio, and its documentation at <http://gevent-socketio.readthedocs.org/> A major overhaul was done at the PyCon 2012 sprints, by John Anderson, Sébastien Béal and myself.
DJango POST URL error
9,738,824
6
2012-03-16T14:11:29Z
9,739,046
9
2012-03-16T14:24:08Z
[ "python", "django", "restful-architecture" ]
I am trying to make a REST Api in Django by outputting Json. I am having problems if i make a POST request using curl in terminal. The error i get is > You called this URL via POST, but the URL doesn't end in a slash and > you have APPEND\_SLASH set. Django can't redirect to the slash URL > while maintaining POST data...
For URL consistency, Django has a setting called `APPEND_SLASH`, that always appends a slash to the end of the URL if it wasn't sent that way to begin with. This ensures that `/my/awesome/url/` is always served from that URL instead of both `/my/awesome/url` *and* `/my/awesome/url/`. However, Django does this by autom...
DJango POST URL error
9,738,824
6
2012-03-16T14:11:29Z
9,744,268
8
2012-03-16T20:43:48Z
[ "python", "django", "restful-architecture" ]
I am trying to make a REST Api in Django by outputting Json. I am having problems if i make a POST request using curl in terminal. The error i get is > You called this URL via POST, but the URL doesn't end in a slash and > you have APPEND\_SLASH set. Django can't redirect to the slash URL > while maintaining POST data...
First, make sure that you send the request to `http://127.0.0.1/add/` not `http://127.0.0.1/add`. Secondly, you may also want to exempt the view from csrf processing by adding the [`@csrf_exempt`](https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#django.views.decorators.csrf.csrf_exempt) decorator - since you ar...
Wrap around C++ vector like in Python
9,739,255
2
2012-03-16T14:37:49Z
9,739,290
11
2012-03-16T14:39:53Z
[ "c++", "python", "list", "iterator" ]
I want to "wrap" around a list/vector in C++ like in Python. Basically I want to shift elements from the end of the list to beginning of the list. I don't want to have to explicitly make a new list. In Python I can write something like: ``` my_list = [1, 2, 3, 4, 5] #[1, 2, 3, 4, 5] q = collections.deque(my_list) q....
You are looking for [`std::rotate`](http://www.cplusplus.com/reference/algorithm/rotate/) from the standard library, which offers an easy way to do this with iterators. ``` #include <algorithm> std::vector<T> v /* = populate() */; std::rotate(v.begin(), v.begin() + 3, v.end()); ``` Any forward iterator can be used, ...
Python for loop skipping every other loop?
9,739,407
4
2012-03-16T14:46:37Z
9,739,465
11
2012-03-16T14:49:57Z
[ "python", "django" ]
I have a weird problem. Does anyone see anything wrong with my code? ``` for x in questions: forms.append((SectionForm(request.POST, prefix=str(x.id)),x)) print "Appended " + str(x) for (form, question) in forms: print "Testing " + str(question) if form.is_valid(): forms.remove((form,question))...
You are modifying the contents of the object `forms` that you are iterating over, when you say: ``` forms.remove((form,question)) ``` According to the [Python documentation of the `for` statement](http://docs.python.org/tutorial/controlflow.html), this is not safe (the emphasis is mine): > The for statement in Pytho...
Python - Small Change to a Huge File
9,739,963
5
2012-03-16T15:22:11Z
9,740,093
8
2012-03-16T15:30:06Z
[ "python" ]
This is a theoretical question as I don't have an actual problem, but I got to wondering ... If I had a *huge* file, say many gigs long and I wanted to change a single byte and I knew the offset of that byte, how could I do this efficiently? Is there a way to do this without rewriting the entire file and only writing ...
As long as you don't need to *insert* or *delete* bytes, you can open the file in `"r+"` mode, use the [`seek`](http://docs.python.org/library/stdtypes.html#file.seek) method to position the file object at the byte to change, and write out one byte. It may be more efficient to use the lower-level [`os.open`, `os.lseek...
python: how to generate char by adding int
9,739,992
6
2012-03-16T15:23:35Z
9,740,058
10
2012-03-16T15:27:53Z
[ "python" ]
I can use 'a'+1 to get 'b' in C language, so what the convient way to do this in Python? I can write it like: ``` chr(ord('a')+1) ``` but I don't know whether it is the best way.
Yes, this is the best way. Python doesn't automatically convert between a character and an int the way C and C++ do.
Django static files versions
9,742,428
2
2012-03-16T18:11:10Z
9,742,614
7
2012-03-16T18:25:06Z
[ "python", "django", "static" ]
How do you control version of your static files in Django? I [wrote custom templatetag](https://bitbucket.org/ad3w/django-sstatic/overview) which adds the modification date as GET parameter of file URL, but would like to know - whether I'm doing. Tag code: ``` import os from django import template from django.conf i...
Applications such as [django-compressor](https://github.com/jezdez/django_compressor), and [django-pipeline](https://github.com/cyberdelia/django-pipeline) are good for these sort of things.
Python Regex Split Keeps Split Pattern Characters
9,743,134
6
2012-03-16T19:08:12Z
9,743,235
8
2012-03-16T19:15:41Z
[ "python", "regex" ]
Easiest way to explain this is an example: I have this string: 'Docs/src/Scripts/temp' Which I know how to split two different ways: ``` re.split('/', 'Docs/src/Scripts/temp') -> ['Docs', 'src', 'Scripts', 'temp'] re.split('(/)', 'Docs/src/Scripts/temp') -> ['Docs', '/', 'src', '/', 'Scripts', '/', 'temp'] ``` Is th...
Interesting question, I would suggest doing something like this: ``` >>> 'Docs/src/Scripts/temp'.replace('/', '/\x00/').split('\x00') ['Docs/', '/src/', '/Scripts/', '/temp'] ``` The idea here is to first replace all `/` characters by two `/` characters separated by a special character that would not be a part of the...
Python subprocess in parallel
9,743,838
7
2012-03-16T20:08:18Z
9,745,864
10
2012-03-16T23:40:03Z
[ "python", "subprocess" ]
I want to run many processes in parallel with ability to take stdout in any time. How should I do it? Do I need to run thread for each `subprocess.Popen()` call, a what?
You can do it in a single thread. Suppose you have a script that prints lines at random times: ``` #!/usr/bin/env python #file: child.py import os import random import sys import time for i in range(10): print("%2d %s %s" % (int(sys.argv[1]), os.getpid(), i)) sys.stdout.flush() time.sleep(random.random()...
How do I test sending an email with Django registration on a local computer (Mac 10.7)?
9,744,003
7
2012-03-16T20:22:05Z
9,744,107
8
2012-03-16T20:30:50Z
[ "python", "django", "email", "smtp", "django-registration" ]
I never tried sending emails programmatically before. Do I need to set up a SMTP server on my local machine or something? Or can I use someone else's SMTP server (maybe Gmail's)? Everytime Django registration is trying to send an email I get the error `[Errno 61] Connection refused`. Here is the [traceback](http://dp...
The [basics of email sending](https://docs.djangoproject.com/en/dev/topics/email/) are detailed quite well in the documentation. For development purposes - a [dummy backend](https://docs.djangoproject.com/en/dev/topics/email/#dummy-backend) is provided; it basically acts like a email server so you can validate your ema...
How to convert integer timestamp to Python datetime
9,744,775
67
2012-03-16T21:31:42Z
9,744,811
118
2012-03-16T21:36:05Z
[ "python", "datetime", "timestamp" ]
I have a data file containing timestamps like "1331856000000". Unfortunately, I don't have a lot of documentation for the format, so I'm not sure how the timestamp is formatted. I've tried Python's standard datetime.fromordinal() and datetime.fromtimestamp() and a few others, but nothing matches. I'm pretty sure that p...
`datetime.datetime.fromtimestamp()` is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but `fromtimestamp()` expects Unix timestamp, in seconds. Do it like that: ``` >>> import datetime >>> your_timestamp = 1331856000000 >>> date = datetime.datetime.fromtimestamp(your_timestamp ...
sleekxmpp pubsub example
9,745,908
4
2012-03-16T23:46:32Z
9,746,642
7
2012-03-17T02:09:15Z
[ "python", "xmpp", "publish-subscribe" ]
I am looking for a working example code for implementing SleekXMPP XEP 60 plugin. What i am trying to do is authenticate over TLS and subscribe to a node called "blogupdates" Then simply wait for events and get the data contained in I have searched a few days but I can't find a good working example google or SO note t...
If you look at this thread on the SleekXMPP mailing list ([Beginner - SleekXMPP - XEP-0060](http://groups.google.com/group/sleekxmpp-discussion/browse_thread/thread/9893daf480fe9c60/c954b17616f2d05b?lnk=gst&q=pubsub%20client#c954b17616f2d05b)) I have an example Pubsub client you can experiment with and examine. I'll be...
How do I send a POST request as a JSON?
9,746,303
50
2012-03-17T00:53:49Z
9,746,432
81
2012-03-17T01:19:51Z
[ "python", "json", "http", "url", "post" ]
``` data = { 'ids': [12, 3, 4, 5, 6 , ...] } urllib2.urlopen("http://abc.com/api/posts/create",urllib.urlencode(data)) ``` I want to send a POST request, but one of the fields should be a list of numbers. How can I do that ? (JSON?)
If your server is expecting the POST request to be json, then you would need to add a header, and also serialize the data for your request... ``` import json import urllib2 data = { 'ids': [12, 3, 4, 5, 6] } req = urllib2.Request('http://example.com/api/posts/create') req.add_header('Content-Type', 'applicat...
How do I send a POST request as a JSON?
9,746,303
50
2012-03-17T00:53:49Z
9,746,499
55
2012-03-17T01:33:15Z
[ "python", "json", "http", "url", "post" ]
``` data = { 'ids': [12, 3, 4, 5, 6 , ...] } urllib2.urlopen("http://abc.com/api/posts/create",urllib.urlencode(data)) ``` I want to send a POST request, but one of the fields should be a list of numbers. How can I do that ? (JSON?)
I recommend using the incredible `requests` module. <http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers> ``` url = 'https://api.github.com/some/endpoint' payload = {'some': 'data'} headers = {'content-type': 'application/json'} response = requests.post(url, data=json.dumps(payload), headers=h...
How do I send a POST request as a JSON?
9,746,303
50
2012-03-17T00:53:49Z
26,876,308
13
2014-11-11T23:07:42Z
[ "python", "json", "http", "url", "post" ]
``` data = { 'ids': [12, 3, 4, 5, 6 , ...] } urllib2.urlopen("http://abc.com/api/posts/create",urllib.urlencode(data)) ``` I want to send a POST request, but one of the fields should be a list of numbers. How can I do that ? (JSON?)
for python 3.4.2 I found the following will work: ``` import urllib.request import json body = {'ids': [12, 14, 50]} myurl = "http://www.testmycode.com" req = urllib.request.Request(myurl) req.add_header('Content-Type', 'application/json; charset=utf-8') jsondata = json.dumps(bo...
How can I use sum() function for a list in Python?
9,746,522
7
2012-03-17T01:38:12Z
9,746,543
11
2012-03-17T01:43:45Z
[ "python", "list", "function", "sum" ]
I am doing my homework and it requirers me to use a sum () and len () functions to find the mean of an input number list, when I tried to use sum () to get the sum of the list, I got an error TypeError: unsupported operand type(s) for +: 'int' and 'str'. Following is my code: ``` numlist = input("Enter a list of numbe...
The problem is that when you read from the input, you have a list of strings. You could do something like that as your second line: ``` numlist = [float(x) for x in numlist] ```
Why can't attribute names be Python keywords?
9,746,838
7
2012-03-17T02:51:40Z
9,747,250
7
2012-03-17T04:28:54Z
[ "python", "attributes", "syntax-error" ]
There is a restriction on the syntax of attribute access, in Python (at least in the CPython 2.7.2 implementation): ``` >>> class C(object): pass >>> o = C() >>> o.x = 123 # Works >>> o.if = 123 o.if = 123 ^ SyntaxError: invalid syntax ``` My question is twofold: 1. Is there a fundamental reason why usin...
Because parser is simpler when keywords are always keywords, and not contextual (e.g. `if` is a keyword when on the statement level, but just an identifier when inside an expression — for `if` it'd be double hard because of `X if C else Y`, and `for` is used in list comprehensions and generator expressions). So the ...
Python Spyder reset
9,747,158
7
2012-03-17T04:07:35Z
9,747,804
8
2012-03-17T06:21:06Z
[ "python", "spyder" ]
I was using python(x,y), which came with Spyder. Yesterday, Spyder crashed I can't figure it out how to fix it. I uninstalled python(x,y) and reinstalled, still the same problem. If I try to open Spyder I get this message: ``` Spyder crashed during last session If Spyder does not start at all and before submitting a...
`python` doesn't search `spyder` in the `PATH` e.g.: ``` c:\some\dir> python some_file ``` Here `python` tries to read `c:\some\dir\some_file` file i.e., it looks in the current directory for `some_file` file. ``` c:\some\dir> python another_dir\some_file ``` Here `python` tries to read `c:\some\dir\another_dir\som...
Which is the best way to check for the existence of an attribute?
9,748,678
31
2012-03-17T09:04:46Z
9,748,715
81
2012-03-17T09:10:00Z
[ "python", "attributes" ]
Which is a better way to check for the existence of an attribute? [Jarret Hardie](http://stackoverflow.com/a/610893/647362) provided this answer: ``` if hasattr(a, 'property'): a.property ``` I see that it can also be done this way: ``` if 'property' in a.__dict__: a.property ``` Is one approach typically ...
**There is no "best" way,** because you are never just checking to see if an attribute exists; it is always a part of some larger program. There are several correct ways and one notable incorrect way. # The wrong way ``` if 'property' in a.__dict__: a.property ``` Here is a demonstration which shows this techniq...
Python: WTForms Can I add a placeholder attribute when I init a field?
9,749,742
37
2012-03-17T11:46:01Z
9,783,777
47
2012-03-20T08:54:24Z
[ "python", "wtforms" ]
I want to add a placeholder attribute on to the field in WTForms. How can I do it? ``` abc = TextField('abc', validators=[Required(), Length(min=3, max=30)], placeholder="test") ``` The above code is not valid How can I add a placeholder attribute with value?
*Updated for WTForms 2.1* You can now as of WTForms 2.1 (December 2015) set rendering keywords by using the `render_kw=` parameter to the field constructor. So the field would look like: ``` abc = TextField('abc', validators=[Required(), ...], render_kw={"placeholder": "test"}) ``` Note while this is possible; it d...
How to convert integer into date object python?
9,750,330
7
2012-03-17T13:26:09Z
11,181,425
8
2012-06-24T21:42:00Z
[ "python", "date", "python-2.7" ]
I am creating a module in python, in which I am receiving the date in integer format like `20120213`, which signifies the 13th of Feb, 2012. Now, I want to convert this integer formatted date into a python date object. Also, if there is any means by which I can subtract/add the number of days in such integer formatted...
This question is already answered, but for the benefit of others looking at this question I'd like to add the following suggestion: Instead of doing the slicing yourself as suggested above you might also use strptime() which is (IMHO) easier to read and perhaps the preferred way to do this conversion. ``` import datet...
How to display only a left and bottom box border in matplotlib?
9,750,699
11
2012-03-17T14:21:10Z
9,751,369
25
2012-03-17T15:48:33Z
[ "python", "plot", "matplotlib" ]
I'm trying to plot data in matplotlib. I would like to hide the upper and right parts of the box. Does anyone know how to do this? Thanks for your help
Just set the spines (and/or ticks) to be invisible. E.g. ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) plt.show() ``` ![enter image description here](http://i.stack.imgur.com/6BJN4.png) If you want to hide the ticks on the t...
Opening pdf urls with pyPdf
9,751,197
2
2012-03-17T15:26:48Z
9,751,490
10
2012-03-17T16:05:21Z
[ "python", "pdf", "pypdf" ]
How would I open a pdf from url instead of from the disk Something like ``` input1 = PdfFileReader(file("http://example.com/a.pdf", "rb")) ``` I want to open several files from web and download a merge of all the files.
I think [urllib2](http://docs.python.org/library/urllib2.html) will get you what you want. ``` from urllib2 import Request, urlopen from pyPdf import PdfFileWriter, PdfFileReader from StringIO import StringIO url = "http://www.silicontao.com/ProgrammingGuide/other/beejnet.pdf" writer = PdfFileWriter() remoteFile = u...
List as a member of a python class, why is its contents being shared across all instances of the class?
9,751,554
8
2012-03-17T16:13:18Z
9,751,566
15
2012-03-17T16:15:26Z
[ "python" ]
I have defined a class `Listener` and created a dictionary of `Listener` objects. Each listener has an `id` to identify them, and a list of `artists` they listen to, `artists = []`. Adding something to the `artists` list adds it for all instances of the `Listener` class, rather than the referred instance. This is my pr...
You don't want the members declared inside the class, but just set in the `__init__` method: ``` class Listener: def __init__(self, id): self.id = id self.artists = [] def addArtist(self, artist, plays): print self.id # debugging... print "pre: ", self.artists self.arti...
What's a faster way to look up a value in a list of tuples?
9,752,308
8
2012-03-17T17:47:56Z
9,752,419
8
2012-03-17T18:01:24Z
[ "python", "search", "sorting", "tuples" ]
I'm looking up country by ip range for tens of millions rows. I'm looking for a faster way to do the lookup. I have 180K tuples in this form: ``` >>> data = ((0, 16777215, 'ZZ'), ... (1000013824, 1000079359, 'CN'), ... (1000079360, 1000210431, 'JP'), ... (1000210432, 1000341503, 'JP'), ... ...
You can use the [`bisect`](http://docs.python.org/library/bisect.html) module to perform a binary search after you sorted the dataset: ``` from operator import itemgetter import bisect data = ((0, 16777215, 'ZZ'), (1000013824, 1000079359, 'CN'), (1000079360, 1000210431, 'JP'), (1000210432, 1000341503, 'JP'), (1000341...
How do I get the column names from a row returned from an adodbapi query?
9,752,372
3
2012-03-17T17:55:18Z
9,752,485
9
2012-03-17T18:10:14Z
[ "python", "adodbapi" ]
Suppose I query a database like this : ``` import adodbapi conn = adodbapi.connect(connStr) tablename = "[salesLT].[Customer]" cur = conn.cursor() sql = "select * from %s" % tablename cur.execute(sql) result = cur.fetchall() ``` The result is, I think, a sequence of SQLrow objects. How can I get a list or sequenc...
`cur.description` is a read-only attribute containing 7-tuples that look like: ``` (name, type_code, display_size, internal_size, precision, scale, null_ok) ``` So for column names you might do: ``` col_names = [i[0] for i in cur.description] ``` Reference: <http://www.python.org/dev/peps/pep-0249/>
How can I return two values from a function in Python?
9,752,958
87
2012-03-17T19:18:53Z
9,752,967
15
2012-03-17T19:20:07Z
[ "python", "list", "function", "return", "return-value" ]
I would like to return two values from a function in two separate variables. For example: ``` def select_choice(): loop = 1 row = 0 while loop == 1: print('''Choose from the following options?: 1. Row 1 2. Row 2 3. Row 3''') row = int(inpu...
I think you what you want is a tuple. If you use `return (i, card)`, you can get these two results by: ``` i, card = select_choice() ```
How can I return two values from a function in Python?
9,752,958
87
2012-03-17T19:18:53Z
9,752,970
183
2012-03-17T19:20:34Z
[ "python", "list", "function", "return", "return-value" ]
I would like to return two values from a function in two separate variables. For example: ``` def select_choice(): loop = 1 row = 0 while loop == 1: print('''Choose from the following options?: 1. Row 1 2. Row 2 3. Row 3''') row = int(inpu...
Return a tuple/list (or any other sequence, e.g. `dict`) and unpack it after the call: ``` def select_choice(): ... return i, card # or [i, card] my_i, my_card = select_choice() ``` In the line `return i, card` `i, card` means creating a tuple. You can also put in parenthesis like `return (i, card)`, but th...
How can I return two values from a function in Python?
9,752,958
87
2012-03-17T19:18:53Z
9,753,320
7
2012-03-17T20:11:02Z
[ "python", "list", "function", "return", "return-value" ]
I would like to return two values from a function in two separate variables. For example: ``` def select_choice(): loop = 1 row = 0 while loop == 1: print('''Choose from the following options?: 1. Row 1 2. Row 2 3. Row 3''') row = int(inpu...
``` def test(): .... return r1, r2, r3, .... >> ret_val = test() >> print ret_val (r1, r2, r3, ....) ``` now you can do everything you like with your tuple.
How can I return two values from a function in Python?
9,752,958
87
2012-03-17T19:18:53Z
9,753,477
17
2012-03-17T20:30:30Z
[ "python", "list", "function", "return", "return-value" ]
I would like to return two values from a function in two separate variables. For example: ``` def select_choice(): loop = 1 row = 0 while loop == 1: print('''Choose from the following options?: 1. Row 1 2. Row 2 3. Row 3''') row = int(inpu...
> I would like to return two values from a function in two separate variables. What would you expect it to look like on the calling end? You can't write `a = select_choice(); b = select_choice()` because that would call the function twice. Values aren't returned "in variables"; that's not how Python works. A function...
'gcc' failed with exit status 1 while trying to install gevent-websocket
9,753,835
7
2012-03-17T21:22:45Z
9,754,547
13
2012-03-17T23:00:18Z
[ "python", "websocket", "gevent" ]
I'm trying to install gevent-websocket for Python (http://www.gelens.org/code/gevent-websocket/), but when I run easy\_install gevent-websocket I get "command 'gcc' failed with exit status 1". The following is the full output from the terminal. ``` tgarv@tommy-Studio-1537:~/Desktop/Code$ sudo easy_install gevent-webs...
> ``` > gevent/libevent.h:9: fatal error: event.h: No such file or directory > ``` Install the libevent development package for your distro. Under Ubuntu, it's `libevent-dev`.
pylab matplotlib "show" waits until window closes
9,753,885
11
2012-03-17T21:29:48Z
9,754,238
19
2012-03-17T22:13:06Z
[ "python", "matplotlib" ]
I'd like to have the matplotlib "show" command return to the command line while displaying the plot. Most other plot packages, like R, do this. But pylab hangs until the plot window closes. For example: ``` import pylab x = pylab.arange( 0, 10, 0.1) y = pylab.sin(x) pylab.plot(x,y, 'ro-') pylab.show() # Python hang...
Add `pylab.ion()` ([interactive mode](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.ion)) before the `pylab.show()` call. That will make the UI run in a separate thread and the call to `show` will return immediately.
Most elegant way to count integers in a list
9,754,030
2
2012-03-17T21:45:14Z
9,754,052
8
2012-03-17T21:47:50Z
[ "python" ]
I am looking for the most elegant way to do the following: Let's say that I want to count number of times each integer appears in a list; I could do it this way: ``` x = [1,2,3,2,4,1,2,5,7,2] dicto = {} for num in x: try: dicto[num] = dicto[num] + 1 except KeyError: dicto[num] = 1 ``` Howev...
Use the Counter class ``` >>> from collections import Counter >>> x = [1,2,3,2,4,1,2,5,7,2] >>> c = Counter(x) ``` Now you can use the `Counter` object `c` as dictionary. ``` >>> c[1] 2 >>> c[10] 0 ``` (This works for non-existant values too)
Can I create a shared multiarray or lists of lists object in python for multiprocessing?
9,754,034
7
2012-03-17T21:46:08Z
9,754,423
11
2012-03-17T22:39:42Z
[ "python", "multidimensional-array", "numpy", "multiprocessing" ]
I need to make a shared object of a multidimensional array or list of lists for it to be available to the other processes. Is there a way to create it as for what i have seen it is not possible. I have tried: ``` from multiprocessing import Process, Value, Array arr = Array('i', range(10)) arr[:] [0, 1, 2, 3, 4, 5, 6,...
To make a numpy array a shared object ([full example](http://stackoverflow.com/a/7908612/4279)): ``` import ctypes as c import numpy as np import multiprocessing as mp n, m = 2, 3 mp_arr = mp.Array(c.c_double, n*m) # shared, can be used from multiple processes # then in each new process create a new numpy array using...
Tastypie URLs not configured properly
9,754,499
2
2012-03-17T22:52:29Z
9,754,622
7
2012-03-17T23:12:00Z
[ "python", "django", "tastypie" ]
I get the following error when I try to access <http://localhost:8000/api/goal/?format=json>: ``` ImproperlyConfigured at /api/goal/ The included urlconf <property object at 0x262bb50> doesn't have any patterns in it ``` Here is what I have added to my urls.py: ``` goal_resource = GoalResource ... url(r'^api/'...
You need to call GoalResource, not just bind it's memory address to variable. So change ``` goal_resource = GoalResource ``` to ``` goal_resource = GoalResource() ```
python asynchronous httprequest
9,754,562
3
2012-03-17T23:02:13Z
9,754,814
7
2012-03-17T23:49:32Z
[ "python", "xmlhttprequest" ]
I am trying to use twitter search web service in python. I want to call a web service like: ``` http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&result_type=mixed ``` from my python program. Can anybody tell me 1. how to use xmlhttprequst object in python 2. how to pass parameters t...
You don't need "asynchronous httprequest" to use twitter search api: ``` import json import urllib import urllib2 # make query query = urllib.urlencode(dict(q="blue angel", rpp=5, include_entities=1, result_type="mixed")) # make request resp = urllib2.urlopen("http://search.twitter.com...
Remove object from a list of objects in python
9,754,729
15
2012-03-17T23:32:42Z
9,755,790
38
2012-03-18T03:35:37Z
[ "python", "arrays", "object" ]
In Python, how can I remove an object from array of objects? Like this: ``` x = object() y = object() array = [x,y] # Remove x ``` I've tried `array.remove()` but it only works with a value, not a specific location in the array. I need to be able to delete the object by addressing its position(`remove array[0]`)
In python there are no arrays, lists are used instead. There are various ways to delete an object from a list: ``` my_list = [1,2,4,6,7] del my_list[1] # Removes index 1 from the list print my_list # [1,4,6,7] my_list.remove(4) # Removes the integer 4 from the list, not the index 4 print my_list # [1,6,7] my_list.pop...
How do I create a LIST of unique random numbers?
9,755,538
31
2012-03-18T02:35:16Z
9,755,548
55
2012-03-18T02:37:20Z
[ "python", "random-sample" ]
I tried using `random.randint(0, 100)`, but some numbers were the same. Is there a method/module to create a list unique random numbers? ``` def getScores(): # open files to read and write f1 = open("page.txt", "r"); p1 = open("pgRes.txt", "a"); gScores = []; bScores = []; yScores = []; #...
This will return a list of 10 numbers selected from the range 0 to 99, without duplicates. ``` random.sample(range(100), 10) ``` With reference to your specific code example, you probably want to read all the lines from the file *once* and then select random lines from the saved list in memory. For example: ``` all_...
Why can tuples contain mutable items?
9,755,990
121
2012-03-18T04:26:35Z
9,756,028
135
2012-03-18T04:36:42Z
[ "python", "list", "tuples", "immutability" ]
If a tuple is immutable then why can it contain mutable items? It is seemingly a contradiction that when a mutable item such as a list does get modified, the tuple it belongs to maintains being immutable.
That's an excellent question. The key insight is that tuples have no way of knowing whether the objects inside them are mutable. The only thing that makes an object mutable is to have a method that alters its data. In general, there is no way to detect this. Another insight is that Python's containers don't actually ...
Why can tuples contain mutable items?
9,755,990
121
2012-03-18T04:26:35Z
9,756,041
150
2012-03-18T04:39:24Z
[ "python", "list", "tuples", "immutability" ]
If a tuple is immutable then why can it contain mutable items? It is seemingly a contradiction that when a mutable item such as a list does get modified, the tuple it belongs to maintains being immutable.
That's because tuples *don't* contain lists, strings or numbers. They contain *references to other objects*.[1](http://docs.python.org/3.3/reference/datamodel.html#objects-values-and-types) The inability to change the sequence of references a tuple contains doesn't mean that you can't mutate the objects associated with...
Why can tuples contain mutable items?
9,755,990
121
2012-03-18T04:26:35Z
9,756,061
8
2012-03-18T04:44:45Z
[ "python", "list", "tuples", "immutability" ]
If a tuple is immutable then why can it contain mutable items? It is seemingly a contradiction that when a mutable item such as a list does get modified, the tuple it belongs to maintains being immutable.
You cannot change the `id` of its items. So it will always contain the same items. ``` $ python >>> t = (1, [2, 3]) >>> id(t[1]) 12371368 >>> t[1].append(4) >>> id(t[1]) 12371368 ```
Why can tuples contain mutable items?
9,755,990
121
2012-03-18T04:26:35Z
9,756,087
14
2012-03-18T04:49:33Z
[ "python", "list", "tuples", "immutability" ]
If a tuple is immutable then why can it contain mutable items? It is seemingly a contradiction that when a mutable item such as a list does get modified, the tuple it belongs to maintains being immutable.
First of all, the word "immutable" can mean many different things to different people. I particularly like how Eric Lippert categorized immutability in [his blog post](http://blogs.msdn.com/b/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx). There, he lists these kinds of immutabili...
Why can tuples contain mutable items?
9,755,990
121
2012-03-18T04:26:35Z
9,758,886
14
2012-03-18T14:00:04Z
[ "python", "list", "tuples", "immutability" ]
If a tuple is immutable then why can it contain mutable items? It is seemingly a contradiction that when a mutable item such as a list does get modified, the tuple it belongs to maintains being immutable.
As I understand it, this question needs to be rephrased as a question about design decisions: Why did the designers of Python choose to create an immutable sequence type that can contain mutable objects? To answer this question, we have to think about the purpose [tuples](http://docs.python.org/2/tutorial/datastructur...
Python string slice indices - slice to end of string
9,757,277
5
2012-03-18T09:31:21Z
9,757,282
10
2012-03-18T09:33:25Z
[ "python", "string" ]
With string indices, is there a way to slice to end of string without using len()? Negative indices start from the end, but [-1] omits the final character. ``` word = "Help" word[1:-1] # But I want to grab up to end of string! word[1:len(word)] # Works but is there anything better? ```
You can instead try using: ``` word[1:] ```
Python string slice indices - slice to end of string
9,757,277
5
2012-03-18T09:31:21Z
9,757,302
8
2012-03-18T09:37:45Z
[ "python", "string" ]
With string indices, is there a way to slice to end of string without using len()? Negative indices start from the end, but [-1] omits the final character. ``` word = "Help" word[1:-1] # But I want to grab up to end of string! word[1:len(word)] # Works but is there anything better? ```
Or even: ``` >>> word = "Help" >>> word[-3:] 'elp' ```
Filter max 20 values from a list of integers
9,757,289
4
2012-03-18T09:34:29Z
9,757,306
11
2012-03-18T09:38:43Z
[ "python", "list", "max" ]
I'd like to create a list *maxValues* containing top 20 values from a list of integers *lst*. ``` maxValues = [] for i in range(20): maxValues.append(max(lst)) lst.remove(max(lst)) ``` Is there a more compact code for achieving this task or even built-in function?
There's [`heapq.nlargest()`](http://docs.python.org/py3k/library/heapq.html#heapq.nlargest): ``` maxvalues = heapq.nlargest(20, lst) ``` From the doc: > `heapq.nlargest(n, iterable, key=None)` > > > Return a list with the n largest elements from the dataset defined by `iterable`. `key`, if provided, specifies a func...
Python - Testing an abstract base class
9,757,299
14
2012-03-18T09:37:31Z
9,759,329
10
2012-03-18T14:57:34Z
[ "python", "oop", "testing", "abc" ]
I am looking for ways / best practices on testing methods defined in an abstract base class. One thing I can think of directly is performing the test on all concrete subclasses of the base class, but that seems excessive at some times. Consider this example: ``` import abc class Abstract(object): __metaclass__ ...
As properly put by lunaryon, it is not possible. The very purpose of ABC is that they are not instantiatable. However, it is possible to create a utility function that introspects an ABC, and creates a dummy, non abstract class on the fly. This function could be called directly inside your test method/function and spa...
Python - Testing an abstract base class
9,757,299
14
2012-03-18T09:37:31Z
17,345,619
9
2013-06-27T14:16:13Z
[ "python", "oop", "testing", "abc" ]
I am looking for ways / best practices on testing methods defined in an abstract base class. One thing I can think of directly is performing the test on all concrete subclasses of the base class, but that seems excessive at some times. Consider this example: ``` import abc class Abstract(object): __metaclass__ ...
Here is what I have found: If you set `__abstractmethods__` attribute to be an empty set you'll be able to instantiate abstract class. This behaviour is specified in [PEP 3119](http://www.python.org/dev/peps/pep-3119/#the-abc-module-an-abc-support-framework): > If the resulting `__abstractmethods__` set is non-empty, ...
Python - Testing an abstract base class
9,757,299
14
2012-03-18T09:37:31Z
28,738,073
7
2015-02-26T08:58:21Z
[ "python", "oop", "testing", "abc" ]
I am looking for ways / best practices on testing methods defined in an abstract base class. One thing I can think of directly is performing the test on all concrete subclasses of the base class, but that seems excessive at some times. Consider this example: ``` import abc class Abstract(object): __metaclass__ ...
In newer versions of Python you can use [`unittest.mock.patch()`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch) ``` class MyAbcClassTest(unittest.TestCase): @patch.multiple(MyAbcClass, __abstractmethods__=set()) def test(self): self.instance = MyAbcClass() # Ha! ```
Unicode encoding for filesystem in Mac OS X not correct in Python?
9,757,843
14
2012-03-18T11:13:32Z
9,758,014
21
2012-03-18T11:44:27Z
[ "python", "osx", "unicode", "file-io", "filesystems" ]
Having a bit of struggle with Unicode file names in OS X and Python. I am trying to use filenames as input for a regular expression later in the code, but the encoding used in the filenames seem to be different from what sys.getfilesystemencoding() tells me. Take the following code: ``` #!/usr/bin/env python # coding=...
MacOS X uses a special kind of decomposed UTF-8 to store filenames. If you need to e.g. read in filenames and write them to a "normal" UTF-8 file, you must normalize them : ``` filename = unicodedata.normalize('NFC', unicode(filename, 'utf-8')).encode('utf-8') ``` from here: <http://boodebr.org/main/python/all-about-...
Unicode encoding for filesystem in Mac OS X not correct in Python?
9,757,843
14
2012-03-18T11:13:32Z
9,758,019
13
2012-03-18T11:45:04Z
[ "python", "osx", "unicode", "file-io", "filesystems" ]
Having a bit of struggle with Unicode file names in OS X and Python. I am trying to use filenames as input for a regular expression later in the code, but the encoding used in the filenames seem to be different from what sys.getfilesystemencoding() tells me. Take the following code: ``` #!/usr/bin/env python # coding=...
`getfilesystemencoding()` is giving you the correct response (the *encoding*), but it does not tell you the [unicode normalisation form](http://www.unicode.org/reports/tr15/). In particular, the HFS+ filesystem uses UTF-8 encoding, and a normalisation form close to "D" (which requires composed characters like `ö` to ...
python - Accessing objects mocked with patch
9,757,965
4
2012-03-18T11:35:37Z
9,758,193
7
2012-03-18T12:11:50Z
[ "python", "unit-testing", "testing", "mocking" ]
I've been using the `mock` library to do some of my testing. It's been great so far, but there are some things that I haven't completely understand yet. `mock` provides a nice way of patching an entire method using `patch`, and I could access the patched object in a method like so: ``` @patch('package.module') def te...
In this case, `test_foo` will have an extra argument, the same way as when you decorate the method. If your method is also patched, it those args will be added as well: ``` @patch.object(os, 'listdir') class TestPackage(unittest.TestCase): @patch.object(sys, 'exit') def test_foo(self, sys_exit, os_listdir): ...
Timeout in paramiko (python)
9,758,432
5
2012-03-18T12:49:43Z
9,758,728
20
2012-03-18T13:32:39Z
[ "python", "ssh", "timeout", "scp", "paramiko" ]
I'm looking for a way to set a timeout for this: ``` transport = paramiko.Transport((host, port)) transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) sftp.get(remotepath, localpath) sftp.close() transport.close() ```
I'm a beginner at python. I figured it out: ``` ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=username, password=password, timeout=10) sftp = ssh.open_sftp() sftp.get(remotepath, localpath) sftp.close() ```
Pandas convert dataframe to array of tuples
9,758,450
21
2012-03-18T12:53:06Z
9,762,084
42
2012-03-18T20:39:19Z
[ "python", "pandas" ]
I have manipulated some data using pandas and now I want to carry out a batch save back to the database. This requires me to convert the dataframe into an array of tuples, with each tuple corresponding to a "row" of the dataframe. My DataFrame looks something like: ``` In [182]: data_set Out[182]: index data_date ...
How about: ``` subset = data_set[['data_date', 'data_1', 'data_2']] tuples = [tuple(x) for x in subset.values] ```
Pandas convert dataframe to array of tuples
9,758,450
21
2012-03-18T12:53:06Z
13,731,128
18
2012-12-05T19:42:50Z
[ "python", "pandas" ]
I have manipulated some data using pandas and now I want to carry out a batch save back to the database. This requires me to convert the dataframe into an array of tuples, with each tuple corresponding to a "row" of the dataframe. My DataFrame looks something like: ``` In [182]: data_set Out[182]: index data_date ...
A generic way: ``` [tuple(x) for x in data_set.to_records(index=False)] ```
How can I round up numbers to the next half-integer?
9,758,513
7
2012-03-18T13:01:48Z
9,758,531
19
2012-03-18T13:03:28Z
[ "python", "rounding" ]
In Python `floor()` and `ceil()` round to the next higher or lower integer. How to round up any value between 1.01 - 1.5 to 1.5 and 1.51 - 2.0 to 2.0 etc.?
Multiply by two, `ceil()`, divide by two: ``` 0.5 * ceil(2.0 * x) ```
Python - how to sort a list of numerical values in ascending order
9,758,959
22
2012-03-18T14:06:43Z
9,758,970
17
2012-03-18T14:08:23Z
[ "python", "list", "sorting" ]
I create an sqlite database with has a table storing temperature values. The temperatures are written to the database in ascending order for the first time. Then I read the temperature values from the database into a list and then add that list to a combobox to select temperatures - works fine. The resulting list is, ...
in python `sorted` works like you want with integers: ``` >>> sorted([10,3,2]) [2, 3, 10] ``` it looks like you have a problem because you are using strings: ``` >>> sorted(['10','3','2']) ['10', '2', '3'] ``` (because string ordering starts with the first character, and "1" comes before "2", no matter what charact...
Python - how to sort a list of numerical values in ascending order
9,758,959
22
2012-03-18T14:06:43Z
9,759,042
33
2012-03-18T14:18:28Z
[ "python", "list", "sorting" ]
I create an sqlite database with has a table storing temperature values. The temperatures are written to the database in ascending order for the first time. Then I read the temperature values from the database into a list and then add that list to a combobox to select temperatures - works fine. The resulting list is, ...
The recommended approach in this case is to sort the data in the database, adding an `ORDER BY` at the end of the query that fetches the results, something like this: ``` SELECT temperature FROM temperatures ORDER BY temperature ASC; -- ascending order SELECT temperature FROM temperatures ORDER BY temperature DESC; -...
How to get a list of variables in specific Python module?
9,759,820
9
2012-03-18T16:08:24Z
9,759,842
11
2012-03-18T16:11:20Z
[ "python" ]
Let's assume I have the following file structure: **data.py** ``` foo = [] bar = [] abc = "def" ``` **core.py** ``` import data # do something here # # a = ... print a # ['foo', 'bar', 'abc'] ``` I need to get all the variables defined in data.py file. How can I achieve that? I could use `dir()`, but it returns al...
``` print [item for item in dir(adfix) if not item.startswith("__")] ``` Is usually the recipe for doing this, but it begs the question. # Why?
How to check if an element of a list is a list (in Python)?
9,759,930
34
2012-03-18T16:22:47Z
9,759,963
67
2012-03-18T16:26:45Z
[ "python" ]
If we have the following list: ``` list = ['UMM', 'Uma', ['Ulaster','Ulter']] ``` If I need to find out if an element in the list is itself a list, what can I replace *aValidList* in the following code with? ``` for e in list: if e == aValidList: return True ``` Is there a special import to use? Is ther...
Use [`isinstance`](http://docs.python.org/library/functions.html#isinstance): ``` if isinstance(e, list): ``` If you want to check that an object is a list or a tuple, pass several classes to `isinstance`: ``` if isinstance(e, (list, tuple)): ```
How to check if an element of a list is a list (in Python)?
9,759,930
34
2012-03-18T16:22:47Z
9,760,003
17
2012-03-18T16:29:43Z
[ "python" ]
If we have the following list: ``` list = ['UMM', 'Uma', ['Ulaster','Ulter']] ``` If I need to find out if an element in the list is itself a list, what can I replace *aValidList* in the following code with? ``` for e in list: if e == aValidList: return True ``` Is there a special import to use? Is ther...
1. Work out what specific properties of a `list` you want the items to have. Do they need to be indexable? Sliceable? Do they need an `.append()` method? 2. Look up the abstract base class which describes that particular type in the [`collections`](http://docs.python.org/library/collections.html#collections-abstract-ba...
How do you extract a url from a string using python?
9,760,588
3
2012-03-18T17:41:24Z
9,760,660
12
2012-03-18T17:48:48Z
[ "python", "string", "url", "extract" ]
For example: ``` string = "This is a link http://www.google.com" ``` How could I extract 'http://www.google.com' ? (Each link will be of the same format i.e 'http://')
There may be few ways to do this but the cleanest would be to use regex ``` >>> myString = "This is a link http://www.google.com" >>> print re.search("(?P<url>https?://[^\s]+)", myString).group("url") http://www.google.com ``` If there can be multiple links you can use something similar to below ``` >>> myString = "...
Accessing parent class attribute from sub-class body
9,760,595
15
2012-03-18T17:41:54Z
9,760,696
8
2012-03-18T17:53:27Z
[ "python", "python-3.x" ]
I have a class `Klass` with a class attribute `my_list`. I have a subclass of it `SubKlass`, in which i want to have a class attribute `my_list` which is a modified version of the same attribute from parent class: ``` class Klass(): my_list = [1, 2, 3] class SubKlass(Klass): my_list = Klass.my_list + [4, 5] ...
You can't. A class definition works in Python works as follows. 1. The interpreter sees a `class` statement followed by a block of code. 2. It creates a new namespace and executes that code in the namespace. 3. It calls the `type` builtin with the resulting namespace, the class name, the base classes, and the metacla...
How to list only regular files (excluding directories) under a directory in Python
9,760,771
3
2012-03-18T18:01:39Z
9,760,855
7
2012-03-18T18:10:48Z
[ "python", "filesystems" ]
One can use `os.listdir('somedir')` to get all the files under `somedir`. However, if what I want is just regular files (excluding directories) like the result of `find . -type f` under shell. I know one can use `[path for path in os.listdir('somedir') if not os.path.isdir('somedir/'+path)]` to achieve similar result ...
You could use [`os.walk`](http://docs.python.org/library/os.html#os.walk), which returns a tuple of path, folders and files: ``` files = next(os.walk('somedir'))[2] ```
dict.get() - default arg evaluated even upon success
9,761,396
8
2012-03-18T19:12:10Z
9,761,421
13
2012-03-18T19:14:51Z
[ "python", "dictionary" ]
Why is the default in [`dict.get(key[, default])`](http://docs.python.org/library/stdtypes.html#dict.get) evaluated even if the key is in the dictionary? ``` >>> key = 'foo' >>> a={} >>> b={key:'bar'} >>> b.get(key, a[key]) Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> b.get(key, a[k...
As in any function call, the arguments are evaluated before the call is executed. In this case `dict.get()` is no exception...
Add indexed column to DataFrame with pandas
9,762,935
11
2012-03-18T22:34:26Z
9,772,031
17
2012-03-19T14:30:06Z
[ "python", "pandas" ]
I'm a beginning pandas user, and after studying the documentation I still can't find a straightforward way to do the following. I have a DataFrame with a pandas.DateRange index, and I want to add a column with values for part of the same DateRange. Suppose I have ``` df A B 2010-...
Do `df.join(df2)`: <http://pandas.pydata.org/pandas-docs/stable/merging.html#joining-on-index>
Parse a tuple from a string?
9,763,116
16
2012-03-18T23:03:53Z
9,763,133
39
2012-03-18T23:05:48Z
[ "python", "python-2.7" ]
Say I have a string that's of the same form a tuple should be, for example, `"(1,2,3,4,5)"`. What's the easiest way to convert that into an actual tuple? An example of what I want to do is: ``` tup_string = "(1,2,3,4,5)" tup = make_tuple(tup_string) ``` Just running `tuple()` on the string make the whole thing one bi...
It [already exists](http://docs.python.org/dev/library/ast.html#ast.literal_eval)! ``` >>> from ast import literal_eval as make_tuple >>> make_tuple("(1,2,3,4,5)") (1, 2, 3, 4, 5) ``` Be aware of the corner-case, though: ``` >>> make_tuple("(1)") 1 >>> make_tuple("(1,)") (1,) ``` If your input format works differen...
How to get the infinitive form of the verb using NLTK (pos tagging)
9,763,393
6
2012-03-18T23:51:44Z
9,764,418
12
2012-03-19T02:52:49Z
[ "python", "nltk", "part-of-speech" ]
I'm trying to learn natural language processing (of English) using NLTK and Python. Is there a way to get the infinitive form of the verb during or after POS-tagging. For example: * is (VBZ) => to be * provided (VBN) => to provide * using (VBG) => to use
Close, you'll need to add the 'to' at the beginning: ``` >>> from nltk.stem.wordnet import WordNetLemmatizer >>> lemmatizer = WordNetLemmatizer() >>> lemmatizer.lemmatize('is', 'v') 'be' >>> lemmatizer.lemmatize('provided', 'v') 'provide' >>> lemmatizer.lemmatize('using', 'v') 'use' ```
Is it possible to sort two lists(which reference each other) in the exact same way?
9,764,298
37
2012-03-19T02:35:10Z
9,764,359
8
2012-03-19T02:44:33Z
[ "python" ]
Okay, this may not be the smartest idea but I was a bit curious if this is possible. Say I have two lists: ``` list1 = [3,2,4,1, 1] list2 = [three, two, four, one, one2] ``` If I run `list1.sort()`, it'll sort it to `[1,1,2,3,4]` but is there a way to get to keep list2 in sync as well(so I can say item 4 belongs to '...
[Schwartzian transform](http://en.wikipedia.org/wiki/Schwartzian_transform). The built-in Python sorting is stable, so the two `1`s don't cause a problem. ``` >>> l1 = [3, 2, 4, 1, 1] >>> l2 = ['three', 'two', 'four', 'one', 'second one'] >>> zip(*sorted(zip(l1, l2))) [(1, 1, 2, 3, 4), ('one', 'second one', 'two', 'th...
Is it possible to sort two lists(which reference each other) in the exact same way?
9,764,298
37
2012-03-19T02:35:10Z
9,764,364
71
2012-03-19T02:45:11Z
[ "python" ]
Okay, this may not be the smartest idea but I was a bit curious if this is possible. Say I have two lists: ``` list1 = [3,2,4,1, 1] list2 = [three, two, four, one, one2] ``` If I run `list1.sort()`, it'll sort it to `[1,1,2,3,4]` but is there a way to get to keep list2 in sync as well(so I can say item 4 belongs to '...
One classic approach to this problem is to use the "decorate, sort, undecorate" idiom, which is especially simple using python's built-in `zip` function: ``` >>> list1 = [3,2,4,1, 1] >>> list2 = ['three', 'two', 'four', 'one', 'one2'] >>> list1, list2 = zip(*sorted(zip(list1, list2))) >>> list1 (1, 1, 2, 3, 4) >>> lis...
Is it possible to sort two lists(which reference each other) in the exact same way?
9,764,298
37
2012-03-19T02:35:10Z
9,764,390
10
2012-03-19T02:48:50Z
[ "python" ]
Okay, this may not be the smartest idea but I was a bit curious if this is possible. Say I have two lists: ``` list1 = [3,2,4,1, 1] list2 = [three, two, four, one, one2] ``` If I run `list1.sort()`, it'll sort it to `[1,1,2,3,4]` but is there a way to get to keep list2 in sync as well(so I can say item 4 belongs to '...
You can sort indexes using values as keys: ``` indexes = range(len(list1)) indexes.sort(key=list1.__getitem__) ``` To get sorted lists given sorted indexes: ``` sorted_list1 = map(list1.__getitem__, indexes) sorted_list2 = map(list2.__getitem__, indexes) ``` In your case you shouldn't have `list1`, `list2` but rath...
Runtime Error with Vim Omnicompletion
9,764,341
16
2012-03-19T02:42:20Z
10,257,098
22
2012-04-21T07:21:34Z
[ "python", "vim", "autocomplete", "runtime-error" ]
I was trying to use Vim's omnicompletion with my Python code, but whenever I try C-x + C-o, it prompts the following error message: > Runtime Error! > > Program E:\Vim\vim73\gvim.exe > > R6034 > An application has made an attempt to load the C runtime library incorrectly. > Please contact the application's support tea...
I have the same issue which cause by gvim not able to load python pyd dll. There are some tips to solve the .pyd dll which cause the above issue. I'm not sure is there any way to solve the Runtime Error for all dll. Refere to [Not embed the correct manifest for the msvc runtimes on windows](http://code.google.com/p/pyo...
C/C++ Python interpreter
9,764,451
2
2012-03-19T02:57:55Z
9,764,462
8
2012-03-19T03:00:03Z
[ "c++", "python", "c", "interpreter" ]
What I'm trying to do is write an app in C/C++ which will allow users to enter a Python script, which the app will then interpret & run. The aforementioned script will have a separate API that I'll implement in C, then expose to the user. Is there a way to do this? I've searched on Google, but I've only found ways to ...
Documentation about [Embedding Python in Another Application](http://docs.python.org/extending/embedding.html) says: > The previous chapters discussed how to extend Python, that is, how to extend the functionality of Python by attaching a library of C functions to it. **It is also possible to do it the other way aroun...
Updating weight information depending on repeat of edges with networkx
9,764,603
8
2012-03-19T03:21:07Z
9,853,591
11
2012-03-24T16:57:17Z
[ "python", "duplicates", "edge", "networkx", "weight" ]
I have a JSON feed data with lots of user relation in it such as: ``` "subject_id = 1, object_id = 2, object = added subject_id = 1, object_id = 2, object = liked subject_id = 1, object_id = 3, object = added subject_id = 2, object_id = 1, object = added" ``` Now I've used following code to convert JSON to networkx ...
You can simply use the `weight` attribute store your weights. You can check if an edge exists with `has_edge` method. Combining these would give you: ``` def load(fname): G = nx.DiGraph() d = simplejson.load(open(fname)) for item in d: for attribute, value in item.iteritems(): subject_i...
Capturing repeating subpatterns in Python regex
9,764,930
12
2012-03-19T04:09:09Z
9,765,390
15
2012-03-19T05:22:44Z
[ "python", "regex" ]
While matching an email address, after I match something like `yasar@webmail`, I want to capture one or more of `(\.\w+)`(what I am doing is a little bit more complicated, this is just an example), I tried adding (.\w+)+ , but it only captures last match. For example, `yasar@webmail.something.edu.tr` matches but only i...
`re` module doesn't support repeated captures ([`regex`](http://pypi.python.org/pypi/regex) supports it): ``` >>> m = regex.match(r'([.\w]+)@((\w+)(\.\w+)+)', 'yasar@webmail.something.edu.tr') >>> m.groups() ('yasar', 'webmail.something.edu.tr', 'webmail', '.tr') >>> m.captures(4) ['.something', '.edu', '.tr'] ``` In...
Python: IOError: [Errno 2] No such file or directory
9,765,227
13
2012-03-19T05:01:12Z
9,765,314
17
2012-03-19T05:13:30Z
[ "python" ]
I am very new to Python so please forgive the following basic code and problem, but I have been trying to figure out what is causing the error I am getting (I have even looked at similar threads on S.O.) but can't get past my issue. Here is what I am trying to do: * loop through a folder of CSV files * search for a '...
Hmm, there are a few things going wrong here. ``` for f in os.listdir(src_dir): os.path.join(src_dir, f) ``` You're not storing the result of `join`. This should be something like: ``` for f in os.listdir(src_dir): f = os.path.join(src_dir, f) ``` This open call is is the cause of your `IOError`. (Because w...
Python: IOError: [Errno 2] No such file or directory
9,765,227
13
2012-03-19T05:01:12Z
9,765,319
9
2012-03-19T05:14:02Z
[ "python" ]
I am very new to Python so please forgive the following basic code and problem, but I have been trying to figure out what is causing the error I am getting (I have even looked at similar threads on S.O.) but can't get past my issue. Here is what I am trying to do: * loop through a folder of CSV files * search for a '...
Even though @Ignacio gave you a straightforward solution, I thought I might add an answer that gives you some more details about the issues with your code... ``` # You are not saving this result into a variable to reuse os.path.join(src_dir, f) # Should be src_path = os.path.join(src_dir, f) # you open the file but y...