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
What is the proper way to format a multi-line dict in Python?
6,388,187
93
2011-06-17T15:35:51Z
6,388,237
117
2011-06-17T15:39:53Z
[ "python", "indentation", "code-formatting", "multiline" ]
In Python, I want to write a multi-line dict in my code. There are a couple of ways one could format it. Here are a few that I could think of: 1. ``` mydict = { "key1": 1, "key2": 2, "key3": 3, } ``` 2. ``` mydict = { "key1": 1, "key2": 2, "key3": 3, ...
I use #3. Same for long lists, tuples, etc. It doesn't require adding any extra spaces beyond the indentations. As always, be consistent. ``` mydict = { "key1": 1, "key2": 2, "key3": 3, } mylist = [ (1, 'hello'), (2, 'world'), ] nested = { a: [ (1, 'a'), (2, 'b'), ], b...
What is the proper way to format a multi-line dict in Python?
6,388,187
93
2011-06-17T15:35:51Z
6,389,593
9
2011-06-17T17:40:06Z
[ "python", "indentation", "code-formatting", "multiline" ]
In Python, I want to write a multi-line dict in my code. There are a couple of ways one could format it. Here are a few that I could think of: 1. ``` mydict = { "key1": 1, "key2": 2, "key3": 3, } ``` 2. ``` mydict = { "key1": 1, "key2": 2, "key3": 3, ...
Since your keys are strings and since we are talking about readability, I prefer : ``` mydict = dict( key1 = 1, key2 = 2, key3 = 3, ) ```
What is the proper way to format a multi-line dict in Python?
6,388,187
93
2011-06-17T15:35:51Z
13,761,377
14
2012-12-07T10:36:14Z
[ "python", "indentation", "code-formatting", "multiline" ]
In Python, I want to write a multi-line dict in my code. There are a couple of ways one could format it. Here are a few that I could think of: 1. ``` mydict = { "key1": 1, "key2": 2, "key3": 3, } ``` 2. ``` mydict = { "key1": 1, "key2": 2, "key3": 3, ...
First of all, like Steven Rumbalski said, "PEP8 doesn't address this question", so it is a matter of personal preference. I would use a similar but not identical format as your format 3. Here is mine, and why. ``` my_dictionary = { # Don't think dict(...) notation has more readability "key1": 1, # Indent by one p...
Perl's Pack('V') function in Python?
6,389,576
7
2011-06-17T17:38:16Z
6,389,623
10
2011-06-17T17:42:28Z
[ "python", "perl", "exploit", "pack", "shellcode" ]
I've been working on some exploit development recently to get ready for a training course, and I've run into a problem with a tutorial. I've been following along with all the tutorials I can find, using Python as opposed to the language the tutorials used, out of preference. I'm trying to crosscode everything, but I ca...
Try using the `"L<"` pack template instead of `"V"`. This should work in Perl and Python both. `N` and `V` are an older Perl method of specifying endianness, and `<` and `>` are the newer method. It looks like when Python borrowed `pack` from Perl it only took the newer, more flexible interface. *Edit:* Python wants t...
Perl's Pack('V') function in Python?
6,389,576
7
2011-06-17T17:38:16Z
6,389,624
7
2011-06-17T17:42:34Z
[ "python", "perl", "exploit", "pack", "shellcode" ]
I've been working on some exploit development recently to get ready for a training course, and I've run into a problem with a tutorial. I've been following along with all the tutorials I can find, using Python as opposed to the language the tutorials used, out of preference. I'm trying to crosscode everything, but I ca...
Python's `struct.pack` uses the first character for the [endianess/size variation](http://docs.python.org/library/struct.html#byte-order-size-and-alignment), and then one or more for the [data type](http://docs.python.org/library/struct.html#format-characters). Perl's `V` [means](http://perldoc.perl.org/functions/pack....
Merge two arrays into a matrix in python and sort
6,389,577
5
2011-06-17T17:38:17Z
6,389,626
9
2011-06-17T17:42:47Z
[ "python", "arrays", "sorting", "matrix" ]
Ok, this is a very easy question for which I could not find the solution here; I have two lists A and B ``` A=(0,1,2,3,...,N-1) (N elements) B=(-50,-30,-10,.....,-45) (N elements) ``` I would like to create a new structure, kind of a 2D matrix "C" with 2xN elements so that ``` C(0)=(0,-50) C(1)=(1,-30) ... C(N)=(N...
``` C = zip(A, B) D = sorted(C, key=lambda x: x[1]) A2, B2 = zip(*D) ``` Or all on one line: ``` A2, B2 = zip(*sorted(zip(A,B), key=lambda x: x[1])) ```
Quick and easy: trayicon with python?
6,389,580
23
2011-06-17T17:38:34Z
6,389,727
45
2011-06-17T17:50:37Z
[ "python", "wxpython", "pyqt", "systray", "tray" ]
I'd just need a quick example on how to easily put an icon with python on my systray. This means: I run the program, no window shows up, just a tray icon (I've got a png file) shows up in the systray and when I right-click on it a menu appears with some options (and when I click on an option, a function is run). Is tha...
## For Windows & Gnome Here ya go! wxPython is the bomb. Adapted from the source of my [Feed Notifier](http://www.feednotifier.com/) application. ``` import wx TRAY_TOOLTIP = 'System Tray Demo' TRAY_ICON = 'icon.png' def create_menu_item(menu, label, func): item = wx.MenuItem(menu, -1, label) menu.Bind(wx....
How do I see the Django debug toolbar?
6,390,310
20
2011-06-17T18:43:29Z
6,390,524
39
2011-06-17T19:00:57Z
[ "python", "django", "django-debug-toolbar" ]
I have a Django webapp. I have installed the debug\_toolbar middleware and module. However, my webapps don't have the debug toolbar pull-out. How do I actually see the debug toolbar? Is there something more I need to do? Do I need to use a particular template for my webapp? I have followed all the steps in the README,...
1. As I know your HTML page must contain closed body tag, meta tag with `content="text/html"`. 2. I prefer the way when all debug-toolbar's settings separed from main settings. So try put in the end of settings.py something like ``` #debug_toolbar settings if DEBUG: INTERNAL_IPS = ('127.0.0.1',) ...
Matplotlib make tick labels font size smaller
6,390,393
102
2011-06-17T18:49:28Z
6,390,584
53
2011-06-17T19:06:04Z
[ "python", "matplotlib" ]
In a matplotlib figure, how can I make the font size for the tick labels using `ax1.set_xticklabels()` smaller? Further, how can one rotate it from horizontal to vertical?
Please note that newer versions of MPL have a shortcut for this task. An example is shown in the other answer to this question: <http://stackoverflow.com/a/11386056/42346> The code below is for illustrative purposes and may not necessarily be optimized. ``` import matplotlib.pyplot as plt import numpy as np def xtic...
Matplotlib make tick labels font size smaller
6,390,393
102
2011-06-17T18:49:28Z
11,386,056
198
2012-07-08T19:37:46Z
[ "python", "matplotlib" ]
In a matplotlib figure, how can I make the font size for the tick labels using `ax1.set_xticklabels()` smaller? Further, how can one rotate it from horizontal to vertical?
There is a simpler way actually. I just found: ``` import pylab as pl # We prepare the plot fig = pl.figure(1) # We define a fake subplot that is in fact only the plot. plot = fig.add_subplot(111) # We change the fontsize of minor ticks label plot.tick_params(axis='both', which='major', labelsize=10) plot.tick_p...
Matplotlib make tick labels font size smaller
6,390,393
102
2011-06-17T18:49:28Z
30,245,556
22
2015-05-14T19:18:45Z
[ "python", "matplotlib" ]
In a matplotlib figure, how can I make the font size for the tick labels using `ax1.set_xticklabels()` smaller? Further, how can one rotate it from horizontal to vertical?
Alternatively, you can just do: ``` import matplotlib as mpl label_size = 8 mpl.rcParams['xtick.labelsize'] = label_size ```
How to prevent decompilation or inspecting python code?
6,390,489
3
2011-06-17T18:57:53Z
6,390,534
8
2011-06-17T19:01:30Z
[ "python", "decompiling", "inspect" ]
let us assume that there is a big, commercial project (a.k.a Project), which uses Python under the hood to manage plugins for configuring new control surfaces which can be attached and used by Project. There was a small information leak, some part of the Project's Python API leaked to the public information and people...
No, this does not solve the problem. Someone could just rename the inspect module to something else and import it. What you're trying to do is not possible. The python interpreter must be able to take your bytecode and execute it. Someone will always be able to decompile the bytecode. They will always be able to produ...
How to prevent decompilation or inspecting python code?
6,390,489
3
2011-06-17T18:57:53Z
6,390,790
7
2011-06-17T19:25:19Z
[ "python", "decompiling", "inspect" ]
let us assume that there is a big, commercial project (a.k.a Project), which uses Python under the hood to manage plugins for configuring new control surfaces which can be attached and used by Project. There was a small information leak, some part of the Project's Python API leaked to the public information and people...
There is no way to keep your application code an absolute secret. Frankly, if a group of dedicated and determined hackers (in the good sense, not in the pejorative sense) can crack the PlayStation's code signing security model, then your app doesn't stand a chance. Once you put your app into the hands of someone outsi...
How to grab numbers in the middle of a string? (Python)
6,390,651
8
2011-06-17T19:12:14Z
6,390,674
7
2011-06-17T19:14:40Z
[ "python", "regex" ]
``` random string this is 34 the string 3 that, i need 234 random string random string random string random string random string this is 1 the string 34 that, i need 22 random string random string random string random string random string this is 35 the string 55 that, i need 12 random string random string random str...
Use regular expressions: ``` >>> import re >>> comp_re = re.compile('this is (\d+) the string (\d+) that, i need (\d+)') >>> s = """random string this is 34 the string 3 that, i need 234 random string random string random string random string random string this is 1 the string 34 that, i need 22 random string random ...
SimpleHTTPRequestHandler Override do_GET
6,391,280
2
2011-06-17T20:13:58Z
6,391,433
8
2011-06-17T20:28:03Z
[ "python" ]
I want to extend SimpleHTTPRequestHandler and override the default behavior of `do_GET()`. I am returning a string from my custom handler but the client doesn't receive the response. Here is my handler class: ``` DUMMY_RESPONSE = """Content-type: text/html <html> <head> <title>Python Test</title> </head> <body> Tes...
Something like (untested code): ``` def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Content-length", len(DUMMY_RESPONSE)) self.end_headers() self.wfile.write(DUMMY_RESPONSE) ```
python check if utf-8 string is uppercase
6,391,442
7
2011-06-17T20:29:20Z
6,399,065
9
2011-06-18T21:44:15Z
[ "python", "unicode", "utf-8" ]
I am having trouble with .isupper() when I have a utf-8 encoded string. I have a lot of text files I am converting to xml. While the text is very variable the format is static. words in all caps should be wrapped in `<title>` tags and everything else `<p>`. It is considerably more complex then this, but this should be ...
The primary reason that your published code fails (even with only ascii characters!) is that **re.split() will not split on a zero-width match**. `r'\b'` matches zero characters: ``` >>> re.split(r'\b', 'foo-BAR_baz') ['foo-BAR_baz'] >>> re.split(r'\W+', 'foo-BAR_baz') ['foo', 'BAR_baz'] >>> re.split(r'[\W_]+', 'foo-B...
Nested Python class needs to access variable in enclosing class
6,391,645
11
2011-06-17T20:47:42Z
6,392,112
7
2011-06-17T21:36:43Z
[ "python", "scope", "nested-class" ]
I've seen a few "solutions" to this, but the solution every time seems to be "Don't use nested classes, define the classes outside and then use them normally". I don't like that answer, because it ignores the primary reason I chose nested classes, which is, to have a pool of constants (associated with the base class) a...
You don't need two classes here. Here's your example code written in a more concise fashion. ``` class ChildClass: def __init__(self, stream): idx = stream.read_ui16() self.name = self.constant_pool[idx] def makeChildren(stream): ChildClass.constant_pool = ConstantPool(stream) return [Chil...
Nested Python class needs to access variable in enclosing class
6,391,645
11
2011-06-17T20:47:42Z
6,392,595
10
2011-06-17T22:53:04Z
[ "python", "scope", "nested-class" ]
I've seen a few "solutions" to this, but the solution every time seems to be "Don't use nested classes, define the classes outside and then use them normally". I don't like that answer, because it ignores the primary reason I chose nested classes, which is, to have a pool of constants (associated with the base class) a...
Despite my "bit patronizing" comment (fair play to call it that!), there are actually ways to achieve what you want: a different avenue of inheritance. A couple: 1. Write a decorator that introspects a class just after it's declared, finds inner classes, and copies attributes from the outer class into them. 2. Do the ...
Check if a variable's type is primitive
6,391,694
17
2011-06-17T20:52:51Z
6,392,016
24
2011-06-17T21:24:44Z
[ "python" ]
maybe this question is a bit stupid but I don't know how to check if a variable is primitive. In java it's like this: ``` if var.isPrimitive(): ``` Thank you.
Since there are no primitive types in Python, you yourself must define what you consider primitive: ``` primitive = (int, str, bool, ...) def is_primitive(thing): return isinstance(thing, primitive) ``` But then, do you consider this primitive, too: ``` class MyStr(str): ... ``` ? If not, you could do thi...
Check if a variable's type is primitive
6,391,694
17
2011-06-17T20:52:51Z
6,392,976
15
2011-06-18T00:06:23Z
[ "python" ]
maybe this question is a bit stupid but I don't know how to check if a variable is primitive. In java it's like this: ``` if var.isPrimitive(): ``` Thank you.
In Python, everything is an object; even ints and bools. So if by 'primitive' you mean "not an object" (as I think the word is used in Java), then there are no such types in Python. If you want to know if know if a given value (remember, in Python variables do not have type, only values do) is an int, float, bool or w...
Check if a variable's type is primitive
6,391,694
17
2011-06-17T20:52:51Z
18,922,399
9
2013-09-20T17:19:22Z
[ "python" ]
maybe this question is a bit stupid but I don't know how to check if a variable is primitive. In java it's like this: ``` if var.isPrimitive(): ``` Thank you.
As every one says, there is no primitive types in python. But I believe, this is what you want. ``` def isPrimitive(obj): return not hasattr(obj, '__dict__') isPrimitive(1) => True isPrimitive("sample") => True isPrimitive(213.1311) => True isPrimitive({}) => True isPrimitive([]) => True isPrimitive(()) => True ...
What does the at (@) symbol do in Python
6,392,739
204
2011-06-17T23:19:30Z
6,392,768
116
2011-06-17T23:23:44Z
[ "python" ]
I'm looking at some Python code which used the `@` symbol, but I have no idea what it does. I also do not know what to search for as searching python docs or Google does not return relevant results when the `@` symbol is included.
The `@` symbol is used for class, function and method *decorators*. Read more here: [PEP 318: Decorators](http://www.python.org/dev/peps/pep-0318/) [Python Decorators](http://wiki.python.org/moin/PythonDecorators) The most common Python decorators you'll run into are: [@property](http://docs.python.org/library/fun...
What does the at (@) symbol do in Python
6,392,739
204
2011-06-17T23:19:30Z
14,799,490
72
2013-02-10T15:47:31Z
[ "python" ]
I'm looking at some Python code which used the `@` symbol, but I have no idea what it does. I also do not know what to search for as searching python docs or Google does not return relevant results when the `@` symbol is included.
This code snippet: ``` def decorator(func): return func @decorator def some_func(): pass ``` Is equivalent to this code: ``` def decorator(func): return func def some_func(): pass some_func = decorator(some_func) ``` In the definition of decorator you can add some modified things that wouldn't be ...
What does the at (@) symbol do in Python
6,392,739
204
2011-06-17T23:19:30Z
15,839,702
122
2013-04-05T17:15:18Z
[ "python" ]
I'm looking at some Python code which used the `@` symbol, but I have no idea what it does. I also do not know what to search for as searching python docs or Google does not return relevant results when the `@` symbol is included.
## Preamble I admit it took more than a few moments to fully grasp this concept for me, so I'll share what I've learned to save others the trouble. The name **decorator** - the thing we define using the `@` syntax before a function definition - was probably the main culprit here. ## Example ``` class Pizza(object):...
What does the at (@) symbol do in Python
6,392,739
204
2011-06-17T23:19:30Z
28,997,112
21
2015-03-11T20:51:38Z
[ "python" ]
I'm looking at some Python code which used the `@` symbol, but I have no idea what it does. I also do not know what to search for as searching python docs or Google does not return relevant results when the `@` symbol is included.
In python3.5 you can overload `@` as an operator. It is named as `__matmul__` because It is designed to do matrix multiplication, but It can be anything you want. see [PEP465](http://www.python.org/dev/peps/pep-0465/) for details. This is a simple implementation of matrix multiplication. ``` class Mat(list) : def...
Why should you lock threads?
6,393,073
5
2011-06-18T00:27:58Z
6,393,126
11
2011-06-18T00:41:44Z
[ "python", "multithreading", "locking", "thread-safety" ]
I've read a lot of examples on locking threads.. but why should you lock them? From my understanding, when you initiate threads without joining them, they will compete with the main thread and all other threads for resources and then execute, sometimes simultaneously, sometimes not. Does locking ensure that threads DO...
A lock allows you to force multiple threads to access a resource one at a time, rather than all of them trying to access the resource simultaneously. As you note, usually you do want threads to execute simultaneously. However, imagine that you have two threads and they are both writing to the same file. If they try to...
Why should you lock threads?
6,393,073
5
2011-06-18T00:27:58Z
6,393,556
9
2011-06-18T02:57:21Z
[ "python", "multithreading", "locking", "thread-safety" ]
I've read a lot of examples on locking threads.. but why should you lock them? From my understanding, when you initiate threads without joining them, they will compete with the main thread and all other threads for resources and then execute, sometimes simultaneously, sometimes not. Does locking ensure that threads DO...
First, locks are designed to protect resources; threads aren't 'locked' or 'unlocked' they /acquire/ a lock (on a resource) and /release/ a lock (on a resource). You are correct that you want threads to run concurrently as much as possible, but let's take a look at this: ``` y=10 def doStuff( x ): global y a...
Testing a RESTful API with POSTs from Python
6,393,122
9
2011-06-18T00:40:40Z
6,393,288
21
2011-06-18T01:27:51Z
[ "python", "api", "http" ]
I'm trying to test a RESTful interface I'm working on (I'm using this one: [codeigniter-restserver](http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/)), and I'd like to use Python. `GET`s seem to be working okay, but I'm having trouble with `POST`s. I'm not asking about the ins & ou...
writing directly to `httplib` is fine, but rather low level. check out the [Requests](http://python-requests.org) module. It is a very simple and pythonic approach to crafting and sending http requests. ``` import requests requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None) ```
ValueError: invalid literal for int() with base 10
6,393,635
3
2011-06-18T03:18:16Z
6,393,697
8
2011-06-18T03:37:59Z
[ "python" ]
I made a program where the user enters a number, and the program would count up to that number and display how much time it took. However, whenever I enter letters or decimals (i.e. 0.5), I would get a error. Here is the full error message: ``` Traceback (most recent call last): File "C:\Documents and Settings\Usern...
Well, there really a way to 'fix' this, it is behaving as expected -- you can't case a letter to an int, that doesn't really make sense. Your best bet (and this is a pythonic way of doing things), is to simply write a function with a try... except block: ``` def get_user_number(): i = input("Enter a number.\n") ...
How python deals with module and package having the same name?
6,393,861
25
2011-06-18T04:26:14Z
6,393,913
12
2011-06-18T04:35:46Z
[ "python", "import", "module", "package" ]
Suppose I have a module `foo.py` and a package `foo/`. If I call ``` import foo ``` which one will be loaded? How can I specify I wand to load the module, or the package?
I believe the package will always get loaded. You can't work around this, as far as I know. So change either the package or the module name. Docs: <http://docs.python.org/tutorial/modules.html#the-module-search-path>
How python deals with module and package having the same name?
6,393,861
25
2011-06-18T04:26:14Z
11,028,558
7
2012-06-14T07:29:35Z
[ "python", "import", "module", "package" ]
Suppose I have a module `foo.py` and a package `foo/`. If I call ``` import foo ``` which one will be loaded? How can I specify I wand to load the module, or the package?
Actually, it is possible (this code is not well tested, but seems to work). File `foo.py` ``` print "foo module loaded" ``` File `foo/__init__.py` ``` print "foo package loaded" ``` File `test1.py` ``` import foo ``` File `test2.py` ``` import os, imp def import_module(dir, name): """ load a module (not a ...
celery task and customize decorator
6,393,879
11
2011-06-18T04:29:49Z
15,229,240
14
2013-03-05T16:36:12Z
[ "python", "django", "decorator", "celery", "django-celery" ]
I'm working on a project using django and celery(django-celery). Our team decided to wrap all data access code within `(app-name)/manager.py`(NOT wrap into Managers like the `django` way), and let code in (app-name)/task.py only dealing with assemble and perform tasks with celery(so we don't have django ORM dependency ...
Not quite sure why passing arguments won't work? if you use this example: ``` @task() def add(x, y): return x + y ``` lets add some logging to the MyCoolTask: ``` from celery import task from celery.registry import tasks import logging import celery logger = logging.getLogger(__name__) class MyCoolTask(celer...
Very basic Python question (strings, formats and escapes)
6,394,170
6
2011-06-18T05:52:13Z
6,394,318
15
2011-06-18T06:29:09Z
[ "python", "string" ]
I am starting to learn Python with an online guide, and I just did an exercise that required me to write this script: ``` from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") ...
The guide is suggesting creating a single string and writing it out rather than calling`write()` six time which seems like good advice. You've got three options. You could concatentate the strings together like this: ``` line1 + "\n" + line2 + "\n" + line3 + "\n" ``` or like this: ``` "\n".join(line1,line2,line3) ...
Only one command line option with argparse
6,394,328
3
2011-06-18T06:30:28Z
6,394,459
14
2011-06-18T07:08:41Z
[ "python", "argparse" ]
I'm trying to create a CLI with the argparse module but I'd like to have different commands with different argument requirements, I tried this: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument('foo', help='foo help') parser.add_argument('test', nargs=1, help='test help') args = parser.parse_a...
[@crodjer](http://stackoverflow.com/questions/6394328/only-one-command-line-option-with-argparse/6394419#6394419) is correct; to provide an example: ``` import argparse parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(title='subcommands', description='valid su...
Python functools.wraps equivalent for classes
6,394,511
36
2011-06-18T07:20:10Z
6,394,966
16
2011-06-18T09:03:03Z
[ "python", "decorator" ]
When defining a decorator using a class, how do I automatically transfer over`__name__`, `__module__` and `__doc__`? Normally, I would use the @wraps decorator from functools. Here's what I did instead for a class (this is not entirely my code): ``` class memoized: """Decorator that caches a function's return valu...
I'm not aware of such things in stdlib, but we can create our own if we need to. Something like this can work : ``` from functools import WRAPPER_ASSIGNMENTS def class_wraps(cls): """Update a wrapper class `cls` to look like the wrapped.""" class Wrapper(cls): """New wrapper that will extend the wr...
Python functools.wraps equivalent for classes
6,394,511
36
2011-06-18T07:20:10Z
17,705,456
19
2013-07-17T16:36:15Z
[ "python", "decorator" ]
When defining a decorator using a class, how do I automatically transfer over`__name__`, `__module__` and `__doc__`? Normally, I would use the @wraps decorator from functools. Here's what I did instead for a class (this is not entirely my code): ``` class memoized: """Decorator that caches a function's return valu...
Everyone seems to have missed the obvious solution. ``` >>> import functools >>> class memoized(object): """Decorator that caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned, and not re-evaluated. """ def __init__(self, fun...
yield break in Python
6,395,063
25
2011-06-18T09:21:20Z
6,395,088
18
2011-06-18T09:26:04Z
[ "python", "generator", "yield" ]
according to answer to this [question](http://stackoverflow.com/questions/1704607/difference-between-yield-in-python-and-yield-in-c), yield break in C# is equivalent to return in python. in normal case, 'return' indeed stop a generator. But if your function does nothing but return, you will get a None not an empty iter...
``` def generate_nothing(): return yield ```
yield break in Python
6,395,063
25
2011-06-18T09:21:20Z
14,190,039
30
2013-01-07T04:47:23Z
[ "python", "generator", "yield" ]
according to answer to this [question](http://stackoverflow.com/questions/1704607/difference-between-yield-in-python-and-yield-in-c), yield break in C# is equivalent to return in python. in normal case, 'return' indeed stop a generator. But if your function does nothing but return, you will get a None not an empty iter...
A good way to handle this is raising [StopIteration](http://docs.python.org/2/library/exceptions.html#exceptions.StopIteration) which is what is raised when your iterator has nothing left to yield and `next()` is called. This will also gracefully break out of a for loop with nothing inside the loop executed. For examp...
Scala: recursively modify lists of elements/lists
6,395,119
2
2011-06-18T09:34:17Z
6,395,577
11
2011-06-18T11:13:18Z
[ "python", "scala", "recursion" ]
I was hoping someone could provide me with some basic code help in Scala. I've written some demo code in Python. Consider a list of elements, where an element can hold either an integer or a list of other elements. I'd like to recursively examine this structure and modify it while keeping the overall structure. To re...
I would rather not call that a List of List, as that does not tell what those lists contains. The structure is a tree, more precisely a leafy tree, where there are data only in the leaves. That would be : ``` sealed trait Tree[+A] case class Node[+A](children: Tree[A]*) extends Tree[A] case class Leaf[+A](value: A) ex...
Finding minimum value in an array of dicts
6,395,716
2
2011-06-18T11:39:26Z
6,395,729
8
2011-06-18T11:41:50Z
[ "python" ]
I have an array like the following: ``` people = [{'node': 'john', 'dist': 3}, {'node': 'mary', 'dist': 5}, {'node': 'alex', 'dist': 4}] ``` I want to compute the minimum of all the 'dist' keys. For instance, in the above example, the answer would be 3. I wrote the following code: ``` min = 99...
Use the [`min`](http://docs.python.org/library/functions.html#min) function: ``` minimum = min(e['dist'] for e in people) # Don't call the variable min, that would overshadow the built-in min function print ('minimum is ' + str(minimum)) ```
Any way to speed up Python and Pygame?
6,395,923
8
2011-06-18T12:15:23Z
6,396,117
11
2011-06-18T12:48:59Z
[ "python", "performance", "pygame", "fps" ]
I am writing a simple top down rpg in Pygame, and I have found that it is quite slow.... Although I am not expecting python or pygame to match the FPS of games made with compiled languages like C/C++ or event Byte Compiled ones like Java, But still the current FPS of pygame is like 15. I tried rendering 16-color Bitmap...
Use Psyco, for python2: ``` import psyco psyco.full() ``` Also, enable doublebuffering. For example: ``` from pygame.locals import * flags = FULLSCREEN | DOUBLEBUF screen = pygame.display.set_mode(resolution, flags, bpp) ``` You could also turn off alpha if you don't need it: ``` screen.set_alpha(None) ``` Instea...
Connecting to MS Access 2007 (.accdb) database using pyodbc
6,396,429
8
2011-06-18T13:42:07Z
6,401,525
13
2011-06-19T09:05:55Z
[ "python", "ms-access", "64bit", "pyodbc" ]
I am on Win7 x64, using Python 2.7.1 x64. I am porting an application I created in VC++ to Python for educational purpouses. The original application has no problem connecting to the MS Access 2007 format DB file by using the following connection string: `OleDbConnection^ conn = gcnew OleDbConnection("Provider=Micr...
1. Try to use something like the following instead of using the same string as the one for OLeDb: `"Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\DB.accdb;"` 2. You may not be able to talk to the driver directly from your x64 Python application: Access 2007 and its ACE driver are 32 bits only. Inst...
Python derived class and base class attributes?
6,396,452
8
2011-06-18T13:45:02Z
6,396,839
26
2011-06-18T14:58:55Z
[ "python", "class", "inheritance", "attributes", "derived" ]
There seems to be no good online documentation on this: If I make a derived class, will it automatically have all the attributes of the base class? But what's the `BaseClass.__init()` for, do you also need to do it to other base class methods? Does `BaseClass.__init__()` need arguments? If you have arguments for your b...
If you implement `__init__` in a class derived from BaseClass, then it will overwrite the inherited `__init__` method and so `BaseClass.__init__` will never be called. If you need to call the `__init__` method for BaseClass (as is normally the case), then its up to you to do that, and its done explicitly by calling `Ba...
How do you get the encoding of the terminal from within a python script?
6,396,659
8
2011-06-18T14:24:56Z
6,396,717
15
2011-06-18T14:37:50Z
[ "python", "encoding", "terminal" ]
Let's say you want to start a python script with some parameters like ``` python myscript some arguments ``` I understand, that the strings `sys.argv[1]` and `sys.argv[2]` will have the encoding specified in the terminal. Is there a way to get this information from within the python script? My goal is something like...
`sys.stdout.encoding` will give you the encoding of standard output. `sys.stdin.encoding` will give you the encdoing for standard input.
How do I get auto-suggestions for array options when typing in Vim?
6,396,880
11
2011-06-18T15:05:32Z
6,396,978
7
2011-06-18T15:22:13Z
[ "python", "vim", "autocomplete", "intellisense" ]
![enter image description here](http://i.stack.imgur.com/e6l21.png) Let's say I type ``` a = [1, 2] ``` in a .py file in vim and when I type "a." and hit TAB, I would like to get suggestion menu that is related to lists. Edit 1 in response to Robin's comment: I think it's possible in vim, because there is a plugin ...
Recent versions of vim come with an omnicompletion script called pythoncomplete. Open up a python file, and type ``` :set completefunc? ``` to check what the current completion function is. If you get back ``` completefunc= ``` then no completionfunction is currently set. You can set pythoncomplete to be the compl...
How do I configure PyCharm to run py.test tests?
6,397,063
42
2011-06-18T15:37:12Z
6,397,315
61
2011-06-18T16:23:50Z
[ "python", "pycharm", "py.test" ]
I want to start writing unit tests for my Python code, and the [py.test](http://pytest.org/) framework sounds like a better bet than Python's bundled [unittest](http://docs.python.org/library/unittest.html). So I added a "tests" directory to my project, and added [test\_sample.py](http://doc.pytest.org/en/latest/gettin...
Please go to Settings | Python Integrated Tools and change the default test runner to py.test. Then you'll get the py.test option to create tests instead of the unittest one.
Unmap of NumPy memmap
6,397,495
7
2011-06-18T16:54:42Z
6,398,543
7
2011-06-18T19:59:14Z
[ "python", "numpy", "mmap" ]
I can't find any documentation on how numpy handles **unmapping** of previously memory mapped regions: `munmap` for `numpy.memmap()` and `numpy.load(mmap_mode)`. My guess is it's done only at garbage collection time, is that correct?
Yes, it's only closed when the object is garbage-collected; `memmap.close` method does nothing. You can call `x._mmap.close()`, but keep in mind that any further access to the `x` object will crash python.
I'm completly confused with PyObject, PyGTK and GNOME 3 as well
6,397,755
12
2011-06-18T17:42:27Z
6,408,533
8
2011-06-20T08:25:39Z
[ "python", "pygtk", "gnome", "pygobject" ]
I installed Fedora 15 to use Python3 and GObject to develop a desktop-application, because PyGTK looks outdated: > PyGTK 2.24.0 released > Friday 01 April 2011 by Rafael Villar Burke > PyGTK 2.24.0 has been released. This is a stable release supporting the GTK+ 2.24 API. > **New users wishing to develop Python applica...
**Update:** there is a bit of documentation here: [The Python GTK+ 3 Tutorial](http://python-gtk-3-tutorial.readthedocs.org/en/latest/index.html). It's still missing anything to do with GIO, etc. It's not... er, impossible... but because you're talking about the latest generation of GTK (&co) bindings, things are boun...
Windows progress bar in python's Tkinter
6,398,437
5
2011-06-18T19:38:38Z
6,398,533
7
2011-06-18T19:57:30Z
[ "python", "windows", "progress-bar", "tkinter", "python-2.6" ]
Is there any way in python's Tkinter, bwidget or anything similar to show a Windwos' default progress bar? I already know the bwidget.ProgressBar, but it produces an ugly progress bar while I mean showing a valid windows progress bar - the green, glowing one: <http://imageshack.us/photo/my-images/853/unledtph.png/> I...
If you are using a modern (2.7+) version of Tkinter you can try the [ttk.ProgressBar](http://docs.python.org/dev/library/tkinter.ttk.html#tkinter.ttk.Progressbar) which is part of Tkinter.
Getting started with Twitter\OAuth2\Python
6,399,978
24
2011-06-19T01:24:36Z
6,807,182
85
2011-07-24T13:53:24Z
[ "python", "twitter", "oauth" ]
I'm attempting to connect to twitter using python, and I'm finding it really frustrating. Everything I read suggests that I need a consumer key, a consumer secret, an access key and an access secret - for example: [Using python OAUTH2 to access OAUTH protected resources](http://parand.com/say/index.php/2010/06/13/us...
Almost all oauth examples on blogs seem to be examples of the authorisation phase of oauth and none focus on how to actually make requests once you have these, as once you understand how it works this part is quite obvious. Getting that initial understanding is quite difficult unfortunately. If you're just trying acce...
Figure out if a business name is very similar to another one - Python
6,400,416
8
2011-06-19T03:52:47Z
6,401,068
18
2011-06-19T06:58:05Z
[ "python", "edit-distance", "similarity" ]
I'm working with a large database of businesses. I'd like to be able to compare two business names for similarity to see if they possibly might be duplicates. Below is a list of business names that should test as having a high probability of being duplicates, what is a good way to go about this? ``` George Washingto...
I've recently done a similar task, although I was matching new data to existing names in a database, rather than looking for duplicates within one set. Name matching is actually a well-studied task, with a number of factors beyond what you'd consider for matching generic strings. First, I'd recommend taking a look at ...
Using "Counter" in Python 3.2
6,400,538
6
2011-06-19T04:27:53Z
6,400,562
13
2011-06-19T04:32:08Z
[ "python", "python-3.x" ]
I've been trying to use the Counter in 3.2 but I'm not sure if I'm trying to use it properly. Any idea why I'm getting the error? ``` >>> import collections >>> Counter() Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> Counter() NameError: name 'Counter' is not defined ``` I can seem ...
You want `from collections import Counter`. Using `import collections` only makes the stuff in collections available as collections.*something*. More on modules and the workings of `import` in the first few sections of [this tutorial chapter](http://docs.python.org/py3k/tutorial/modules.html).
How do I pass a fraction to python as an exponent in order to calculate the nth root of an integer?
6,401,167
3
2011-06-19T07:31:39Z
6,401,264
9
2011-06-19T08:06:06Z
[ "python", "math", "fractions" ]
I'm attempting to write a simple python script that will calculate the squareroot of a number. heres the code i've come up with and it works. but i would like to learn how to use fractional exponents instead. ``` var1 = input('Please enter number:') var1 = int(var1) var2 = var1**(.5) print(var2) ``` thanks for the h...
You can use fractional exponents with the help of `fractions` module. In this module there is a class `Fraction` which works similar to our inbuilt `int` class. Here is a link to the documentation of the class - <http://docs.python.org/library/fractions.html> (just go through its first few examples to understand how...
Using different versions of python with virtualenvwrapper
6,401,951
11
2011-06-19T10:55:25Z
10,534,684
13
2012-05-10T13:09:47Z
[ "python", "virtualenvwrapper" ]
I've got various versions of python installed on my Mac using Macports. When I've selected python 2.7 via `$ port select python python27`, virtualenvwrapper works perfectly. But if I select another version of python, i.e. 2.6, virtualenvwrapper generates an error message: ImportError: No module named virtualenvwrapper...
I know this is pretty much solved in your comments, but it's mac only, and even more I think the correct way should be to set `VIRTUALENVWRAPPER_PYTHON` to the real python you are using on the command line. To be sure you can do `which python`. Actually, you can even do: ``` export VIRTUALENVWRAPPER_PYTHON=`which p...
Python conditional assignment operator
6,402,311
21
2011-06-19T12:21:11Z
6,402,327
16
2011-06-19T12:23:45Z
[ "python", "variables", "conditional" ]
Does a Python equivalent to the Ruby `||=` operator ("set the variable if the variable is not set") exist? Example in Ruby : ``` variable_not_set ||= 'bla bla' variable_not_set == 'bla bla' variable_set = 'pi pi' variable_set ||= 'bla bla' variable_set == 'pi pi' ```
No, the replacement is: ``` try: v except NameError: v = 'bla bla' ``` However, wanting to use this construct is a sign of overly complicated code flow. Usually, you'd do the following: ``` try: v = complicated() except ComplicatedError: # complicated failed v = 'fallback value' ``` and never be unsure ...
Python conditional assignment operator
6,402,311
21
2011-06-19T12:21:11Z
6,640,034
62
2011-07-10T08:21:28Z
[ "python", "variables", "conditional" ]
Does a Python equivalent to the Ruby `||=` operator ("set the variable if the variable is not set") exist? Example in Ruby : ``` variable_not_set ||= 'bla bla' variable_not_set == 'bla bla' variable_set = 'pi pi' variable_set ||= 'bla bla' variable_set == 'pi pi' ```
I'm surprised no one offered this answer. It's not as "built-in" as Ruby's `||=` but it's basically equivalent and still a one-liner: ``` foo = foo if 'foo' in locals() else 'default' ``` Of course, locals() is just a dictionary, so you can do: ``` foo = locals().get('foo', 'default') ```
Python conditional assignment operator
6,402,311
21
2011-06-19T12:21:11Z
11,475,887
7
2012-07-13T18:03:52Z
[ "python", "variables", "conditional" ]
Does a Python equivalent to the Ruby `||=` operator ("set the variable if the variable is not set") exist? Example in Ruby : ``` variable_not_set ||= 'bla bla' variable_not_set == 'bla bla' variable_set = 'pi pi' variable_set ||= 'bla bla' variable_set == 'pi pi' ```
I would use ``` x = 'default' if not x else x ``` Much shorter than all of your alternatives suggested here, and straight to the point. Read, "set x to 'default' if x is not set otherwise keep it as x." If you need `None`, `0`, `False`, or `""` to be valid values however, you will need to change this behavior, for in...
How to get to a new line in Python Shell?
6,402,781
8
2011-06-19T13:59:20Z
11,993,793
20
2012-08-16T19:04:38Z
[ "python" ]
In IDLE, say i want to write the following in TWO lines: ``` x = 3 print x**5 ``` but when i type x = 3 and press enter, it executes the assignment. How to let it execute AFTER two lines are all typed in? having read first pages of Python tutorial but no answer to this "funny" question...
Use the `Ctrl`-`J` key sequence instead of the `Enter` key to get a plain newline plus indentation without having IDLE start interpreting your code. You can find other key sequences that make IDLE easier to use for this type of learning under the `Options->Configure` IDLE menu.
How to convert an H:MM:SS time string to seconds in Python?
6,402,812
17
2011-06-19T14:05:11Z
6,402,859
21
2011-06-19T14:11:43Z
[ "python" ]
Basically I have the inverse of this problem: [Python Time Seconds to h:m:s](http://stackoverflow.com/questions/775049/python-time-seconds-to-hms) I have a string in the format H:MM:SS (always 2 digits for minutes and seconds), and I need the integer number of seconds that it represents. How can I do this in python? ...
``` def get_sec(time_str): h, m, s = time_str.split(':') return int(h) * 3600 + int(m) * 60 + int(s) print get_sec('1:23:45') print get_sec('0:04:15') print get_sec('0:00:25') ```
How to convert an H:MM:SS time string to seconds in Python?
6,402,812
17
2011-06-19T14:05:11Z
6,402,934
21
2011-06-19T14:22:29Z
[ "python" ]
Basically I have the inverse of this problem: [Python Time Seconds to h:m:s](http://stackoverflow.com/questions/775049/python-time-seconds-to-hms) I have a string in the format H:MM:SS (always 2 digits for minutes and seconds), and I need the integer number of seconds that it represents. How can I do this in python? ...
``` t = "1:23:45" print(sum(int(x) * 60 ** i for i,x in enumerate(reversed(t.split(":"))))) ``` The current example, elaborated: ``` 45 × 60⁰ = 45 × 1 = 45 23 × 60¹ = 23 × 60 = 1380 1 × 60² = 1 × 3600 = 3600 ```
filter map vs list comprehension
6,402,824
6
2011-06-19T14:07:18Z
6,402,856
8
2011-06-19T14:11:23Z
[ "python" ]
Is filter/map equivalent to list comprehension? Suppose I have the following function ``` def fib_gen(): a,b = 0,1 yield 0 yield 1 while True: a,b = b,a+b yield b ``` Now I can use list comprehension to list fib numbers: ``` a = fib_gen() print [a.next() for i in range(int(sys.argv[1]...
You could use a generator to store the intermediate result, and "filter" on it. ``` fibs = (a.next() for i in whatever) even_fibs = [num for num in fibs if num % 2 == 0] ``` or in one line: ``` even_fibs = [num for num in (a.next() for i in whatever) if num % 2 == 0] ``` Note that, if you want to take a definite nu...
filter map vs list comprehension
6,402,824
6
2011-06-19T14:07:18Z
6,402,901
12
2011-06-19T14:17:28Z
[ "python" ]
Is filter/map equivalent to list comprehension? Suppose I have the following function ``` def fib_gen(): a,b = 0,1 yield 0 yield 1 while True: a,b = b,a+b yield b ``` Now I can use list comprehension to list fib numbers: ``` a = fib_gen() print [a.next() for i in range(int(sys.argv[1]...
> Is filter/map equivalent to list comprehension? Yes, `map(f, L)` is equivalent to `[f(x) for x in L]`. `filter(f, L)` is equivalent to `[x for x in L if f(x)]`. But, since list comprehensions with side effects are generally bad (and here you modify the state of the generator), you can use [`itertools`](http://docs.p...
Python - run through a loop in non linear fashion
6,403,607
4
2011-06-19T16:25:23Z
6,403,640
9
2011-06-19T16:31:25Z
[ "python", "list", "for-loop" ]
SO, I am searching for a way to loop through a list of items in a for loop fashion, except I want the loop to iterate in a 'random' way. i.e. I dont want the loop to go 0,1,2,3,m+1...n, I want it to pick it in some random order and still run through the loop for all items. Here is my current looping code: ``` for sin...
If listOfItems can be shuffled, then ``` import random random.shuffle(listOfItems) for singleSelectedItem in listOfItems: blahblah ``` otherwise ``` import random randomRange = range(len(listOfItems)) random.shuffle(randomRange) for i in randomRange: singleSelectedItem = listOfItems[i] blahblah ``` Edit...
Error installing PyCurl
6,403,757
6
2011-06-19T16:52:38Z
6,403,976
11
2011-06-19T17:29:23Z
[ "python", "pycurl" ]
I urgently need help. I tried installing pycurl via pip. it didn't work and instead it gives me this error. Anything I can do? Any hints? ``` running install running build running build_py running build_ext building 'pycurl' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall...
I got it working using this ``` sudo env ARCHFLAGS="-arch x86_64" pip install pycurl ```
string insertion in big file
6,404,962
6
2011-06-19T20:32:24Z
6,404,969
8
2011-06-19T20:34:26Z
[ "python", "file" ]
I have big file (few GBs) with text. For example, it have next text: ``` Hello, World! ``` I need to insert word " funny" at 5 position, and offset the rest of text: ``` Hello, funny World! ``` How I can don't read all file for offsetting rest? Or how I can optimise this operation? Thanks.
You can't. Plain text files cannot be shrunk or expanded in the beginning or middle of the file, but only at the end.
How to convert numeric string ranges to a list in Python
6,405,208
12
2011-06-19T21:28:28Z
6,405,228
18
2011-06-19T21:32:19Z
[ "python", "list", "string" ]
I would like to be able to convert a string such as "1,2,5-7,10" to a python list such as [1,2,5,6,7,10]. I looked around and found [this](http://stackoverflow.com/questions/2668107), but I was wondering if there is a clean and simple way to do this in Python.
``` >>> def f(x): ... result = [] ... for part in x.split(','): ... if '-' in part: ... a, b = part.split('-') ... a, b = int(a), int(b) ... result.extend(range(a, b + 1)) ... else: ... a = int(part) ... result.append(a) ... return ...
Get a list from a set in python
6,405,512
30
2011-06-19T22:37:22Z
6,405,514
41
2011-06-19T22:38:14Z
[ "python", "list", "set" ]
Ho do I get the contents of a `set()` in `list[]` form in Python? I need to do this because I need to save the collection in Google App Engine and Entity property types can be lists, but not sets. I know I can just iterate over the whole thing, but it seems like there should be a short-cut, or "best practice" way to d...
``` >>> s = set([1, 2, 3]) >>> list(s) [1, 2, 3] ``` Note that the list you get doesn't have a defined order.
Get a list from a set in python
6,405,512
30
2011-06-19T22:37:22Z
6,405,602
45
2011-06-19T23:04:20Z
[ "python", "list", "set" ]
Ho do I get the contents of a `set()` in `list[]` form in Python? I need to do this because I need to save the collection in Google App Engine and Entity property types can be lists, but not sets. I know I can just iterate over the whole thing, but it seems like there should be a short-cut, or "best practice" way to d...
See Sven's answer, but I would use the `sorted()` function instead: that way you get the elements in a nice predictable order (so you can compare the lists afterwards, for example). ``` >>> s = set([1, 2, 3, 4, 5]) >>> sorted(s) [1, 2, 3, 4, 5] ``` Of course, the set elements have to be sortable for this to work. You...
Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks
6,406,368
42
2011-06-20T02:36:48Z
6,406,750
77
2011-06-20T04:13:36Z
[ "python", "matplotlib", "graphing" ]
*Nb: You may need to open the PNGs below directly - Right Click on the image, then View Image (in FF), or Open image in new tab (Chrome). The image resize done by SO has rendered them nigh unreadable...lol.* I'm using Matplotlib to plot a histogram. Using tips from my previous question: [Matplotlib - label each bin]...
use labelpad parameter: ``` pl.xlabel("...", labelpad=20) ``` or set it after: ``` ax.xaxis.labelpad = 20 ```
Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks
6,406,368
42
2011-06-20T02:36:48Z
25,018,490
7
2014-07-29T14:57:09Z
[ "python", "matplotlib", "graphing" ]
*Nb: You may need to open the PNGs below directly - Right Click on the image, then View Image (in FF), or Open image in new tab (Chrome). The image resize done by SO has rendered them nigh unreadable...lol.* I'm using Matplotlib to plot a histogram. Using tips from my previous question: [Matplotlib - label each bin]...
If the variable ax.xaxis.\_autolabelpos = True, matplotlib sets the label position in function \_update\_label\_position in axis.py according to (some excerpts): ``` bboxes, bboxes2 = self._get_tick_bboxes(ticks_to_draw, renderer) bbox = mtransforms.Bbox.union(bboxes) bottom = bbox.y0 x, y = self.label...
Decorators versus inheritance
6,406,446
11
2011-06-20T02:59:21Z
6,406,580
14
2011-06-20T03:31:50Z
[ "python", "inheritance", "decorator" ]
How do you decide between using decorators and inheritance when both are possible? E.g., [this problem](http://stackoverflow.com/questions/6394511/python-functools-wraps-equivalent-for-classes) has two solutions. I'm particularly interested in Python.
Decorators...: * ...should be used if what you are trying to do is "wrapping". Wrapping consists of taking something, modifying (or registering it with something), and/or returning a proxy object that behaves "almost exactly" like the original. * ...are okay for applying mixin-like behavior, as long as you aren't crea...
How to pass List as an argument to a function in threading.Timer
6,406,748
2
2011-06-20T04:12:48Z
6,407,489
8
2011-06-20T06:19:34Z
[ "python" ]
How to pass a list as an argument to function in `threading.Timer(...)` ? Please see the following code. I would like to pass nb[] as an argument ``` nb=['192.168.1.2', '192.168.1.3', '192.168.1.4'] ping_thread = threading.Timer(12.0, pingstarter, nb,) ping_thread.start() ``` pingstarter is a funciton and taking argu...
The problem is simple: you need to pass the list argument `nb` to `threading.Timer()` as the single element of a sequence (I usually use a tuple, note the trailing comma **inside** the parentheses): ``` threading.Timer(12.0, pingstarter, (nb,)) ``` ...or, a list ``` threading.Timer(12.0, pingstarter, [nb]) ``` Why?...
What happens when I omit the brackets when trying to catch multiple exceptions?
6,407,079
3
2011-06-20T05:18:12Z
6,407,169
7
2011-06-20T05:33:40Z
[ "python", "exception" ]
I just tried writing this: ``` try: # do something except ValueError, IndexError: # do something else ``` And then got very confused when my program still threw an `IndexError` because I thought I was catching it. If it doesn't catch the `IndexError`, what exactly does this code do? It doesn't seem to be a s...
Because this mistake/problem is so common, the syntax changes for Python3. You code would be equivalent to ``` try: # do something except (ValueError, ) as IndexError: # do something else ``` You would have seen that this is obviously wrong. The new syntax works back as far as Python2.6 This works ok ``` t...
How can I check if a date is the same day as datetime.today()?
6,407,362
29
2011-06-20T06:01:25Z
6,407,378
13
2011-06-20T06:04:06Z
[ "python" ]
``` if date_num_posts < datetime.datetime.today(): ``` is always true even if it's the same day because it is comparing time. How can I check if a date is the same day as datetime.today()?
* If you need to compare only day of month value than you can use the following code: ``` if yourdate.day == datetime.today().day: # do something ``` * If you need to check that the difference between two dates is acceptable then you can use [timedelta](http://docs.python.org/release/2.6.6/library/dateti...
How can I check if a date is the same day as datetime.today()?
6,407,362
29
2011-06-20T06:01:25Z
6,407,393
63
2011-06-20T06:06:08Z
[ "python" ]
``` if date_num_posts < datetime.datetime.today(): ``` is always true even if it's the same day because it is comparing time. How can I check if a date is the same day as datetime.today()?
If you want to just compare dates, ``` yourdatetime.date() < datetime.today().date() ``` Or, obviously, ``` yourdatetime.date() == datetime.today().date() ``` If you want to check that they're *the same* date. [The documentation](http://docs.python.org/library/datetime.html) is usually helpful. It is also usually ...
How to extract data from JSON Object in Python?
6,407,780
4
2011-06-20T06:56:27Z
6,407,798
9
2011-06-20T06:58:46Z
[ "python", "json", "simplejson", "tweepy" ]
I am trying to extract data from JSON Object which is returned from the api call for api.trends() [Tweepy] but I am not able to extract the data. Can anyone give me an example of how to extract data from JSON object. I want to extract the data in tabular form. Thanks in advance.
Once you run it though `json.loads()` it becomes normal Python objects. Simply index it as you would any dict or list. ``` >>> json.loads('{"foo": 42, "bar": "baz"}')[u'bar'] u'baz' ```
How to memoize **kwargs?
6,407,993
17
2011-06-20T07:22:06Z
6,408,008
7
2011-06-20T07:24:21Z
[ "python", "memoization" ]
I haven't seen an established way to memoize a function that takes key-word arguments, i.e. something of type ``` def f(*args, **kwargs) ``` since typically a memoizer has a `dict` to cache results for a given set of input parameters, and `kwargs` is a `dict` and hence unhashable. I have tried, following discussions ...
dicts can be in arbitrary order, so there's no guarantee that the latter will work. Use `sorted(kwargs.items())` to get it sorted by key first.
How to memoize **kwargs?
6,407,993
17
2011-06-20T07:22:06Z
6,408,175
10
2011-06-20T07:46:10Z
[ "python", "memoization" ]
I haven't seen an established way to memoize a function that takes key-word arguments, i.e. something of type ``` def f(*args, **kwargs) ``` since typically a memoizer has a `dict` to cache results for a given set of input parameters, and `kwargs` is a `dict` and hence unhashable. I have tried, following discussions ...
``` key = (args, frozenset(kwargs.items()) ``` This is the "best" you can do without making assumptions about your data. However it seems conceivable to want to perform memoization on dictionaries (a bit unusual though), you could special-case that if you desired it. For example you could recursively apply `frozenset...
Index a SciPy sparse matrix with an array of booleans
6,408,385
8
2011-06-20T08:08:46Z
6,408,525
9
2011-06-20T08:24:40Z
[ "python", "indexing", "numpy", "scipy", "sparse-matrix" ]
NumPy arrays can be indexed with an array of booleans to select the rows corresponding to `True` entries: ``` >>> X = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> rows = np.array([True,False,True]) >>> X[rows] array([[1, 2, 3], [7, 8, 9]]) >>> X[np.logical_not(rows)] array([[4, 5, 6]]) ``` But this seems not poss...
You can use [`np.nonzero`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html#numpy.nonzero) (or `ndarray.nonzero`) on your boolean array to get corresponding numerical indices, then use these to access the sparse matrix. Since "fancy indexing" on sparse matrices is quite limited compared to dense `...
thread lock necessary for processing queues + Python
6,408,665
2
2011-06-20T08:39:14Z
6,408,715
8
2011-06-20T08:43:56Z
[ "python", "multithreading" ]
I have a queue in which i have to use it in several threads, so is it necessary to acquire the thread lock to avoid conflicts while processing this single queue, because i know it is necessary to acquire thread lock for variables or other resources, but little confused for queues. thanks
If you use the Queue in the module Queue, it will take care of the locking for you. See this page for more information: <http://docs.python.org/library/queue.html> ("The Queue class in this module implements all the required locking semantics.")
Python constants declaration
6,408,886
7
2011-06-20T09:01:06Z
6,408,907
11
2011-06-20T09:02:46Z
[ "python", "constants" ]
if I declare a const class which are contains variables: for example ``` class const: MASTER_CLIENT_CONNECTED = 0 CLIENT_CONNECTED = 1 GET_SERVER_QUEUE = 9998 ERROR = 9999 ``` is there any way to reach this variable(constants) without creating a new class. like this: ``` import const co...
Yes, instead of putting them in a class put them directly into your module (name the file e.g. `const.py` so the module name is `const`). Using a class for this is pretty much abusing classes for namespacing - and Python has [packages/modules](http://docs.python.org/tutorial/modules.html) for this purpose. Then you co...
Why do all module run together?
6,409,012
2
2011-06-20T09:12:10Z
6,409,052
10
2011-06-20T09:15:11Z
[ "python", "eclipse", "pydev" ]
I just made a fresh copy of eclipse and installed pydev. In my first trial to use pydev with eclipse, I created 2 module under the src package(the default one) FirstModule.py: ``` ''' Created on 18.06.2009 @author: Lars Vogel ''' def add(a,b): return a+b def addFixedValue(a): y = 5 return y +a print "...
When you import a module, everything in it is "run". This means that classes and function objects are created, global variables are set, and print statements are executed. \*) It is common practice to enclose statements only meant to be executed when the module is run *directly* in an if-block such as this: ``` if __...
`Node.js` and/or other Javascript offshoots' performance, stability and speed relative to non-JS frameworks (Rails, Django...)
6,409,306
20
2011-06-20T09:35:38Z
6,409,417
18
2011-06-20T09:46:35Z
[ "javascript", "python", "ruby-on-rails", "node.js", "model-view-controller" ]
I find myself often needing performance & speed references for friends who still don't believe a Node.js or other Javascript-derived implementation or application can compete with those powered by Rails, Pure Ruby, `.NET`, Python and similar setups. I have seen very impressive reports on this, with graphs and eyecandy...
* [v8 faster then php/python, 3x slower then C++](http://blog.famzah.net/2010/07/01/cpp-vs-python-vs-perl-vs-php-performance-benchmark/) * [node.js vs tornade](http://www.ostinelli.net/a-comparison-between-misultin-mochiweb-cowboy-nodejs-and-tornadoweb/) * [Express vs Sinatra](http://tjholowaychuk.com/post/543953703/ex...
`Node.js` and/or other Javascript offshoots' performance, stability and speed relative to non-JS frameworks (Rails, Django...)
6,409,306
20
2011-06-20T09:35:38Z
6,409,663
7
2011-06-20T10:07:51Z
[ "javascript", "python", "ruby-on-rails", "node.js", "model-view-controller" ]
I find myself often needing performance & speed references for friends who still don't believe a Node.js or other Javascript-derived implementation or application can compete with those powered by Rails, Pure Ruby, `.NET`, Python and similar setups. I have seen very impressive reports on this, with graphs and eyecandy...
Node.js is beating other platforms, sure. But it's not it's raw speed (V8), it's the sophisticated event-driven model which powers the node.js platform ;)
Is del called on an object that doesn't complete init?
6,409,644
18
2011-06-20T10:06:11Z
6,409,689
14
2011-06-20T10:11:44Z
[ "python", "python-3.x" ]
Will `__del__` be called if an object's `__init__` does not complete (such as by throwing an exception)?
Answer is **YES**. As discussed [here](http://www.algorithm.co.il/blogs/programming/python-gotchas-1-__del__-is-not-the-opposite-of-__init__/) `__del__` is not the opposite of `__init__`, but merely the oppposite of `__new__`. If `__new__` raise an exception before the object creation (in general before the superclas...
Is del called on an object that doesn't complete init?
6,409,644
18
2011-06-20T10:06:11Z
6,409,718
23
2011-06-20T10:15:31Z
[ "python", "python-3.x" ]
Will `__del__` be called if an object's `__init__` does not complete (such as by throwing an exception)?
``` class test(): def __init__(self): raise def __del__(self): print "__del__ called" try: test() except: pass ``` Yes. **Explanation:** `__del__` is called when the last reference to the object is removed. But if you do not catch the exception, `__del__` will not be called because t...
How to dynamically change child widgets with Python and Qt?
6,410,593
9
2011-06-20T11:43:14Z
6,410,990
18
2011-06-20T12:18:05Z
[ "python", "qt", "pyqt", "pyqt4", "pyside" ]
I would like to create a widget that has a child widget that I can dynamically change. Here is what I tried: ``` import sys from PySide.QtCore import * from PySide.QtGui import * class Widget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setLayout(QVBoxLayout()) ...
`removeWidget()` only removes the item from the layout, it doesn't delete it. You can delete the child widget by calling `setParent(None)`. ``` def update(self): self.layout().removeWidget(self.child) self.child.setParent(None) self.child = QLabel("bar", self) self.layout().addWidget(self.child) ```
Python datetime object show wrong timezone offset
6,410,971
10
2011-06-20T12:16:24Z
6,411,149
21
2011-06-20T12:29:58Z
[ "python", "datetime", "pytz" ]
I am try creating a datetime object in python using datetime and pytz, the offset shown is wrong. ``` import datetime from pytz import timezone start = datetime.datetime(2011, 6, 20, 0, 0, 0, 0, timezone('Asia/Kolkata')) print start ``` The output shown is ``` datetime.datetime(2011, 6, 20, 0, 0, tzinfo=<DstTzInfo ...
See: <http://bytes.com/topic/python/answers/676275-pytz-giving-incorrect-offset-timezone> In the comments, someone proposes to use `tzinfo.localize()` instead of the `datetime` constructor, which does the trick. ``` >>> tz = timezone('Asia/Kolkata') >>> dt = tz.localize(datetime.datetime(2011, 6, 20, 0, 0, 0, 0)) >>>...
Enumerate items in a list so a user can select the numeric value
6,410,982
2
2011-06-20T12:17:05Z
6,411,076
8
2011-06-20T12:23:45Z
[ "python", "enumerate" ]
I'm trying to find the most straightforward way to enumerate items in a list so that a user will not be burdened to type a long file name on a command line. The function below shows a user all .tgz and .tar files in a folder ... the user is then allowed to enter the name of the file he wants to extract. This is tedious...
Start with a list of files: ``` files = [fname for fname in os.listdir(path) if fname.endswith(('.tgz','.tar'))] ``` Now you can literally `enumerate` them: ``` for item in enumerate(files): print "[%d] %s" % item try: idx = int(raw_input("Enter the file's number")) except ValueError: pr...
Randomly selecting a file from a tree of directories in a completely fair manner
6,411,811
6
2011-06-20T13:22:07Z
6,411,889
10
2011-06-20T13:27:31Z
[ "python" ]
I'm looking for a way to randomly select a file from a tree of directories in a manner such that any individual file has exactly the same probability of being chosen as all other files. For example in the following tree of files, each file should have a 25% chance of being chosen: * /some/parent/dir/ + Foo.jpg + s...
You can only select all files with the same probability if you know the total number of files in advance, so you need to create a full list first: ``` files = [os.path.join(path, filename) for path, dirs, files in os.walk(dir) for filename in files if not filename.endswith(".bak")] return ra...
Extraction from python over multiple lines
6,411,911
2
2011-06-20T13:29:10Z
6,411,961
9
2011-06-20T13:33:23Z
[ "python", "findall" ]
I'm working with python and am trying to extract numbers from a .txt file and then group them into multiple categories. The .txt file looks like this: ``` IF 92007<=ZIPCODE<=92011 OR ZIPCODE=92014 OR ZIPCODE=92024 OR 92054<=ZIPCODE<=92058 OR ZIPCODE=92067 OR ZIPCODE=92075 OR ZIPCODE=92083 OR ZIPCODE=92084 OR ZIPCODE...
Just do: ``` matches = re.findall("([0-9]{5})",f.read()) ``` You can extract them all at once - no need to loop over lines.
Python decorator as a staticmethod
6,412,146
36
2011-06-20T13:43:34Z
6,412,373
35
2011-06-20T13:58:36Z
[ "python", "decorator", "static-methods" ]
I'm trying to write a python class which uses a decorator function that needs information of the instance state. This is working as intended, but if I explicitly make the decorator a staticmetod, I get the following error: ``` Traceback (most recent call last): File "tford.py", line 1, in <module> class TFord(ob...
This is not how `staticmethod` is supposed to be used. `staticmethod` objects are [descriptors](http://docs.python.org/howto/descriptor.html) that return the wrapped object, so they only work when accessed as `classname.staticmethodname`. Example ``` class A(object): @staticmethod def f(): pass print A...
Python: How to read stdout non blocking from another process?
6,413,803
12
2011-06-20T15:38:15Z
6,414,205
10
2011-06-20T16:07:33Z
[ "python", "stdout", "popen" ]
During the runtime of a process I would like to read its stdout and write it to a file. Any attempt of mine however failed because no matter what I tried as soon as I tried reading from the stdout it blocked until the process finished. Here is a snippet of what I am trying to do. (The first part is simply a python scr...
What is happening is buffering on the writer side. Since you are writing such small chunks from the little code snippet the underlying FILE object is buffering the output until the end. The following works as you expect. ``` #!/usr/bin/python import sys import subprocess p = subprocess.Popen("""python -c ' from time...
Exit Code Standards in Python
6,413,831
9
2011-06-20T15:40:25Z
6,413,924
12
2011-06-20T15:48:11Z
[ "python", "coding-style" ]
Are there any established exit code standards or reserved exit codes in Python (specifically, Python CLI utilities)? (e.g., /usr/include/sysexits.h for C in UNIX platforms, or <http://tldp.org/LDP/abs/html/exitcodes.html> for Bash scripts)
Provided you are on a POSIX platform, you can access the constants from `sysexit.h` via the [`posix`](http://docs.python.org/library/posix.html) module: ``` >>> import posix >>> posix.EX_ <tab pressed> posix.EX_CANTCREAT posix.EX_NOHOST posix.EX_OK posix.EX_SOFTWARE posix.EX_CONFIG posix.EX_NO...
Python exception ordering
6,414,390
2
2011-06-20T16:22:57Z
6,414,430
8
2011-06-20T16:26:02Z
[ "python", "python-2.x" ]
Just curious, why does the following code ``` import sys class F(Exception): sys.stderr.write('Inside exception\n') sys.stderr.flush() pass sys.stderr.write('Before Exception\n') sys.stderr.flush() try: raise F except F: pass ``` output: ``` Inside exception Before Exception ``` and not: ``` ...
You're printing in the class, not its initialization block . Try running this ``` import sys class F(Exception): sys.stderr.write('Inside exception\n') sys.stderr.flush() pass ``` alone. i.e., it's not running when you call `raise F`. Try this instead ``` import sys class F(Exception): def __init__()...
MySQLdb error when running python server on MacOSX10.6
6,414,407
5
2011-06-20T16:24:13Z
6,415,687
15
2011-06-20T18:23:53Z
[ "python", "mysql", "django", "osx" ]
Running my server (python manage.py runserver) yielded this error: > django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb I attempted the winning solution on this page with no avail: [Django + MySQL on Mac OS 10.6.2 Snow Leopard](http://stackoverflow.com/questions/1904039...
It looks like you have everything installed right, but it can't find libmysqlclient. Have you tried the following? ``` > sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib > sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql ```
Manually Clone/Copy an instance in Python
6,414,881
2
2011-06-20T17:10:13Z
6,414,921
8
2011-06-20T17:14:09Z
[ "python", "copy", "clone" ]
I know we have both `copy` and `deepcopy` inside the module `copy`, but I'd like to do it manually... I started by playing a little with `__dict__` object just to see how can I create instances setting the same attributes that the object to be copied have, and here's the result of my first test: ``` class A(object): ...
To manually create a shallow copy of an instance of the user-defined class `A`, you can do ``` a = A() b = object.__new__(A) b.__dict__ = a.__dict__.copy() # or dict(a.__dict__) ``` The call to `object.__new__()` creates a new instance without calling `__init__()`. Your code constructs a new type object rather tha...
Scala equivalent of python echo server/client example?
6,414,942
13
2011-06-20T17:15:50Z
6,416,755
20
2011-06-20T20:02:06Z
[ "python", "scala", "echo" ]
All the "server" example in scala use actors, reactors etc... Can someone show me how to write a dead simple echo server and client, just like the following python example of [Server](http://ilab.cs.byu.edu/python/socket/echoserver.html) and [Client](http://ilab.cs.byu.edu/python/socket/echoclient.html): ``` # A simp...
You can do following within standard library: ``` // Simple server import java.net._ import java.io._ import scala.io._ val server = new ServerSocket(9999) while (true) { val s = server.accept() val in = new BufferedSource(s.getInputStream()).getLines() val out = new PrintStream(s.getOutputStream()) ...
eval giving syntax error even when correct code given
6,414,991
6
2011-06-20T17:19:56Z
6,415,018
7
2011-06-20T17:22:31Z
[ "python", "eval" ]
I have the following code, which uses the `eval` function: ``` lines = self.fulltext.splitlines() CURRENT = 0 extractors = { "solar zenith angle" : (CURRENT, 1, "self.solar_z"), "ground pressure" : (CURRENT, 2, "self.ground_pressure") } print locals() for l...
`eval()` evaluates expressions. Assignment in Python is a statement. This will not work.
eval giving syntax error even when correct code given
6,414,991
6
2011-06-20T17:19:56Z
6,415,043
9
2011-06-20T17:25:05Z
[ "python", "eval" ]
I have the following code, which uses the `eval` function: ``` lines = self.fulltext.splitlines() CURRENT = 0 extractors = { "solar zenith angle" : (CURRENT, 1, "self.solar_z"), "ground pressure" : (CURRENT, 2, "self.ground_pressure") } print locals() for l...
Use [exec](https://docs.python.org/2.0/ref/exec.html) instead, it does evaluate statements, to. `exec "self.solar_z = values[1]" in locals(), locals()`