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 |
|---|---|---|---|---|---|---|---|---|---|
Parse String to Float or Int | 379,906 | 1,130 | 2008-12-19T01:52:26Z | 17,815,252 | 26 | 2013-07-23T16:00:21Z | [
"python",
"string",
"parsing",
"floating-point",
"integer"
] | In Python, how can I parse a numeric string like `"545.2222"` to its corresponding float value, `542.2222`? Or parse the string `"31"` to an integer, `31`?
I just want to know how to parse a float string to a float, and (separately) an int string to an int. | ## Localization and commas
You should consider the possibility of commas in the string representation of a number, for cases like `float("545,545.2222")` which throws an exception. Instead, use methods in `locale` to convert the strings to numbers and interpret commas correctly. The `locale.atof` method converts to a ... |
Parse String to Float or Int | 379,906 | 1,130 | 2008-12-19T01:52:26Z | 20,929,983 | 246 | 2014-01-05T04:15:39Z | [
"python",
"string",
"parsing",
"floating-point",
"integer"
] | In Python, how can I parse a numeric string like `"545.2222"` to its corresponding float value, `542.2222`? Or parse the string `"31"` to an integer, `31`?
I just want to know how to parse a float string to a float, and (separately) an int string to an int. | ## Python method to check if a string is a float:
```
def isfloat(value):
try:
float(value)
return True
except:
return False
```
## What is, and is not a float in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) may surprise you:
```
Command to parse isFlo... |
Parse String to Float or Int | 379,906 | 1,130 | 2008-12-19T01:52:26Z | 25,299,501 | 8 | 2014-08-14T03:21:37Z | [
"python",
"string",
"parsing",
"floating-point",
"integer"
] | In Python, how can I parse a numeric string like `"545.2222"` to its corresponding float value, `542.2222`? Or parse the string `"31"` to an integer, `31`?
I just want to know how to parse a float string to a float, and (separately) an int string to an int. | If you aren't averse to third-party modules, you could check out the [fastnumbers](https://pypi.python.org/pypi/fastnumbers) module. It provides a function called [fast\_real](http://pythonhosted.org//fastnumbers/fast.html#fast-real) that does exactly what this question is asking for and does it faster than a pure-Pyth... |
How do I respond to mouse clicks on sprites in PyGame? | 380,420 | 5 | 2008-12-19T08:54:57Z | 393,256 | 10 | 2008-12-25T22:46:33Z | [
"python",
"pygame"
] | What is the canonical way of making your sprites respond to mouse clicks in PyGame ?
Here's something simple, in my event loop:
```
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_game()
[...]
elif ( event.type == pygame.MOUSEBUTTONDOWN and
pygame.mouse.get_pressed... | I usually give my clickable objects a click function, like in your example. I put all of those objects in a list, for easy iteration when the click functions are to be called.
when checking for which mousebutton you press, use the button property of the event.
```
import pygame
from pygame.locals import * #This lets ... |
How do I get the full XML or HTML content of an element using ElementTree? | 380,603 | 5 | 2008-12-19T10:33:52Z | 380,717 | 11 | 2008-12-19T11:21:52Z | [
"python",
"xml",
"api",
"elementtree"
] | That is, all text and subtags, without the tag of an element itself?
Having
```
<p>blah <b>bleh</b> blih</p>
```
I want
```
blah <b>bleh</b> blih
```
element.text returns "blah " and etree.tostring(element) returns:
```
<p>blah <b>bleh</b> blih</p>
``` | ElementTree works perfectly, you have to assemble the answer yourself. Something like this...
```
"".join( [ "" if t.text is None else t.text ] + [ xml.tostring(e) for e in t.getchildren() ] )
```
Thanks to JV amd PEZ for pointing out the errors.
---
Edit.
```
>>> import xml.etree.ElementTree as xml
>>> s= '<p>bla... |
How to do this - python dictionary traverse and search | 380,734 | 7 | 2008-12-19T11:33:06Z | 380,769 | 12 | 2008-12-19T11:44:56Z | [
"python",
"dictionary",
"parsing"
] | I have nested dictionaries:
```
{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'},
u'key1': {'attrs': {'entity': 'r',
'hash': '34njasd3h43b4n3',
'id': '4130-1'},
u'key2': {'attrs': {'entity': 'c',
... | If you want to solve the problem in a general way, no matter how many level of nesting you have in your dict, then create a recursive function which will traverse the tree:
```
def traverse_tree(dictionary, id=None):
for key, value in dictionary.items():
if key == 'id':
if value == id:
... |
How to do this - python dictionary traverse and search | 380,734 | 7 | 2008-12-19T11:33:06Z | 380,874 | 12 | 2008-12-19T12:45:28Z | [
"python",
"dictionary",
"parsing"
] | I have nested dictionaries:
```
{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'},
u'key1': {'attrs': {'entity': 'r',
'hash': '34njasd3h43b4n3',
'id': '4130-1'},
u'key2': {'attrs': {'entity': 'c',
... | Your structure is unpleasantly irregular. Here's a version with a **Visitor** function that traverses the `attrs` sub-dictionaries.
```
def walkDict( aDict, visitor, path=() ):
for k in aDict:
if k == 'attrs':
visitor( path, aDict[k] )
elif type(aDict[k]) != dict:
pass
... |
How to do this - python dictionary traverse and search | 380,734 | 7 | 2008-12-19T11:33:06Z | 380,987 | 9 | 2008-12-19T13:37:03Z | [
"python",
"dictionary",
"parsing"
] | I have nested dictionaries:
```
{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'},
u'key1': {'attrs': {'entity': 'r',
'hash': '34njasd3h43b4n3',
'id': '4130-1'},
u'key2': {'attrs': {'entity': 'c',
... | This kind of problem is often better solved with proper class definitions, not generic dictionaries.
```
class ProperObject( object ):
"""A proper class definition for each "attr" dictionary."""
def __init__( self, path, attrDict ):
self.path= path
self.__dict__.update( attrDict )
def __str... |
Python: single instance of program | 380,870 | 66 | 2008-12-19T12:42:52Z | 380,876 | 16 | 2008-12-19T12:46:38Z | [
"python",
"locking"
] | Is there a Pythonic way to have only one instance of a program running?
The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this?
(Take into... | I don't know if it's pythonic enough, but in the Java world listening on a defined port is a pretty widely used solution, as it works on all major platforms and doesn't have any problems with crashing programs.
Another advantage of listening to a port is that you could send a command to the running instance. For examp... |
Python: single instance of program | 380,870 | 66 | 2008-12-19T12:42:52Z | 384,493 | 25 | 2008-12-21T14:02:47Z | [
"python",
"locking"
] | Is there a Pythonic way to have only one instance of a program running?
The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this?
(Take into... | Simple, ~~cross-platform~~ solution, found in **[another question](http://stackoverflow.com/questions/220525/ensuring-a-single-instance-of-an-application-in-linux#221159)** by [zgoda](http://stackoverflow.com/users/12138/zgoda):
```
import fcntl, sys
pid_file = 'program.pid'
fp = open(pid_file, 'w')
try:
fcntl.loc... |
Python: single instance of program | 380,870 | 66 | 2008-12-19T12:42:52Z | 1,265,445 | 56 | 2009-08-12T10:45:24Z | [
"python",
"locking"
] | Is there a Pythonic way to have only one instance of a program running?
The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this?
(Take into... | The following code should do the job, it is cross-platform and runs on Python 2.4-3.2. I tested it on Windows, OS X and Linux.
```
from tendo import singleton
me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running
```
The latest code version is available [singleton.py](https://github.com/pyc... |
Python: single instance of program | 380,870 | 66 | 2008-12-19T12:42:52Z | 1,662,504 | 19 | 2009-11-02T17:10:48Z | [
"python",
"locking"
] | Is there a Pythonic way to have only one instance of a program running?
The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this?
(Take into... | This code is Linux specific ( it uses 'abstract' UNIX domain sockets ) but it is simple and won't leave stale lock files around. I prefer it to the solution above because it doesn't require a specially reserved TCP port.
```
try:
import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
## Create... |
Comparing massive lists of dictionaries in python | 382,466 | 11 | 2008-12-19T22:49:15Z | 382,707 | 18 | 2008-12-20T01:01:00Z | [
"python"
] | I never actually thought I'd run into speed-issues with python, but I have. I'm trying to compare really big lists of dictionaries to each other based on the dictionary values. I compare two lists, with the first like so
```
biglist1=[{'transaction':'somevalue', 'id':'somevalue', 'date':'somevalue' ...}, {'transactio'... | Index on the fields you want to use for lookup. O(n+m)
```
matches = []
biglist1_indexed = {}
for item in biglist1:
biglist1_indexed[(item["transaction"], item["date"])] = item
for item in biglist2:
if (item["transaction"], item["date"]) in biglist1_indexed:
matches.append(item)
```
This is probably thousands o... |
In what contexts do programming languages make real use of an Infinity value? | 382,603 | 25 | 2008-12-19T23:54:04Z | 382,605 | 34 | 2008-12-19T23:55:12Z | [
"python",
"ruby",
"language-agnostic",
"idioms",
"infinity"
] | So in Ruby there is a trick to specify infinity:
```
1.0/0
=> Infinity
```
I believe in Python you can do something like this
```
float('inf')
```
These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it ... | Off the top of the head, it can be useful as an initial value when searching for a minimum value.
For example:
```
min = float('inf')
for x in somelist:
if x<min:
min=x
```
Which I prefer to setting `min` initially to the first value of `somelist`
Of course, in Python, you should just use the min() built-in... |
In what contexts do programming languages make real use of an Infinity value? | 382,603 | 25 | 2008-12-19T23:54:04Z | 382,628 | 11 | 2008-12-20T00:07:03Z | [
"python",
"ruby",
"language-agnostic",
"idioms",
"infinity"
] | So in Ruby there is a trick to specify infinity:
```
1.0/0
=> Infinity
```
I believe in Python you can do something like this
```
float('inf')
```
These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it ... | In some physics calculations you can normalize irregularities (ie, infinite numbers) of the same order with each other, canceling them both and allowing a approximate result to come through.
When you deal with limits, calculations like (infinity / infinity) -> approaching a finite a number could be achieved. It's usef... |
In what contexts do programming languages make real use of an Infinity value? | 382,603 | 25 | 2008-12-19T23:54:04Z | 382,674 | 34 | 2008-12-20T00:40:24Z | [
"python",
"ruby",
"language-agnostic",
"idioms",
"infinity"
] | So in Ruby there is a trick to specify infinity:
```
1.0/0
=> Infinity
```
I believe in Python you can do something like this
```
float('inf')
```
These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it ... | Dijkstra's Algorithm typically assigns infinity as the initial edge weights in a graph. This doesn't *have* to be "infinity", just some arbitrarily constant but in java I typically use Double.Infinity. I assume ruby could be used similarly. |
In what contexts do programming languages make real use of an Infinity value? | 382,603 | 25 | 2008-12-19T23:54:04Z | 382,686 | 8 | 2008-12-20T00:46:51Z | [
"python",
"ruby",
"language-agnostic",
"idioms",
"infinity"
] | So in Ruby there is a trick to specify infinity:
```
1.0/0
=> Infinity
```
I believe in Python you can do something like this
```
float('inf')
```
These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it ... | [Alpha-beta pruning](http://en.wikipedia.org/wiki/Alpha-beta_pruning) |
In what contexts do programming languages make real use of an Infinity value? | 382,603 | 25 | 2008-12-19T23:54:04Z | 382,736 | 10 | 2008-12-20T01:29:23Z | [
"python",
"ruby",
"language-agnostic",
"idioms",
"infinity"
] | So in Ruby there is a trick to specify infinity:
```
1.0/0
=> Infinity
```
I believe in Python you can do something like this
```
float('inf')
```
These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it ... | Use `Infinity` and `-Infinity` when implementing a mathematical algorithm calls for it.
In Ruby, `Infinity` and `-Infinity` have nice comparative properties so that `-Infinity` < `x` < `Infinity` for any real number `x`. For example, `Math.log(0)` returns `-Infinity`, extending to `0` the property that `x > y` implies... |
In what contexts do programming languages make real use of an Infinity value? | 382,603 | 25 | 2008-12-19T23:54:04Z | 383,348 | 17 | 2008-12-20T14:03:13Z | [
"python",
"ruby",
"language-agnostic",
"idioms",
"infinity"
] | So in Ruby there is a trick to specify infinity:
```
1.0/0
=> Infinity
```
I believe in Python you can do something like this
```
float('inf')
```
These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it ... | There seems to be an implied "Why does this functionality even exist?" in your question. And the reason is that Ruby and Python are just giving access to the full range of values that one can specify in floating point form as specified by IEEE.
This page seems to describe it well:
<http://steve.hollasch.net/cgindex/co... |
In what contexts do programming languages make real use of an Infinity value? | 382,603 | 25 | 2008-12-19T23:54:04Z | 399,013 | 8 | 2008-12-29T23:05:55Z | [
"python",
"ruby",
"language-agnostic",
"idioms",
"infinity"
] | So in Ruby there is a trick to specify infinity:
```
1.0/0
=> Infinity
```
I believe in Python you can do something like this
```
float('inf')
```
These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it ... | I use it to specify the mass and inertia of a static object in physics simulations. Static objects are essentially unaffected by gravity and other simulation forces. |
Is @measured a standard decorator? What library is it in? | 382,624 | 2 | 2008-12-20T00:04:41Z | 382,666 | 13 | 2008-12-20T00:37:25Z | [
"python",
"decorator"
] | In [this blog article](http://abstracthack.wordpress.com/2007/09/05/multi-threaded-map-for-python/) they use the construct:
```
@measured
def some_func():
#...
# Presumably outputs something like "some_func() is finished in 121.333 s" somewhere
```
This `@measured` directive doesn't seem to work with raw py... | `@measured` decorates the some\_func() function, using a function or class named `measured`. The `@` is the decorator syntax, `measured` is the decorator function name.
Decorators can be a bit hard to understand, but they are basically used to either wrap code around a function, or inject code into one.
For example t... |
Django: How can I use my model classes to interact with my database from outside Django? | 383,073 | 13 | 2008-12-20T07:48:15Z | 383,089 | 15 | 2008-12-20T08:18:44Z | [
"python",
"django",
"django-models"
] | I'd like to write a script that interacts with my DB using a Django app's model. However, I would like to be able to run this script from the command line or via cron. What all do I need to import to allow this? | You need to set up the Django environment variables. These tell Python where your project is, and what the name of the settings module is (the project name in the settings module is optional):
```
import os
os.environ['PYTHONPATH'] = '/path/to/myproject'
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
```... |
Django: How can I use my model classes to interact with my database from outside Django? | 383,073 | 13 | 2008-12-20T07:48:15Z | 383,246 | 13 | 2008-12-20T12:06:39Z | [
"python",
"django",
"django-models"
] | I'd like to write a script that interacts with my DB using a Django app's model. However, I would like to be able to run this script from the command line or via cron. What all do I need to import to allow this? | The preferred way should be to add a [custom command](http://docs.djangoproject.com/en/dev/howto/custom-management-commands/) and then run it as any other `django-admin` (not to be confused with `django.contrib.admin`) command:
```
./manage.py mycustomcommand --customarg
```
Setting DJANGO\_SETTINGS\_MODULE should on... |
How to iterate over a list repeating each element in Python | 383,565 | 6 | 2008-12-20T18:23:52Z | 383,578 | 12 | 2008-12-20T18:36:27Z | [
"python",
"iterator"
] | I'm using Python to **infinitely** iterate over a list, repeating each element in the list a number of times. For example given the list:
```
l = [1, 2, 3, 4]
```
I would like to output each element two times and then repeat the cycle:
```
1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ...
```
I've got an idea of where to star... | How about this:
```
import itertools
def bicycle(iterable, repeat=1):
for item in itertools.cycle(iterable):
for _ in xrange(repeat):
yield item
c = bicycle([1,2,3,4], 2)
print [c.next() for _ in xrange(10)]
```
EDIT: incorporated [bishanty's](http://stackoverflow.com/users/37522/bishanty) r... |
How do you apply 'or' to all values of a list in Python? | 383,623 | 14 | 2008-12-20T19:05:12Z | 383,642 | 31 | 2008-12-20T19:16:37Z | [
"python",
"list",
"reduce"
] | How do you apply 'or' to all values of a list in Python? I'm thinking something like:
```
or([True, True, False])
```
or if it was possible:
```
reduce(or, [True, True, False])
``` | The built-in function `any` does what you want:
```
>>> any([True, True, False])
True
>>> any([False, False, False])
False
>>> any([False, False, True])
True
```
`any` has the advantage over `reduce` of shortcutting the test for later items in the sequence once it finds a true value. This can be very handy if the seq... |
How do you apply 'or' to all values of a list in Python? | 383,623 | 14 | 2008-12-20T19:05:12Z | 383,668 | 7 | 2008-12-20T19:49:58Z | [
"python",
"list",
"reduce"
] | How do you apply 'or' to all values of a list in Python? I'm thinking something like:
```
or([True, True, False])
```
or if it was possible:
```
reduce(or, [True, True, False])
``` | No one has mentioned it, but "`or`" is available as a function in the operator module:
```
from operator import or_
```
Then you can use `reduce` as above.
Would always advise "`any`" though in more recent Pythons. |
104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN? | 383,738 | 20 | 2008-12-20T21:04:42Z | 383,816 | 10 | 2008-12-20T22:18:15Z | [
"python",
"sockets",
"wsgi",
"httplib2",
"werkzeug"
] | We're developing a Python web service and a client web site in parallel. When we make an HTTP request from the client to the service, one call consistently raises a socket.error in socket.py, in read:
```
(104, 'Connection reset by peer')
```
When I listen in with wireshark, the "good" and "bad" responses look very s... | I've had this problem. See [The Python "Connection Reset By Peer" Problem](http://www.itmaybeahack.com/homepage/iblog/architecture/C551260341/E20081031204203/index.html).
You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.
You can (sometimes) correct this with a `time.... |
104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN? | 383,738 | 20 | 2008-12-20T21:04:42Z | 481,952 | 7 | 2009-01-27T00:37:29Z | [
"python",
"sockets",
"wsgi",
"httplib2",
"werkzeug"
] | We're developing a Python web service and a client web site in parallel. When we make an HTTP request from the client to the service, one call consistently raises a socket.error in socket.py, in read:
```
(104, 'Connection reset by peer')
```
When I listen in with wireshark, the "good" and "bad" responses look very s... | Don't use wsgiref for production. Use Apache and mod\_wsgi, or something else.
We continue to see these connection resets, sometimes frequently, with wsgiref (the backend used by the werkzeug test server, and possibly others like the Django test server). Our solution was to log the error, retry the call in a loop, and... |
Best way to return the language of a given string | 383,966 | 7 | 2008-12-21T01:12:56Z | 383,988 | 14 | 2008-12-21T01:40:58Z | [
"python",
"algorithm",
"string"
] | More specifically, I'm trying to check if given string (a sentence) is in Turkish.
I can check if the string has Turkish characters such as Ã, Å, Ã, Ã, Ä etc. However that's not very reliable as those might be converted to C, S, U, O, G before I receive the string.
Another method is to have the 100 most used wor... | One option would be to use a Bayesian Classifier such as [Reverend](http://www.divmod.org/trac/wiki/DivmodReverend). The Reverend homepage gives this suggestion for a naive language detector:
```
from reverend.thomas import Bayes
guesser = Bayes()
guesser.train('french', 'le la les du un une je il elle de en')
guesser... |
Best way to return the language of a given string | 383,966 | 7 | 2008-12-21T01:12:56Z | 384,062 | 10 | 2008-12-21T03:32:36Z | [
"python",
"algorithm",
"string"
] | More specifically, I'm trying to check if given string (a sentence) is in Turkish.
I can check if the string has Turkish characters such as Ã, Å, Ã, Ã, Ä etc. However that's not very reliable as those might be converted to C, S, U, O, G before I receive the string.
Another method is to have the 100 most used wor... | A simple statistical method that I've used before:
Get a decent amount of sample training text in the language you want to detect. Split it up into trigrams, e.g.
"Hello foobar" in trigrams is:
'Hel', 'ell', 'llo', 'lo ', 'o f', ' fo', 'foo', 'oob', 'oba', 'bar'
For all of the source data, count up the frequency of ... |
How can I color Python logging output? | 384,076 | 174 | 2008-12-21T03:57:45Z | 384,125 | 119 | 2008-12-21T05:17:39Z | [
"python",
"logging",
"colors"
] | Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized).
Now, Python has the `logging` module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can... | I already knew about the color escapes, I used them in my bash prompt a while ago. Thanks anyway.
What I wanted was to integrate it with the logging module, which I eventually did after a couple of tries and errors.
Here is what I end up with:
```
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
#... |
How can I color Python logging output? | 384,076 | 174 | 2008-12-21T03:57:45Z | 1,336,640 | 56 | 2009-08-26T18:29:35Z | [
"python",
"logging",
"colors"
] | Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized).
Now, Python has the `logging` module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can... | Here is a solution that should work on any platform. If it doesn't just tell me and I will update it.
How it works: on platform supporting ANSI escapes is using them (non-Windows) and on Windows it does use API calls to change the console colors.
The script does hack the logging.StreamHandler.emit method from standar... |
How can I color Python logging output? | 384,076 | 174 | 2008-12-21T03:57:45Z | 2,205,909 | 8 | 2010-02-05T08:36:51Z | [
"python",
"logging",
"colors"
] | Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized).
Now, Python has the `logging` module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can... | I modified the original example provided by Sorin and subclassed StreamHandler to a ColorizedConsoleHandler.
The downside of their solution is that it modifies the message, and because that is modifying the actual logmessage any other handlers will get the modified message as well.
This resulted in logfiles with colo... |
How can I color Python logging output? | 384,076 | 174 | 2008-12-21T03:57:45Z | 2,532,931 | 12 | 2010-03-28T12:49:40Z | [
"python",
"logging",
"colors"
] | Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized).
Now, Python has the `logging` module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can... | I updated the example from airmind supporting tags for foreground and background.
Just use the color variables $BLACK - $WHITE in your log formatter string. To set the background just use $BG-BLACK - $BG-WHITE.
```
import logging
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
COLORS = {
'WARNIN... |
How can I color Python logging output? | 384,076 | 174 | 2008-12-21T03:57:45Z | 4,691,726 | 10 | 2011-01-14T13:52:14Z | [
"python",
"logging",
"colors"
] | Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized).
Now, Python has the `logging` module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can... | Look at the following solution. The stream handler should be the thing doing the colouring, then you have the option of colouring words rather than just the whole line (with the Formatter).
<http://plumberjack.blogspot.com/2010/12/colorizing-logging-output-in-terminals.html> |
How can I color Python logging output? | 384,076 | 174 | 2008-12-21T03:57:45Z | 7,995,762 | 39 | 2011-11-03T13:31:53Z | [
"python",
"logging",
"colors"
] | Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized).
Now, Python has the `logging` module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can... | Quick and dirty solution for predefined log levels and without defining a new class.
```
logging.addLevelName( logging.WARNING, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
logging.addLevelName( logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR))
``` |
How can I color Python logging output? | 384,076 | 174 | 2008-12-21T03:57:45Z | 16,847,935 | 29 | 2013-05-31T00:16:27Z | [
"python",
"logging",
"colors"
] | Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized).
Now, Python has the `logging` module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can... | Years ago I wrote a colored stream handler for my own use. Then I came across this page and found a collection of code snippets that people are copy/pasting :-(. My stream handler currently only works on UNIX (Linux, Mac OS X) but the advantage is that it's [available on PyPI](https://pypi.python.org/pypi/coloredlogs) ... |
How can I color Python logging output? | 384,076 | 174 | 2008-12-21T03:57:45Z | 23,964,880 | 16 | 2014-05-30T23:39:51Z | [
"python",
"logging",
"colors"
] | Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized).
Now, Python has the `logging` module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can... | **Update**: Because this is an itch that I've been meaning to scratch for so long, I went ahead and wrote a library for lazy people like me who just want simple ways to do things: [zenlog](https://github.com/ManufacturaInd/zenlog)
Colorlog is excellent for this. It's [available on PyPI](https://pypi.python.org/pypi/co... |
Database does not update automatically with MySQL and Python | 384,228 | 24 | 2008-12-21T07:57:04Z | 384,240 | 42 | 2008-12-21T08:08:32Z | [
"python",
"mysql",
"mysql-python"
] | I'm having some trouble updating a row in a MySQL database. Here is the code I'm trying to run:
```
import MySQLdb
conn=MySQLdb.connect(host="localhost", user="root", passwd="pass", db="dbname")
cursor=conn.cursor()
cursor.execute("UPDATE compinfo SET Co_num=4 WHERE ID=100")
cursor.execute("SELECT Co_num FROM compin... | I am not certain, but I am going to guess you are using a INNODB table, and you haven't done a commit. I believe MySQLdb enable transactions automatically.
Call `conn.commit()` before calling `close`.
From the FAQ: [Starting with 1.2.0, MySQLdb disables autocommit by default](http://mysql-python.sourceforge.net/FAQ.h... |
Database does not update automatically with MySQL and Python | 384,228 | 24 | 2008-12-21T07:57:04Z | 384,311 | 7 | 2008-12-21T10:11:28Z | [
"python",
"mysql",
"mysql-python"
] | I'm having some trouble updating a row in a MySQL database. Here is the code I'm trying to run:
```
import MySQLdb
conn=MySQLdb.connect(host="localhost", user="root", passwd="pass", db="dbname")
cursor=conn.cursor()
cursor.execute("UPDATE compinfo SET Co_num=4 WHERE ID=100")
cursor.execute("SELECT Co_num FROM compin... | You need to commit changes manually or turn auto-commit on.
The reason SELECT returns the modified (but not persisted) data is because the connection is still in the same transaction. |
Database does not update automatically with MySQL and Python | 384,228 | 24 | 2008-12-21T07:57:04Z | 384,452 | 22 | 2008-12-21T13:19:16Z | [
"python",
"mysql",
"mysql-python"
] | I'm having some trouble updating a row in a MySQL database. Here is the code I'm trying to run:
```
import MySQLdb
conn=MySQLdb.connect(host="localhost", user="root", passwd="pass", db="dbname")
cursor=conn.cursor()
cursor.execute("UPDATE compinfo SET Co_num=4 WHERE ID=100")
cursor.execute("SELECT Co_num FROM compin... | MySQLdb has autocommit off by default, which may be confusing at first. Your connection exists in its own transaction and you will not be able to see the changes you make from other connections until you commit that transaction.
You can either do `conn.commit()` after the update statement as others have pointed out, o... |
MySQL-db lib for Python 3.x? | 384,471 | 29 | 2008-12-21T13:37:38Z | 3,611,517 | 7 | 2010-08-31T17:19:17Z | [
"python",
"mysql",
"python-3.x"
] | So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing. | I was looking for it too, but also found nothing, so I ported MySQL-python-1.2.3 to py3k
you can read it here
<http://sourceforge.net/p/mysql-python/discussion/70460/thread/61e3a3c9/> |
MySQL-db lib for Python 3.x? | 384,471 | 29 | 2008-12-21T13:37:38Z | 5,288,582 | 29 | 2011-03-13T09:42:27Z | [
"python",
"mysql",
"python-3.x"
] | So, looking for a mysql-db-lib that is compatible with py3k/py3.0/py3000, any ideas? Google turned up nothing. | It appears the MySQLdb is pretty much a dead project. However, [PyMySQL](https://github.com/PyMySQL/PyMySQL/) is a dbapi compliant, pure-python implementation of a mysql client, and it has python 3 support.
EDIT: There's also [MySQL Connector/Python](https://launchpad.net/myconnpy). Same idea. |
PIL and numpy | 384,759 | 67 | 2008-12-21T18:21:32Z | 384,926 | 81 | 2008-12-21T20:46:21Z | [
"python",
"image",
"numpy",
"python-imaging-library"
] | Alright, I'm toying around with converting a PIL image object back and forth to a numpy array so I can do some faster pixel by pixel transformations than PIL's PixelAccess object would allow. I've figured out how to place the pixel information in a useful 3D numpy array by way of:
```
pic = Image.open("foo.jpg")
pix =... | You're not saying how exactly `putdata()` is not behaving. I'm assuming you're doing
```
>>> pic.putdata(a)
Traceback (most recent call last):
File "...blablabla.../PIL/Image.py", line 1185, in putdata
self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple
```
Thi... |
PIL and numpy | 384,759 | 67 | 2008-12-21T18:21:32Z | 1,095,878 | 66 | 2009-07-08T02:33:17Z | [
"python",
"image",
"numpy",
"python-imaging-library"
] | Alright, I'm toying around with converting a PIL image object back and forth to a numpy array so I can do some faster pixel by pixel transformations than PIL's PixelAccess object would allow. I've figured out how to place the pixel information in a useful 3D numpy array by way of:
```
pic = Image.open("foo.jpg")
pix =... | Open I as an array:
```
>>> I = numpy.asarray(PIL.Image.open('test.jpg'))
```
Do some stuff to I, then, convert it back to an image:
```
>>> im = PIL.Image.fromarray(numpy.uint8(I))
```
[Filter numpy images with FFT, Python](http://barnesc.blogspot.com/2007/09/filter-numpy-images-with-fft-python.html)
If you want ... |
Checking 2-dimensional array (like eight queens puzzle) | 384,874 | 5 | 2008-12-21T20:00:55Z | 384,887 | 19 | 2008-12-21T20:10:32Z | [
"python",
"arrays",
"puzzle"
] | My problem is very similar to eight queens puzzle.
I've got 2-dimensional array (N x N) that for example, looks like this:
```
0,0,0,0,1 y
0,0,0,0,0 |
0,0,0,0,0 V
0,0,0,1,0
0,0,0,0,0
x->
```
I'm checking horizontally, vertically and diagonally for occurrences of 1
```
\,0,|,0,/
0,\,|,/,0
-,-,1,-,-
0,/,|,\,0
/,0,|,0... | One possible solution:
```
def collision(x1, y1, x2, y2):
return x1 == x2 or y1 == y2 or abs(x1-x2) == abs(y1-y2)
```
i.e. there is a collision if the two points are on the same horizontal row, same vertical row or same diagonal (vertical distance == horizontal distance). |
How do I send a custom header with urllib2 in a HTTP Request? | 385,262 | 42 | 2008-12-22T00:39:53Z | 385,411 | 91 | 2008-12-22T02:29:01Z | [
"python",
"header",
"urllib2"
] | I want to send a custom "Accept" header in my request when using urllib2.urlopen(..). How do I do that? | Not quite. Creating a `Request` object does not actually send the request, and Request objects have no `Read()` method. (Also: `read()` is lowercase.) All you need to do is pass the `Request` as the first argument to `urlopen()` and that will give you your response.
```
import urllib2
request = urllib2.Request("http:/... |
How do I send a custom header with urllib2 in a HTTP Request? | 385,262 | 42 | 2008-12-22T00:39:53Z | 32,026,467 | 8 | 2015-08-15T15:51:41Z | [
"python",
"header",
"urllib2"
] | I want to send a custom "Accept" header in my request when using urllib2.urlopen(..). How do I do that? | ```
import urllib2
request_headers = {
"Accept-Language": "en-US,en;q=0.5",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Referer": "http://thewebsite.com",
"Connection": "keep-alive"
}
request ... |
dropping trailing '.0' from floats | 385,325 | 22 | 2008-12-22T01:33:33Z | 385,392 | 14 | 2008-12-22T02:18:07Z | [
"python"
] | I'm looking for a way to convert numbers to string format, dropping any redundant '.0'
The input data is a mix of floats and strings. Desired output:
0 --> '0'
0.0 --> '0'
0.1 --> '0.1'
1.0 --> '1'
I've come up with the following generator expression, but I wonder if there's a faster way:
```
(str(i).rstrip('.0'... | `rstrip` doesn't do what you want it to do, it strips *any* of the characters you give it and not a suffix:
```
>>> '30000.0'.rstrip('.0')
'3'
```
Actually, just `'%g' % i` will do what you want.
EDIT: as Robert pointed out in his comment this won't work for large numbers since it uses the default precision of %g whi... |
dropping trailing '.0' from floats | 385,325 | 22 | 2008-12-22T01:33:33Z | 12,080,042 | 28 | 2012-08-22T19:23:16Z | [
"python"
] | I'm looking for a way to convert numbers to string format, dropping any redundant '.0'
The input data is a mix of floats and strings. Desired output:
0 --> '0'
0.0 --> '0'
0.1 --> '0.1'
1.0 --> '1'
I've come up with the following generator expression, but I wonder if there's a faster way:
```
(str(i).rstrip('.0'... | See [PEP 3101](http://www.python.org/dev/peps/pep-3101/):
```
'g' - General format. This prints the number as a fixed-point
number, unless the number is too large, in which case
it switches to 'e' exponent notation.
```
Old style:
```
>>> "%g" % float(10)
'10'
```
New style (recommended):
```
>>> '{0:g... |
Prototype based object orientation. The good, the bad and the ugly? | 385,403 | 10 | 2008-12-22T02:25:02Z | 385,467 | 7 | 2008-12-22T03:15:34Z | [
"javascript",
"python",
"language-agnostic",
"lua",
"oop"
] | I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditio... | To conserve the bandwidth here is the link to [my answer on "How can I emulate âclassesâ in JavaScript? (with or without a third-party library)"](http://stackoverflow.com/questions/355848/what-is-the-best-way-to-emulate-classes-in-javascript-with-or-without-a-framewo#356343). It contains further references as well ... |
Prototype based object orientation. The good, the bad and the ugly? | 385,403 | 10 | 2008-12-22T02:25:02Z | 385,571 | 13 | 2008-12-22T04:34:49Z | [
"javascript",
"python",
"language-agnostic",
"lua",
"oop"
] | I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditio... | Prototype-based OO lends itself poorly to static type checking, which some might consider a bad or ugly thing. Prototype-based OO *does* have a standard way of creating new objects, you **clone and modify existing objects**. You can also build factories, etc.
I think what people like most (the "good") is that prototyp... |
Extract float/double value | 385,558 | 17 | 2008-12-22T04:28:01Z | 385,597 | 38 | 2008-12-22T04:56:22Z | [
"python",
"regex"
] | How do I extract a double value from a string using regex.
```
import re
pattr = re.compile(???)
x = pattr.match("4.5")
``` | A regexp from the [`perldoc perlretut`](http://perldoc.perl.org/perlretut.html#Building-a-regexp):
```
import re
re_float = re.compile("""(?x)
^
[+-]?\ * # first, match an optional sign *and space*
( # then match integers or f.p. mantissas:
\d+ # start out with a ...
... |
Extract float/double value | 385,558 | 17 | 2008-12-22T04:28:01Z | 386,177 | 16 | 2008-12-22T12:41:31Z | [
"python",
"regex"
] | How do I extract a double value from a string using regex.
```
import re
pattr = re.compile(???)
x = pattr.match("4.5")
``` | Here's the easy way. Don't use regex's for built-in types.
```
try:
x = float( someString )
except ValueError, e:
# someString was NOT floating-point, what now?
``` |
Typecasting in Python | 385,572 | 12 | 2008-12-22T04:35:18Z | 385,583 | 26 | 2008-12-22T04:44:48Z | [
"python",
"string",
"int",
"bit",
"casting"
] | I need to convert strings in Python to other types such as unsigned and signed 8, 16, 32, and 64 bit ints, doubles, floats, and strings.
How can I do this? | You can convert a string to a 32-bit signed integer with the `int` function:
```
str = "1234"
i = int(str) // i is a 32-bit integer
```
If the string does not represent an integer, you'll get a `ValueError` exception. Note, however, that if the string does represent an integer, but that integer does not fit into a 3... |
Python Performance - have you ever had to rewrite in something else? | 386,655 | 42 | 2008-12-22T16:23:13Z | 386,674 | 33 | 2008-12-22T16:28:08Z | [
"python",
"performance",
"optimization",
"rewrite"
] | Has anyone ever had code in Python, that turned out not to perform fast enough?
I mean, you were forced to *choose another language* because of it?
We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say,... | Yes, I have. I wrote a row-count program for a binary (length-prefixed rather than delimited) bcp output file once and ended up having to redo it in C because the python one was too slow. This program was quite small (it only took a couple of days to re-write it in C), so I didn't bother to try and build a hybrid appli... |
Python Performance - have you ever had to rewrite in something else? | 386,655 | 42 | 2008-12-22T16:23:13Z | 386,702 | 18 | 2008-12-22T16:40:55Z | [
"python",
"performance",
"optimization",
"rewrite"
] | Has anyone ever had code in Python, that turned out not to perform fast enough?
I mean, you were forced to *choose another language* because of it?
We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say,... | This is a much more difficult question to answer than people are willing to admit.
For example, it may be that I am able to write a program that performs better in Python than it does in C. The fallacious conclusion from that statement is "Python is therefore faster than C". In reality, it may be because I have much m... |
Python Performance - have you ever had to rewrite in something else? | 386,655 | 42 | 2008-12-22T16:23:13Z | 386,770 | 7 | 2008-12-22T17:12:50Z | [
"python",
"performance",
"optimization",
"rewrite"
] | Has anyone ever had code in Python, that turned out not to perform fast enough?
I mean, you were forced to *choose another language* because of it?
We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say,... | While at uni we were writing a computer vision system for analysing human behaviour based on video clips. We used python because of the excellent PIL, to speed up development and let us get easy access to the image frames we'd extracted from the video for converting to arrays etc.
For 90% of what we wanted it was fine... |
Python Performance - have you ever had to rewrite in something else? | 386,655 | 42 | 2008-12-22T16:23:13Z | 386,999 | 7 | 2008-12-22T18:41:19Z | [
"python",
"performance",
"optimization",
"rewrite"
] | Has anyone ever had code in Python, that turned out not to perform fast enough?
I mean, you were forced to *choose another language* because of it?
We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say,... | Not so far. I work for a company that has a molecular simulation engine and a bunch of programs written in python for processing the large multi-gigabyte datasets. All of our analysis software is now being written in Python because of the huge advantages in development flexibility and time.
If something is not fast en... |
Python Performance - have you ever had to rewrite in something else? | 386,655 | 42 | 2008-12-22T16:23:13Z | 478,872 | 14 | 2009-01-26T04:54:13Z | [
"python",
"performance",
"optimization",
"rewrite"
] | Has anyone ever had code in Python, that turned out not to perform fast enough?
I mean, you were forced to *choose another language* because of it?
We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say,... | Adding my $0.02 for the record.
My work involves developing numeric models that run over 100's of gigabytes of data. The hard problems are in coming up with a revenue-generating solution quickly (i.e. time-to-market). To be commercially successful the solution also has to *execute* quickly (compute the solution in min... |
How do I convert part of a python tuple (byte array) into an integer | 386,753 | 4 | 2008-12-22T17:06:00Z | 386,763 | 9 | 2008-12-22T17:10:02Z | [
"python",
"tuples"
] | I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values:
response = (0, 0, 117, 143, 6)
The first 4 values are a 32-bit int telling me how many bytes have been used and the last value is the percentage... | See [Convert Bytes to Floating Point Numbers in Python](http://stackoverflow.com/questions/5415/)
You probably want to use the struct module, e.g.
```
import struct
response = (0, 0, 117, 143, 6)
struct.unpack(">I", ''.join([chr(x) for x in response[:-1]]))
```
Assuming an unsigned int. There may be a better way to... |
How do I convert part of a python tuple (byte array) into an integer | 386,753 | 4 | 2008-12-22T17:06:00Z | 386,830 | 13 | 2008-12-22T17:36:02Z | [
"python",
"tuples"
] | I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values:
response = (0, 0, 117, 143, 6)
The first 4 values are a 32-bit int telling me how many bytes have been used and the last value is the percentage... | Would,
> num = (response[0] << 24) +
> (response[1] << 16) + (response[2] <<
> 8) + response[3]
meet your needs?
aid |
Evaluate environment variables into a string | 386,934 | 24 | 2008-12-22T18:18:05Z | 386,978 | 41 | 2008-12-22T18:35:16Z | [
"python",
"filesystems",
"environment-variables"
] | I have a string representing a path. Because this application is used on Windows, OSX and Linux, we've defined environment variables to properly map volumes from the different file systems. The result is:
```
"$C/test/testing"
```
What I want to do is evaluate the environment variables in the string so that they're r... | Use [os.path.expandvars](http://docs.python.org/library/os.path.html#os.path.expandvars) to expand the environment variables in the string, for example:
```
>>> os.path.expandvars('$C/test/testing')
'/stackoverflow/test/testing'
``` |
What are the steps to make a ModelForm work with a ManyToMany relationship with an intermediary model in Django? | 387,686 | 30 | 2008-12-22T22:58:24Z | 932,234 | 18 | 2009-05-31T15:27:30Z | [
"python",
"django",
"django-models",
"django-templates",
"django-forms"
] | * I have a *Client* and *Groupe* Model.
* A *Client* can be part of multiple *groups*.
* *Clients* that are part of a group can use its group's free rental rate at anytime but only once. That is where the intermediary model (*ClientGroupe*) comes in with that extra data.
For now, when I try to save the m2m data, it ju... | If you use the save method right now, Django will try to save using the manager (which Django doesn't allow). Unfortunately, the behavior you want is a little bit trickier than what `ModelForm` does by default. What you need to do is create a *formset*.
First of all, you will need to change the options of your `Client... |
What are the steps to make a ModelForm work with a ManyToMany relationship with an intermediary model in Django? | 387,686 | 30 | 2008-12-22T22:58:24Z | 3,882,808 | 10 | 2010-10-07T14:41:20Z | [
"python",
"django",
"django-models",
"django-templates",
"django-forms"
] | * I have a *Client* and *Groupe* Model.
* A *Client* can be part of multiple *groups*.
* *Clients* that are part of a group can use its group's free rental rate at anytime but only once. That is where the intermediary model (*ClientGroupe*) comes in with that extra data.
For now, when I try to save the m2m data, it ju... | ```
â¦
if form.is_valid():
client_mod = form.save(commit=False)
client_mod.save()
for groupe in form.cleaned_data.get('groupes'):
clientgroupe = ClientGroupe(client=client_mod, groupe=groupe)
clientgroupe.save()
â¦
``` |
How to gracefully deal with failed future feature (__future__) imports due to old interpreter version? | 388,069 | 68 | 2008-12-23T03:10:51Z | 388,083 | 57 | 2008-12-23T03:20:03Z | [
"python",
"python-import"
] | How do you gracefully handle failed future feature imports? If a user is running using Python 2.5 and the first statement in my module is:
```
from __future__ import print_function
```
Compiling this module for Python 2.5 will fail with a:
```
File "__init__.py", line 1
from __future__ import print_function
Sy... | "I'd like to inform the user that they need to rerun the program with Python >= 2.6 and maybe provide some instructions on how to do so."
Isn't that what a README file is for?
Here's your alternative. A "wrapper": a little blob of Python that checks the environment before running your target aop.
File: appwrapper.py... |
How to gracefully deal with failed future feature (__future__) imports due to old interpreter version? | 388,069 | 68 | 2008-12-23T03:10:51Z | 3,037,220 | 46 | 2010-06-14T12:36:33Z | [
"python",
"python-import"
] | How do you gracefully handle failed future feature imports? If a user is running using Python 2.5 and the first statement in my module is:
```
from __future__ import print_function
```
Compiling this module for Python 2.5 will fail with a:
```
File "__init__.py", line 1
from __future__ import print_function
Sy... | A rather hacky but simple method I've used before is to exploit the fact that byte literals were introduced in Python 2.6 and use something like this near the start of the file:
```
b'This module needs Python 2.6 or later. Please do xxx.'
```
This is harmless in Python 2.6 or later, but a `SyntaxError` in any earlier... |
How to gracefully deal with failed future feature (__future__) imports due to old interpreter version? | 388,069 | 68 | 2008-12-23T03:10:51Z | 7,252,783 | 38 | 2011-08-31T05:10:18Z | [
"python",
"python-import"
] | How do you gracefully handle failed future feature imports? If a user is running using Python 2.5 and the first statement in my module is:
```
from __future__ import print_function
```
Compiling this module for Python 2.5 will fail with a:
```
File "__init__.py", line 1
from __future__ import print_function
Sy... | Just put a comment on the same line with the `"from __future__ import ..."`, like this:
```
from __future__ import print_function, division # We require Python 2.6 or later
```
Since Python displays the line containing the error, if you try to run the module with Python 2.5 you'll get a nice, descriptive error:
```... |
How do I use the built in password reset/change views with my own templates | 388,800 | 67 | 2008-12-23T12:47:32Z | 388,858 | 74 | 2008-12-23T13:21:11Z | [
"python",
"django",
"passwords"
] | For example I can point the `url '^/accounts/password/reset/$'` to `django.contrib.auth.views.password_reset` with my template filename in the context but I think need to send more context details.
I need to know exactly what context to add for each of the password reset and change views. | If you take a look at the sources for [django.contrib.auth.views.password\_reset](http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py) you'll see that it uses [`RequestContext`](http://code.djangoproject.com/browser/django/trunk/django/template/__init__.py). The upshot is, you can use Contex... |
How do I use the built in password reset/change views with my own templates | 388,800 | 67 | 2008-12-23T12:47:32Z | 389,679 | 9 | 2008-12-23T18:27:06Z | [
"python",
"django",
"passwords"
] | For example I can point the `url '^/accounts/password/reset/$'` to `django.contrib.auth.views.password_reset` with my template filename in the context but I think need to send more context details.
I need to know exactly what context to add for each of the password reset and change views. | You just need to wrap the existing functions and pass in the template you want. For example:
```
from django.contrib.auth.views import password_reset
def my_password_reset(request, template_name='path/to/my/template'):
return password_reset(request, template_name)
```
To see this just have a look at the function... |
How do I use the built in password reset/change views with my own templates | 388,800 | 67 | 2008-12-23T12:47:32Z | 14,868,595 | 22 | 2013-02-14T05:52:07Z | [
"python",
"django",
"passwords"
] | For example I can point the `url '^/accounts/password/reset/$'` to `django.contrib.auth.views.password_reset` with my template filename in the context but I think need to send more context details.
I need to know exactly what context to add for each of the password reset and change views. | Strongly recommend this article.
I just plugged it in and it worked
<http://garmoncheg.blogspot.com.au/2012/07/django-resetting-passwords-with.html> |
Producing documentation for Python classes | 389,688 | 11 | 2008-12-23T18:30:53Z | 389,704 | 12 | 2008-12-23T18:37:06Z | [
"python",
"data-structures",
"documentation"
] | I'm about to start a project where I will be the only one doing actual code and two less experienced programmers (scary to think of myself as experienced!) will be watching and making suggestions on the program in general.
Is there a good (free) system that I can use to provide documentation for classes and functions ... | I have used [epydoc](http://epydoc.sourceforge.net/) to generate documentation for Python modules from embedded docstrings. It's pretty easy to use and generates nice looking output in multiple formats. |
Producing documentation for Python classes | 389,688 | 11 | 2008-12-23T18:30:53Z | 389,706 | 11 | 2008-12-23T18:37:36Z | [
"python",
"data-structures",
"documentation"
] | I'm about to start a project where I will be the only one doing actual code and two less experienced programmers (scary to think of myself as experienced!) will be watching and making suggestions on the program in general.
Is there a good (free) system that I can use to provide documentation for classes and functions ... | python.org is now using [sphinx](http://sphinx.pocoo.org/) for it's documentation.
I personally like the output of sphinx over epydoc. I also feel the restructured text is easier to read in the docstrings than the epydoc markup. |
How can I read Perl data structures from Python? | 389,945 | 9 | 2008-12-23T20:11:08Z | 389,970 | 17 | 2008-12-23T20:19:38Z | [
"python",
"perl",
"configuration",
"data-structures"
] | I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only:
```
%config = (
'color' => 'red',
'numbers' => [5, 8],
qr/^spam/ => 'eggs'
);
```
What's the best way to convert the contents of these files into Python-equivalent data structures, using pure ... | Is using pure Python a requirement? If not, you can load it in Perl and convert it to YAML or JSON. Then use PyYAML or something similar to load them in Python. |
How can I read Perl data structures from Python? | 389,945 | 9 | 2008-12-23T20:11:08Z | 390,062 | 8 | 2008-12-23T20:56:23Z | [
"python",
"perl",
"configuration",
"data-structures"
] | I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only:
```
%config = (
'color' => 'red',
'numbers' => [5, 8],
qr/^spam/ => 'eggs'
);
```
What's the best way to convert the contents of these files into Python-equivalent data structures, using pure ... | Not sure what the use case is. Here's my assumption: you're going to do a one-time conversion from Perl to Python.
Perl has this
```
%config = (
'color' => 'red',
'numbers' => [5, 8],
qr/^spam/ => 'eggs'
);
```
In Python, it would be
```
config = {
'color' : 'red',
'numbers' : [5, 8],
re.com... |
How can I read Perl data structures from Python? | 389,945 | 9 | 2008-12-23T20:11:08Z | 390,589 | 11 | 2008-12-24T01:41:06Z | [
"python",
"perl",
"configuration",
"data-structures"
] | I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only:
```
%config = (
'color' => 'red',
'numbers' => [5, 8],
qr/^spam/ => 'eggs'
);
```
What's the best way to convert the contents of these files into Python-equivalent data structures, using pure ... | I'd just turn the Perl data structure into something else. Not seeing the actual file, there might be some extra work that my solution doesn't do.
If the only thing that's in the file is the one variable declaration (so, no `1;` at the end, and so on), it can be really simple to turn your `%config` it into YAML:
```
... |
Elegant ways to support equivalence ("equality") in Python classes | 390,250 | 222 | 2008-12-23T22:30:52Z | 390,280 | 8 | 2008-12-23T22:44:26Z | [
"python",
"equality",
"equivalence"
] | When writing custom classes it is often important to allow equivalence by means of the `==` and `!=` operators. In Python, this is made possible by implementing the `__eq__` and `__ne__` special methods, respectively. The easiest way I've found to do this is the following method:
```
class Foo:
def __init__(self, ... | You don't have to override both `__eq__` and `__ne__` you can override only `__cmp__` but this will make an implication on the result of ==, !==, < , > and so on.
`is` tests for object identity. This means a `is` b will be `True` in the case when a and b both hold the reference to the same object. In python you always... |
Elegant ways to support equivalence ("equality") in Python classes | 390,250 | 222 | 2008-12-23T22:30:52Z | 390,511 | 143 | 2008-12-24T00:44:13Z | [
"python",
"equality",
"equivalence"
] | When writing custom classes it is often important to allow equivalence by means of the `==` and `!=` operators. In Python, this is made possible by implementing the `__eq__` and `__ne__` special methods, respectively. The easiest way I've found to do this is the following method:
```
class Foo:
def __init__(self, ... | The way you describe is the way I've always done it. Since it's totally generic, you can always break that functionality out into a mixin class and inherit it in classes where you want that functionality.
```
class CommonEqualityMixin(object):
def __eq__(self, other):
return (isinstance(other, self.__clas... |
Elegant ways to support equivalence ("equality") in Python classes | 390,250 | 222 | 2008-12-23T22:30:52Z | 390,640 | 166 | 2008-12-24T02:30:13Z | [
"python",
"equality",
"equivalence"
] | When writing custom classes it is often important to allow equivalence by means of the `==` and `!=` operators. In Python, this is made possible by implementing the `__eq__` and `__ne__` special methods, respectively. The easiest way I've found to do this is the following method:
```
class Foo:
def __init__(self, ... | You need to be careful with inheritance:
```
>>> class Foo:
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
>>> class Bar(Foo):pass
>>> b = Bar()
>>> f = Foo()
>>> f == b
True
>>> b == f
False
```
Ch... |
Elegant ways to support equivalence ("equality") in Python classes | 390,250 | 222 | 2008-12-23T22:30:52Z | 12,494,556 | 11 | 2012-09-19T12:19:09Z | [
"python",
"equality",
"equivalence"
] | When writing custom classes it is often important to allow equivalence by means of the `==` and `!=` operators. In Python, this is made possible by implementing the `__eq__` and `__ne__` special methods, respectively. The easiest way I've found to do this is the following method:
```
class Foo:
def __init__(self, ... | Not a direct answer but seemed relevant enough to be tacked on as it saves a bit of verbose tedium on occasion. Cut straight from the docs...
---
[functools.total\_ordering(cls)](http://docs.python.org/library/functools.html#functools.total_ordering)
**Given a class defining one or more rich comparison ordering meth... |
Elegant ways to support equivalence ("equality") in Python classes | 390,250 | 222 | 2008-12-23T22:30:52Z | 25,176,504 | 75 | 2014-08-07T07:24:42Z | [
"python",
"equality",
"equivalence"
] | When writing custom classes it is often important to allow equivalence by means of the `==` and `!=` operators. In Python, this is made possible by implementing the `__eq__` and `__ne__` special methods, respectively. The easiest way I've found to do this is the following method:
```
class Foo:
def __init__(self, ... | Sorry, but non of the answers fully "work".
Consider the simple problem:
```
class Number:
"""Very basic"""
def __init__(self, some_number):
self.some_number = some_number
n1 = Number(1)
n2 = Number(1)
print n1 == n2 # False -- oops
```
So, Python by default uses the id of objects for comparison.
`... |
How do you debug Mako templates? | 390,409 | 31 | 2008-12-23T23:43:30Z | 536,087 | 38 | 2009-02-11T09:31:33Z | [
"python",
"debugging",
"templates",
"jinja2",
"mako"
] | So far I've found it impossible to produce usable tracebacks when Mako templates aren't coded correctly.
Is there any way to debug templates besides iterating for every line of code? | Mako actually provides a [VERY nice way to track down errors in a template](http://docs.makotemplates.org/en/latest/usage.html#handling-exceptions):
```
from mako import exceptions
try:
template = lookup.get_template(uri)
print template.render()
except:
print exceptions.html_error_template().render()
``` |
Is there any built-in way to get the length of an iterable in python? | 390,852 | 23 | 2008-12-24T05:55:37Z | 390,861 | 15 | 2008-12-24T06:03:06Z | [
"python",
"iterator"
] | For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines.
One quick way is to do this:
```
lines = len(list(open(fname)))
```
However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to... | If you need a count of lines you can do this, I don't know of any better way to do it:
```
line_count = sum(1 for line in open("yourfile.txt"))
``` |
Is there any built-in way to get the length of an iterable in python? | 390,852 | 23 | 2008-12-24T05:55:37Z | 390,885 | 43 | 2008-12-24T06:23:35Z | [
"python",
"iterator"
] | For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines.
One quick way is to do this:
```
lines = len(list(open(fname)))
```
However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to... | Short of iterating through the iterable and counting the number of iterations, no. That's what makes it an iterable and not a list. This isn't really even a python-specific problem. Look at the classic linked-list data structure. Finding the length is an O(n) operation that involves iterating the whole list to find the... |
Is there any built-in way to get the length of an iterable in python? | 390,852 | 23 | 2008-12-24T05:55:37Z | 390,928 | 8 | 2008-12-24T06:54:08Z | [
"python",
"iterator"
] | For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines.
One quick way is to do this:
```
lines = len(list(open(fname)))
```
However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to... | Absolutely not, for the simple reason that iterables are not guaranteed to be finite.
Consider this perfectly legal generator function:
```
def forever():
while True:
yield "I will run forever"
```
Attempting to calculate the length of this function with `len([x for x in forever()])` will clearly not wor... |
Is there any built-in way to get the length of an iterable in python? | 390,852 | 23 | 2008-12-24T05:55:37Z | 390,989 | 7 | 2008-12-24T07:49:02Z | [
"python",
"iterator"
] | For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines.
One quick way is to do this:
```
lines = len(list(open(fname)))
```
However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to... | I've used this redefinition for some time now:
```
def len(thingy):
try:
return thingy.__len__()
except AttributeError:
return sum(1 for item in iter(thingy))
``` |
Organising my Python project | 391,879 | 45 | 2008-12-24T17:23:14Z | 391,899 | 30 | 2008-12-24T17:31:40Z | [
"python",
"project-organization"
] | I'm starting a Python project and expect to have 20 or more classes in it. As is good practice I want to put them in a separate file each. However, the project directory quickly becomes swamped with files (or will when I do this).
If I put a file to import in a folder I can no longer import it. How do I import a file ... | Create an `__init__.py` file in your projects folder, and it will be treated like a module by Python.
Classes in your package directory can then be imported using syntax like:
```
from package import class
import package.class
```
Within `__init__.py`, you may create an `__all__` array that defines `from package imp... |
Organising my Python project | 391,879 | 45 | 2008-12-24T17:23:14Z | 391,902 | 13 | 2008-12-24T17:33:00Z | [
"python",
"project-organization"
] | I'm starting a Python project and expect to have 20 or more classes in it. As is good practice I want to put them in a separate file each. However, the project directory quickly becomes swamped with files (or will when I do this).
If I put a file to import in a folder I can no longer import it. How do I import a file ... | Python doesn't force you into Java's nasty one-class-per-file style. In fact, it's not even considered good style to put each class in a separate file unless they are huge. (If they are huge, you probably have to do refactoring anyway.) Instead, you should group similar classes and functions in modules. For example, if... |
Organising my Python project | 391,879 | 45 | 2008-12-24T17:23:14Z | 391,904 | 7 | 2008-12-24T17:33:09Z | [
"python",
"project-organization"
] | I'm starting a Python project and expect to have 20 or more classes in it. As is good practice I want to put them in a separate file each. However, the project directory quickly becomes swamped with files (or will when I do this).
If I put a file to import in a folder I can no longer import it. How do I import a file ... | simple answer is to create an empty file called `__init__.py` in the new folder you made. Then in your top level .py file include with something like:
```
import mynewsubfolder.mynewclass
``` |
Organising my Python project | 391,879 | 45 | 2008-12-24T17:23:14Z | 391,916 | 22 | 2008-12-24T17:42:54Z | [
"python",
"project-organization"
] | I'm starting a Python project and expect to have 20 or more classes in it. As is good practice I want to put them in a separate file each. However, the project directory quickly becomes swamped with files (or will when I do this).
If I put a file to import in a folder I can no longer import it. How do I import a file ... | "As is good practice I want to put them in a separate file each. "
This is not actually a very good practice. You should design modules that contain closely-related classes.
As a practical matter, no class actually stands completely alone. Generally classes come in clusters or groups that are logically related. |
Python Optparse list | 392,041 | 33 | 2008-12-24T18:54:52Z | 392,061 | 35 | 2008-12-24T19:03:51Z | [
"python",
"optparse"
] | I'm using the python optparse module in my program, and I'm having trouble finding an easy way to parse an option that contains a list of values.
For example:
```
--groups one,two,three.
```
I'd like to be able to access these values in a list format as `options.groups[]`. Is there an optparse option to convert comm... | Look at [option callbacks](http://docs.python.org/2/library/optparse#option-callbacks). Your callback function can parse the value into a list using a basic `optarg.split(',')` |
Python Optparse list | 392,041 | 33 | 2008-12-24T18:54:52Z | 392,258 | 73 | 2008-12-24T21:50:34Z | [
"python",
"optparse"
] | I'm using the python optparse module in my program, and I'm having trouble finding an easy way to parse an option that contains a list of values.
For example:
```
--groups one,two,three.
```
I'd like to be able to access these values in a list format as `options.groups[]`. Is there an optparse option to convert comm... | S.Lott's answer has already been accepted, but here's a code sample for the archives:
```
def foo_callback(option, opt, value, parser):
setattr(parser.values, option.dest, value.split(','))
parser = OptionParser()
parser.add_option('-f', '--foo',
type='string',
action='callback',... |
Python Optparse list | 392,041 | 33 | 2008-12-24T18:54:52Z | 29,301,200 | 7 | 2015-03-27T12:53:43Z | [
"python",
"optparse"
] | I'm using the python optparse module in my program, and I'm having trouble finding an easy way to parse an option that contains a list of values.
For example:
```
--groups one,two,three.
```
I'd like to be able to access these values in a list format as `options.groups[]`. Is there an optparse option to convert comm... | Again, just for the sake of archive completeness, expanding the example above:
* You can still use "dest" to specify the option name for later access
* Default values cannot be used in such cases (see explanation in [Triggering callback on default value in optparse](http://stackoverflow.com/questions/14568141/triggeri... |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | 51 | 2008-12-24T20:13:06Z | 392,255 | 27 | 2008-12-24T21:43:05Z | [
"python",
"metaclass"
] | I have a friend who likes to use metaclasses, and regularly offers them as a solution.
I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.
Being a... | The purpose of metaclasses isn't to replace the class/object distinction with metaclass/class - it's to change the behaviour of class definitions (and thus their instances) in some way. Effectively it's to alter the behaviour of the class statement in ways that may be more useful for your particular domain than the def... |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | 51 | 2008-12-24T20:13:06Z | 392,442 | 12 | 2008-12-25T02:23:47Z | [
"python",
"metaclass"
] | I have a friend who likes to use metaclasses, and regularly offers them as a solution.
I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.
Being a... | Let's start with Tim Peter's classic quote:
> Metaclasses are deeper magic than 99%
> of users should ever worry about. If
> you wonder whether you need them, you
> don't (the people who actually need
> them know with certainty that they
> need them, and don't need an
> explanation about why). Tim Peters
> (c.l.p post... |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | 51 | 2008-12-24T20:13:06Z | 393,368 | 10 | 2008-12-26T01:35:56Z | [
"python",
"metaclass"
] | I have a friend who likes to use metaclasses, and regularly offers them as a solution.
I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.
Being a... | I have a class that handles non-interactive plotting, as a frontend to Matplotlib. However, on occasion one wants to do interactive plotting. With only a couple functions I found that I was able to increment the figure count, call draw manually, etc, but I needed to do these before and after every plotting call. So to ... |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | 51 | 2008-12-24T20:13:06Z | 31,061,875 | 13 | 2015-06-25T22:26:32Z | [
"python",
"metaclass"
] | I have a friend who likes to use metaclasses, and regularly offers them as a solution.
I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.
Being a... | I was asked the same question recently, and came up with several answers. I hope it's OK to revive this thread, as I wanted to elaborate on a few of the use cases mentioned, and add a few new ones.
Most metaclasses I've seen do one of two things:
1. Registration (adding a class to a data structure):
```
models... |
Modify bound variables of a closure in Python | 392,349 | 22 | 2008-12-24T23:38:30Z | 392,366 | 17 | 2008-12-24T23:58:23Z | [
"python",
"functional-programming",
"closures"
] | Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.
```
def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # ... | I don't think there is any way to do that in Python. When the closure is defined, the current state of variables in the enclosing scope is captured and no longer has a directly referenceable name (from outside the closure). If you were to call `foo()` again, the new closure would have a different set of variables from ... |
Modify bound variables of a closure in Python | 392,349 | 22 | 2008-12-24T23:38:30Z | 392,372 | 8 | 2008-12-25T00:08:52Z | [
"python",
"functional-programming",
"closures"
] | Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.
```
def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # ... | I've found an alternate answer answer to Greg's, slightly less verbose because it uses Python 2.1's custom function attributes (which conveniently enough can be accessed from inside their own function).
```
def foo():
var_b = 3
def _closure(x):
return _closure.var_a + var_b + x
_closure.func_dict['var_a'] = 2
... |
Modify bound variables of a closure in Python | 392,349 | 22 | 2008-12-24T23:38:30Z | 392,468 | 19 | 2008-12-25T03:13:56Z | [
"python",
"functional-programming",
"closures"
] | Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.
```
def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # ... | It is quite possible in python 3 thanks to the magic of [nonlocal](http://jeremyhylton.blogspot.com/2007/02/nonlocal-implemented.html).
```
def foo():
var_a = 2
var_b = 3
def _closure(x, magic = None):
nonlocal var_a
if magic is not None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.