title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python Argument Binders
277,922
39
2008-11-10T14:01:22Z
278,217
9
2008-11-10T15:50:43Z
[ "python" ]
How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s `boost::bind`.
If `functools.partial` is not available then it can be easily emulated: ``` >>> make_printer = lambda s: lambda: sys.stdout.write("%s\n" % s) >>> import sys >>> print_hello = make_printer("hello") >>> print_hello() hello ``` Or ``` def partial(func, *args, **kwargs): def f(*args_rest, **kwargs_rest): kw = kwargs.copy() kw.update(kwargs_rest) return func(*(args + args_rest), **kw) return f def f(a, b): return a + b p = partial(f, 1, 2) print p() # -> 3 p2 = partial(f, 1) print p2(7) # -> 8 d = dict(a=2, b=3) p3 = partial(f, **d) print p3(), p3(a=3), p3() # -> 5 6 5 ```
Python Argument Binders
277,922
39
2008-11-10T14:01:22Z
279,892
7
2008-11-11T03:03:27Z
[ "python" ]
How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s `boost::bind`.
This would work, too: ``` def curry(func, *args): def curried(*innerargs): return func(*(args+innerargs)) curried.__name__ = "%s(%s, ...)" % (func.__name__, ", ".join(map(str, args))) return curried >>> w=curry(sys.stdout.write, "Hey there") >>> w() Hey there ```
Dictionary or If statements, Jython
277,965
4
2008-11-10T14:20:13Z
277,972
14
2008-11-10T14:24:04Z
[ "python", "switch-statement", "jython" ]
I am writing a script at the moment that will grab certain information from HTML using dom4j. Since Python/Jython does not have a native **switch** statement I decided to use a whole bunch of **if** statements that call the appropriate method, like below: ``` if type == 'extractTitle': extractTitle(dom) if type == 'extractMetaTags': extractMetaTags(dom) ``` I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below: ``` { 'extractTitle': extractTitle, 'extractMetaTags': extractMetaTags }[type](dom) ``` I know that each time I run the script the dictionary will be built, but at the same time if I were to use the **if** statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use? **Update:** @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g. ``` handle_extractTag(self, dom, anotherObject) # Do something ``` How would you make the appropriate changes to the **handle** method to implemented this? Hope you know what I mean :) Cheers
To avoid specifying the tag and handler in the dict, you could just use a handler class with methods named to match the type. Eg ``` class MyHandler(object): def handle_extractTitle(self, dom): # do something def handle_extractMetaTags(self, dom): # do something def handle(self, type, dom): func = getattr(self, 'handle_%s' % type, None) if func is None: raise Exception("No handler for type %r" % type) return func(dom) ``` Usage: ``` handler = MyHandler() handler.handle('extractTitle', dom) ``` **Update:** When you have multiple arguments, just change the handle function to take those arguments and pass them through to the function. If you want to make it more generic (so you don't have to change both the handler functions and the handle method when you change the argument signature), you can use the \*args and \*\*kwargs syntax to pass through all received arguments. The handle method then becomes: ``` def handle(self, type, *args, **kwargs): func = getattr(self, 'handle_%s' % type, None) if func is None: raise Exception("No handler for type %r" % type) return func(*args, **kwargs) ```
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
279,253
259
2008-11-10T21:33:33Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
Be sure that dirBar has the `__init__.py` file -- this makes a directory into a Python package.
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
279,287
64
2008-11-10T21:46:04Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
(This is from memory so someone edit if I make a typo, please.) If you structure your project this way: ``` src\ __init__.py main.py dirFoo\ __init__.py Foo.py dirBar\ __init__.py Bar.py ``` Then from Foo.py you should be able to do: ``` import dirFoo.Foo ``` Or: ``` from dirFoo.Foo import FooObject ``` **EDIT 1:** Per Tom's comment, this does require that the `src` folder is accessible either via `site_packages` or your search path. Also, as he mentions, `__init__.py` is implicitly imported when you first import a module in that package/directory. Typically `__init__.py` is simply an empty file.
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
279,338
186
2008-11-10T22:04:27Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
You could also add the sub directory to your python path so that it imports as a normal script. ``` import sys sys.path.append( <path to dirFoo> ) import Bar ```
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
279,389
32
2008-11-10T22:22:47Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
This is the relevant PEP: <http://www.python.org/dev/peps/pep-0328/> In particular, presuming dirFoo is a directory up from dirBar... In dirFoo\Foo.py: ``` from ..dirBar import Bar ```
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
282,778
41
2008-11-12T01:56:51Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
The easiest method is to use sys.path.append(). However, you may be also interested in the [imp](http://docs.python.org/library/imp.html?highlight=imp#module-imp) module. It provides access to internal import functions. ``` # mod_name is the filename without the .py/.pyc extention py_mod = imp.load_source(mod_name,filename_path) # Loads .py file py_mod = imp.load_compiled(mod_name,filename_path) # Loads .pyc file ``` This can be used to load modules dynamically when you don't know a module's name. I've used this in the past to create a plugin type interface to an application, where the user would write a script with application specific functions, and just drop thier script in a specific directory. Also, these functions may be useful: ``` imp.find_module(name[, path]) imp.load_module(name, file, pathname, description) ```
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
3,714,805
11
2010-09-15T05:02:52Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
In my opinion the best choice is to put **\_\_ init \_\_.py** in the folder and call the file with ``` from dirBar.Bar import * ``` It is not recommended to use sys.path.append() because something might gone wrong if you use the same file name as the existing python package. I haven't test that but that will be ambiguous.
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
4,284,378
87
2010-11-26T10:21:28Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
``` import os, sys lib_path = os.path.abspath(os.path.join('..', '..', '..', 'lib')) sys.path.append(lib_path) import mymodule ```
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
4,397,291
71
2010-12-09T10:40:09Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
Just do Simple Things to import py file from different folder- Let's you have a directory like- ``` lib/abc.py ``` Then just keep a empty file in lib folder as named ``` __init__.py ``` and then use ``` from lib.abc import <Your Module name> ``` Keep `__init__.py` file in every folder of hierarchy of import module
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
6,098,238
255
2011-05-23T14:00:43Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
Assuming that both your directories are real python packages (do have the `__init__.py` file inside them), here is a safe solution for inclusion of modules relatively to the location of the script. I assume that you want to do this because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter. ``` import os, sys, inspect # realpath() will make your script run, even if you symlink it :) cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0])) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) # use this if you want to include modules from a subfolder cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder"))) if cmd_subfolder not in sys.path: sys.path.insert(0, cmd_subfolder) # Info: # cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!! # __file__ fails if script is called in different ways on Windows # __file__ fails if someone does os.chdir() before # sys.argv[0] also fails because it doesn't not always contains the path ``` As a bonus, this approach does let you force Python to use your module instead of the ones installed on the system. Warning! I don't really know what is happening when current module is inside an `egg` file. Probably it fails too. Add a comment if you really need a better solution, I may invest few more hours in improving it.
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
7,262,716
8
2011-08-31T20:02:15Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
``` from .dirBar import Bar ``` instead of: ``` from dirBar import Bar ``` just in case there could be another dirBar installed and confuse a foo.py reader.
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
13,963,800
10
2012-12-20T01:07:43Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
## The quick-and-dirty way for Linux users If you are just tinkering around and don't care about deployment issues, you can use a symbolic link (assuming your filesystem supports it) to make the module or package directly visible in the folder of the requesting module. ``` ln -s (path)/module_name.py ``` or ``` ln -s (path)/package_name ``` --- *Note: A "module" is any file with a .py extension and a "package" is any folder that contains the file `__init__.py` (which can be an empty file). From a usage standpoint, modules and packages are identical -- both expose their contained "definitions and statements" as requested via the `import` command.* See: <http://docs.python.org/2/tutorial/modules.html>
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
14,803,823
14
2013-02-10T23:21:51Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
The easiest way without any modification to your script is to set PYTHONPATH environment variable. Cause sys.path is initialized from these locations: 1. the directory containing the input script (or the current directory). 2. PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). 3. the installation-dependent default. Just run: ``` export PYTHONPATH=/absolute/path/to/your/module ``` You sys.path will contains above path, as show below: print sys.path ``` ['', '/absolute/path/to/your/module', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol'] ```
Import a module from a relative path
279,237
555
2008-11-10T21:28:48Z
26,639,332
7
2014-10-29T19:49:53Z
[ "python", "relative-path", "python-import" ]
How do I import a python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
For this case to import Bar.py into Foo.py, first I'd turn these folders into python packages like so: ``` dirFoo\ __init__.py Foo.py dirBar\ __init__.py Bar.py ``` Then I would do it like this in Foo.py: ``` from .dirBar import Bar ``` If I wanted the namespacing to look like Bar.*whatever*, or ``` from . import dirBar ``` If I wanted the namespacing dirBar.Bar.*whatever*. This second case is usefull if you have more modules under the dirBar package.
What is the Python equivalent of static variables inside a function?
279,561
311
2008-11-10T23:33:36Z
279,568
8
2008-11-10T23:37:00Z
[ "python" ]
What is the idiomatic Python equivalent of this C/C++ code? ``` void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } ``` specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
Use a generator function to generate an iterator. ``` def foo_gen(): n = 0 while True: n+=1 yield n ``` Then use it like ``` foo = foo_gen().next for i in range(0,10): print foo() ``` If you want an upper limit: ``` def foo_gen(limit=100000): n = 0 while n < limit: n+=1 yield n ``` If the iterator terminates (like the example above), you can also loop over it directly, like ``` for i in foo_gen(20): print i ``` Of course, in these simple cases it's better to use xrange :) Here is the documentation on the [yield statement](http://docs.python.org/reference/simple_stmts.html#the-yield-statement).
What is the Python equivalent of static variables inside a function?
279,561
311
2008-11-10T23:33:36Z
279,586
376
2008-11-10T23:46:00Z
[ "python" ]
What is the idiomatic Python equivalent of this C/C++ code? ``` void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } ``` specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
A bit reversed, but this should work: ``` def foo(): foo.counter += 1 print "Counter is %d" % foo.counter foo.counter = 0 ``` If you want the counter initialization code at the top instead of the bottom, you can create a decorator: ``` def static_var(varname, value): def decorate(func): setattr(func, varname, value) return func return decorate ``` Then use the code like this: ``` @static_var("counter", 0) def foo(): foo.counter += 1 print "Counter is %d" % foo.counter ``` It'll still require you to use the `foo.` prefix, unfortunately. --- EDIT (thanks to [ony](http://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function/279586#comment41067162_279586)): This looks even nicer: ``` def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate @static_vars(counter=0) def foo(): foo.counter += 1 print "Counter is %d" % foo.counter ```
What is the Python equivalent of static variables inside a function?
279,561
311
2008-11-10T23:33:36Z
279,592
28
2008-11-10T23:47:53Z
[ "python" ]
What is the idiomatic Python equivalent of this C/C++ code? ``` void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } ``` specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
Other answers have demonstrated the way you should do this. Here's a way you shouldn't: ``` >>> def foo(counter=[0]): ... counter[0] += 1 ... print("Counter is %i." % counter[0]); ... >>> foo() Counter is 1. >>> foo() Counter is 2. >>> ``` Default values are initialized only when the function is first evaluated, not each time it is executed, so you can use a list or any other mutable object to store static values.
What is the Python equivalent of static variables inside a function?
279,561
311
2008-11-10T23:33:36Z
279,597
137
2008-11-10T23:53:00Z
[ "python" ]
What is the idiomatic Python equivalent of this C/C++ code? ``` void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } ``` specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
You can add attributes to a function, and use it as a static variable. ``` def myfunc(): myfunc.counter += 1 print myfunc.counter # attribute must be initialized myfunc.counter = 0 ``` Alternatively, if you don't want to setup the variable outside the function, you can use `hasattr()` to avoid an `AttributeError` exception: ``` def myfunc(): if not hasattr(myfunc, "counter"): myfunc.counter = 0 # it doesn't exist yet, so initialize it myfunc.counter += 1 ``` Anyway static variables are rather rare, and you should find a better place for this variable, most likely inside a class.
What is the Python equivalent of static variables inside a function?
279,561
311
2008-11-10T23:33:36Z
279,598
16
2008-11-10T23:53:12Z
[ "python" ]
What is the idiomatic Python equivalent of this C/C++ code? ``` void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } ``` specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
Python doesn't have static variables but you can fake it by defining a callable class object and then using it as a function. [Also see this answer](http://stackoverflow.com/a/593046/4561887). ``` class Foo(object): # Class variable, shared by all instances of this class counter = 0 def __call__(self): Foo.counter += 1 print Foo.counter # Create an object instance of class "Foo," called "foo" foo = Foo() # Make calls to the "__call__" method, via the object's name itself foo() #prints 1 foo() #prints 2 foo() #prints 3 ``` Note that `__call__` makes an instance of a class (object) callable by its own name. That's why calling `foo()` above calls the class' `__call__` method. [From the documentation](https://docs.python.org/3/reference/datamodel.html): > Instances of arbitrary classes can be made callable by defining a `__call__()` method in their class.
What is the Python equivalent of static variables inside a function?
279,561
311
2008-11-10T23:33:36Z
12,270,415
19
2012-09-04T19:51:35Z
[ "python" ]
What is the idiomatic Python equivalent of this C/C++ code? ``` void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } ``` specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
Here is a fully encapsulated version that doesn't require an external initialization call: ``` def mystaticfun(): if "counter" not in vars(mystaticfun): mystaticfun.counter=-1 mystaticfun.counter+=1 print (mystaticfun.counter) ``` In Python, object members are dynamically stored in a special `__dict__` member, and in Python, functions are objects. The built-in `vars()` returns this `__dict__`. EDIT: Note, unlike the alternative `try:except AttributeError` answer, with this approach the variable will always be ready for the code logic following initialization. I think the `try:except AttributeError` alternative to the following will be less DRY and/or have awkward flow: ``` def Fibonacci(n): if n<2: return n if 'memo' not in vars(Fibonacci): Fibonacci.memo={} return Fibonacci.memo.setdefault(n,Fibonacci(n-1)+Fibonacci(n-2)) ```
What is the Python equivalent of static variables inside a function?
279,561
311
2008-11-10T23:33:36Z
16,214,510
86
2013-04-25T12:16:31Z
[ "python" ]
What is the idiomatic Python equivalent of this C/C++ code? ``` void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } ``` specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
One could also consider: ``` def foo(): try: foo.counter += 1 except AttributeError: foo.counter = 1 ``` Reasoning: * much pythonic (`ask for forgiveness not permission`) * use exception (thrown only once) instead of `if` branch (think [StopIteration](https://docs.python.org/2/library/exceptions.html#exceptions.StopIteration) exception)
What is the Python equivalent of static variables inside a function?
279,561
311
2008-11-10T23:33:36Z
27,783,657
15
2015-01-05T16:24:14Z
[ "python" ]
What is the idiomatic Python equivalent of this C/C++ code? ``` void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } ``` specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
Many people have already suggested testing 'hasattr', but there's a simpler answer: ``` def func(): func.counter = getattr(func, 'counter', 0) + 1 ``` No try/except, no testing hasattr, just getattr with a default.
How can one get the set of all classes with reverse relationships for a model in Django?
279,782
4
2008-11-11T01:42:39Z
279,809
14
2008-11-11T02:00:20Z
[ "python", "django", "django-models", "django-orm" ]
Given: ``` from django.db import models class Food(models.Model): """Food, by name.""" name = models.CharField(max_length=25) class Cat(models.Model): """A cat eats one type of food""" food = models.ForeignKey(Food) class Cow(models.Model): """A cow eats one type of food""" food = models.ForeignKey(Food) class Human(models.Model): """A human may eat lots of types of food""" food = models.ManyToManyField(Food) ``` How can one, given only the class Food, get a set of all classes that it has "reverse relationships" to. I.e. given the class **Food**, how can one get the classes **Cat**, **Cow** and **Human**. I would think it's possible because Food has the three "reverse relations": *Food.cat\_set*, *Food.cow\_set*, and *Food.human\_set*. Help's appreciated & thank you!
Some digging in the source code revealed: django/db/models/options.py: ``` def get_all_related_objects(self, local_only=False): def get_all_related_many_to_many_objects(self, local_only=False) ``` And, using these functions on the models from above, you hypothetically get: ``` >>> Food._meta.get_all_related_objects() [<RelatedObject: app_label:cow related to food>, <RelatedObject: app_label:cat related to food>,] >>> Food._meta.get_all_related_many_to_many_objects() [<RelatedObject: app_label:human related to food>,] # and, per django/db/models/related.py # you can retrieve the model with >>> Food._meta.get_all_related_objects()[0].model <class 'app_label.models.Cow'> ``` *Note*: I hear Model.\_meta is 'unstable', and perhaps ought not to be relied upon in the post Django-1.0 world. Thanks for reading. :)
How can one get the set of all classes with reverse relationships for a model in Django?
279,782
4
2008-11-11T01:42:39Z
279,952
7
2008-11-11T03:48:52Z
[ "python", "django", "django-models", "django-orm" ]
Given: ``` from django.db import models class Food(models.Model): """Food, by name.""" name = models.CharField(max_length=25) class Cat(models.Model): """A cat eats one type of food""" food = models.ForeignKey(Food) class Cow(models.Model): """A cow eats one type of food""" food = models.ForeignKey(Food) class Human(models.Model): """A human may eat lots of types of food""" food = models.ManyToManyField(Food) ``` How can one, given only the class Food, get a set of all classes that it has "reverse relationships" to. I.e. given the class **Food**, how can one get the classes **Cat**, **Cow** and **Human**. I would think it's possible because Food has the three "reverse relations": *Food.cat\_set*, *Food.cow\_set*, and *Food.human\_set*. Help's appreciated & thank you!
Either A) Use [multiple table inheritance](http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance) and create a "Eater" base class, that Cat, Cow and Human inherit from. B) Use a [Generic Relation](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1), where Food could be linked to any other Model. Those are well-documented and officially supported features, you'd better stick to them to keep your own code clean, avoid workarounds and be sure it'll be still supported in the future. -- EDIT ( A.k.a. "how to be a reputation whore" ) So, here is a recipe for that particular case. Let's assume you absolutely want separate models for Cat, Cow and Human. In a real-world application, you want to ask to yourself why a "category" field wouldn't do the job. It's easier to get to the "real" class through generic relations, so here is the implementation for B. We can't have that 'food' field in Person, Cat or Cow, or we'll run into the same problems. So we'll create an intermediary "FoodConsumer" model. We'll have to write additional validation tests if we don't want more than one food for an instance. ``` from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Food(models.Model): """Food, by name.""" name = models.CharField(max_length=25) # ConsumedFood has a foreign key to Food, and a "eaten_by" generic relation class ConsumedFood(models.Model): food = models.ForeignKey(Food, related_name="eaters") content_type = models.ForeignKey(ContentType, null=True) object_id = models.PositiveIntegerField(null=True) eaten_by = generic.GenericForeignKey('content_type', 'object_id') class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField() address = models.CharField(max_length=100) city = models.CharField(max_length=50) foods = generic.GenericRelation(ConsumedFood) class Cat(models.Model): name = models.CharField(max_length=50) foods = generic.GenericRelation(ConsumedFood) class Cow(models.Model): farmer = models.ForeignKey(Person) foods = generic.GenericRelation(ConsumedFood) ``` Now, to demonstrate it let's just write this working [doctest](http://docs.djangoproject.com/en/dev/topics/testing/#writing-doctests): ``` """ >>> from models import * Create some food records >>> weed = Food(name="weed") >>> weed.save() >>> burger = Food(name="burger") >>> burger.save() >>> pet_food = Food(name="Pet food") >>> pet_food.save() John the farmer likes burgers >>> john = Person(first_name="John", last_name="Farmer", birth_date="1960-10-12") >>> john.save() >>> john.foods.create(food=burger) <ConsumedFood: ConsumedFood object> Wilma the cow eats weed >>> wilma = Cow(farmer=john) >>> wilma.save() >>> wilma.foods.create(food=weed) <ConsumedFood: ConsumedFood object> Felix the cat likes pet food >>> felix = Cat(name="felix") >>> felix.save() >>> pet_food.eaters.create(eaten_by=felix) <ConsumedFood: ConsumedFood object> What food john likes again ? >>> john.foods.all()[0].food.name u'burger' Who's getting pet food ? >>> living_thing = pet_food.eaters.all()[0].eaten_by >>> isinstance(living_thing,Cow) False >>> isinstance(living_thing,Cat) True John's farm is in fire ! He looses his cow. >>> wilma.delete() John is a lot poorer right now >>> john.foods.clear() >>> john.foods.create(food=pet_food) <ConsumedFood: ConsumedFood object> Who's eating pet food now ? >>> for consumed_food in pet_food.eaters.all(): ... consumed_food.eaten_by <Cat: Cat object> <Person: Person object> Get the second pet food eater >>> living_thing = pet_food.eaters.all()[1].eaten_by Try to find if it's a person and reveal his name >>> if isinstance(living_thing,Person): living_thing.first_name u'John' """ ```
PyOpenGl or pyglet?
279,912
24
2008-11-11T03:17:03Z
279,970
26
2008-11-11T04:03:04Z
[ "python", "pyglet", "pyopengl" ]
I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet Which would you recommend and why?
As Tony said, this is really going to depend on your goals. If you're "tinkering" to try to learn about OpenGL or 3D rendering in general that I would dispense with all pleasantries and start working with PyOpenGL, which is as close are you're going to get to "raw" 3D programming using Python. On the other hand, if you're "tinkering" by way of mocking up a game or multimedia application, or trying to learn about programming practices in general than Pyglet will save you lots of up-front development time by providing hooks for input events, sounds, text/billboarding, etc. Often, this up-front investment is what prevents people from completing their projects, so having it done for you is not something to be ignored. (It is also very Pythonic to avoid reinventing the wheel.) If you are looking to do any sort of heavy-duty lifting (which normally falls outside my definition of "tinkering", but maybe not if you're tinkering with 3D engine design) then you might want to take a look at [Python-Ogre](http://www.python-ogre.org/), which wraps the *very* full-featured and robust [OGRE 3D](http://www.ogre3d.org/) graphics engine.
PyOpenGl or pyglet?
279,912
24
2008-11-11T03:17:03Z
4,246,325
22
2010-11-22T14:21:04Z
[ "python", "pyglet", "pyopengl" ]
I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pyglet Which would you recommend and why?
Start with pyglet. It contains the best high-level API, which contains all you need to get started, from opening a window to drawing sprites and OpenGL primitives using their friendly and powerful Sprite and Batch classes. Later, you might also want to write your own lower-level code, that makes calls directly to OpenGL functions such as glDrawArrays, etc. You can do this using pyglet's OpenGL bindings, or using PyOpenGL's. The good news is that whichever you use, you can insert such calls right into the middle of your existing pyglet application, and they will 'just work'. Transitioning your code from Pyglet to PyOpenGL is fairly easy, so this is not a decision you need to worry about too much upfront. The trades-off between the two are: PyOpenGL's bindings make the OpenGL interface more friendly and pythonic. For example, you can pass vertex arrays in many different forms, ctypes arrays, numpy arrays, plain lists, etc, and PyOpenGL will convert them into something OpenGL can use. Things like this make PyOpenGL really easy and convenient. pyglet's OpenGL bindings are automatically generated, and are not as friendly to use as PyOpenGL. For example, sometimes you will have to manually create ctypes objects, in order to pass 'C pointer' kinds of args to OpenGL. This can be fiddly. The plus side though, is pyglet's bindings tends to be significantly faster. This implies that there is an optimal middle ground: Use pyglet for windowing, mouse events, sound, etc. Then use PyOpenGL's friendly API when you want to make direct OpenGL function calls. Then when optimising, replace just the small percentage of performance-critical PyOpenGL calls that lie within your inner render loop with the pyglet equivalents. For me, this gives me between 2 and 4 times faster framerates, with PyOpenGL's convenience for 90% of my code.
Python - sort a list of nested lists
280,222
13
2008-11-11T07:15:56Z
280,226
12
2008-11-11T07:19:20Z
[ "python", "list", "sorting", "nested-lists" ]
I have input consisting of a list of nested lists like this: ``` l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] ``` I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this: ``` [39, 6, 13, 50] ``` Then I want to sort based on these. So the output should be: ``` [[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]] ``` What's a nice pythonic way of doing this?
A little recursive function would do it: ``` def asum(a): if isinstance(a, list): return sum(asum(x) for x in a) else: return a l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] l.sort(key=asum) print l ```
Python - sort a list of nested lists
280,222
13
2008-11-11T07:15:56Z
280,865
15
2008-11-11T13:26:37Z
[ "python", "list", "sorting", "nested-lists" ]
I have input consisting of a list of nested lists like this: ``` l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] ``` I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this: ``` [39, 6, 13, 50] ``` Then I want to sort based on these. So the output should be: ``` [[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]] ``` What's a nice pythonic way of doing this?
A slight simplification and generalization to the answers provided so far, using a recent addition to python's syntax: ``` >>> l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] >>> def asum(t): return sum(map(asum, t)) if hasattr(t, '__iter__') else t ... >>> sorted(l, key=asum) [[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]] ```
Python Linked List
280,243
110
2008-11-11T07:31:21Z
280,284
10
2008-11-11T07:54:20Z
[ "python", "linked-list" ]
What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by `'(1 2 3 4 5)`. Python's lists, `[1, 2, 3, 4, 5]`, and tuples, `(1, 2, 3, 4, 5)`, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!
Immutable lists are best represented through two-tuples, with None representing NIL. To allow simple formulation of such lists, you can use this function: ``` def mklist(*args): result = None for element in reversed(args): result = (element, result) return result ``` To work with such lists, I'd rather provide the whole collection of LISP functions (i.e. first, second, nth, etc), than introducing methods.
Python Linked List
280,243
110
2008-11-11T07:31:21Z
280,286
35
2008-11-11T07:54:49Z
[ "python", "linked-list" ]
What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by `'(1 2 3 4 5)`. Python's lists, `[1, 2, 3, 4, 5]`, and tuples, `(1, 2, 3, 4, 5)`, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!
I wrote this up the other day ``` #! /usr/bin/env python class node: def __init__(self): self.data = None # contains the data self.next = None # contains the reference to the next node class linked_list: def __init__(self): self.cur_node = None def add_node(self, data): new_node = node() # create a new node new_node.data = data new_node.next = self.cur_node # link the new node to the 'previous' node. self.cur_node = new_node # set the current node to the new one. def list_print(self): node = self.cur_node # cant point to ll! while node: print node.data node = node.next ll = linked_list() ll.add_node(1) ll.add_node(2) ll.add_node(3) ll.list_print() ```
Python Linked List
280,243
110
2008-11-11T07:31:21Z
281,294
11
2008-11-11T15:59:46Z
[ "python", "linked-list" ]
What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by `'(1 2 3 4 5)`. Python's lists, `[1, 2, 3, 4, 5]`, and tuples, `(1, 2, 3, 4, 5)`, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!
Here's a slightly more complex version of a linked list class, with a similar interface to python's sequence types (ie. supports indexing, slicing, concatenation with arbitrary sequences etc). It should have O(1) prepend, doesn't copy data unless it needs to and can be used pretty interchangably with tuples. It won't be as space or time efficient as lisp cons cells, as python classes are obviously a bit more heavyweight (You could improve things slightly with "`__slots__ = '_head','_tail'`" to reduce memory usage). It will have the desired big O performance characteristics however. Example of usage: ``` >>> l = LinkedList([1,2,3,4]) >>> l LinkedList([1, 2, 3, 4]) >>> l.head, l.tail (1, LinkedList([2, 3, 4])) # Prepending is O(1) and can be done with: LinkedList.cons(0, l) LinkedList([0, 1, 2, 3, 4]) # Or prepending arbitrary sequences (Still no copy of l performed): [-1,0] + l LinkedList([-1, 0, 1, 2, 3, 4]) # Normal list indexing and slice operations can be performed. # Again, no copy is made unless needed. >>> l[1], l[-1], l[2:] (2, 4, LinkedList([3, 4])) >>> assert l[2:] is l.next.next # For cases where the slice stops before the end, or uses a # non-contiguous range, we do need to create a copy. However # this should be transparent to the user. >>> LinkedList(range(100))[-10::2] LinkedList([90, 92, 94, 96, 98]) ``` Implementation: ``` import itertools class LinkedList(object): """Immutable linked list class.""" def __new__(cls, l=[]): if isinstance(l, LinkedList): return l # Immutable, so no copy needed. i = iter(l) try: head = i.next() except StopIteration: return cls.EmptyList # Return empty list singleton. tail = LinkedList(i) obj = super(LinkedList, cls).__new__(cls) obj._head = head obj._tail = tail return obj @classmethod def cons(cls, head, tail): ll = cls([head]) if not isinstance(tail, cls): tail = cls(tail) ll._tail = tail return ll # head and tail are not modifiable @property def head(self): return self._head @property def tail(self): return self._tail def __nonzero__(self): return True def __len__(self): return sum(1 for _ in self) def __add__(self, other): other = LinkedList(other) if not self: return other # () + l = l start=l = LinkedList(iter(self)) # Create copy, as we'll mutate while l: if not l._tail: # Last element? l._tail = other break l = l._tail return start def __radd__(self, other): return LinkedList(other) + self def __iter__(self): x=self while x: yield x.head x=x.tail def __getitem__(self, idx): """Get item at specified index""" if isinstance(idx, slice): # Special case: Avoid constructing a new list, or performing O(n) length # calculation for slices like l[3:]. Since we're immutable, just return # the appropriate node. This becomes O(start) rather than O(n). # We can't do this for more complicated slices however (eg [l:4] start = idx.start or 0 if (start >= 0) and (idx.stop is None) and (idx.step is None or idx.step == 1): no_copy_needed=True else: length = len(self) # Need to calc length. start, stop, step = idx.indices(length) no_copy_needed = (stop == length) and (step == 1) if no_copy_needed: l = self for i in range(start): if not l: break # End of list. l=l.tail return l else: # We need to construct a new list. if step < 1: # Need to instantiate list to deal with -ve step return LinkedList(list(self)[start:stop:step]) else: return LinkedList(itertools.islice(iter(self), start, stop, step)) else: # Non-slice index. if idx < 0: idx = len(self)+idx if not self: raise IndexError("list index out of range") if idx == 0: return self.head return self.tail[idx-1] def __mul__(self, n): if n <= 0: return Nil l=self for i in range(n-1): l += self return l def __rmul__(self, n): return self * n # Ideally we should compute the has ourselves rather than construct # a temporary tuple as below. I haven't impemented this here def __hash__(self): return hash(tuple(self)) def __eq__(self, other): return self._cmp(other) == 0 def __ne__(self, other): return not self == other def __lt__(self, other): return self._cmp(other) < 0 def __gt__(self, other): return self._cmp(other) > 0 def __le__(self, other): return self._cmp(other) <= 0 def __ge__(self, other): return self._cmp(other) >= 0 def _cmp(self, other): """Acts as cmp(): -1 for self<other, 0 for equal, 1 for greater""" if not isinstance(other, LinkedList): return cmp(LinkedList,type(other)) # Arbitrary ordering. A, B = iter(self), iter(other) for a,b in itertools.izip(A,B): if a<b: return -1 elif a > b: return 1 try: A.next() return 1 # a has more items. except StopIteration: pass try: B.next() return -1 # b has more items. except StopIteration: pass return 0 # Lists are equal def __repr__(self): return "LinkedList([%s])" % ', '.join(map(repr,self)) class EmptyList(LinkedList): """A singleton representing an empty list.""" def __new__(cls): return object.__new__(cls) def __iter__(self): return iter([]) def __nonzero__(self): return False @property def head(self): raise IndexError("End of list") @property def tail(self): raise IndexError("End of list") # Create EmptyList singleton LinkedList.EmptyList = EmptyList() del EmptyList ```
Python Linked List
280,243
110
2008-11-11T07:31:21Z
282,238
112
2008-11-11T21:45:30Z
[ "python", "linked-list" ]
What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by `'(1 2 3 4 5)`. Python's lists, `[1, 2, 3, 4, 5]`, and tuples, `(1, 2, 3, 4, 5)`, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!
For some needs, a [deque](https://docs.python.org/library/collections.html#collections.deque) may also be useful. You can add and remove items on both ends of a deque at O(1) cost. ``` from collections import deque d = deque([1,2,3,4]) print d for x in d: print x print d.pop(), d ```
Python Linked List
280,243
110
2008-11-11T07:31:21Z
283,630
51
2008-11-12T11:10:15Z
[ "python", "linked-list" ]
What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by `'(1 2 3 4 5)`. Python's lists, `[1, 2, 3, 4, 5]`, and tuples, `(1, 2, 3, 4, 5)`, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!
Here is some list functions based on [Martin v. Löwis's representation](http://stackoverflow.com/questions/280243/python-linked-list#280284): ``` cons = lambda el, lst: (el, lst) mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None) car = lambda lst: lst[0] if lst else lst cdr = lambda lst: lst[1] if lst else lst nth = lambda n, lst: nth(n-1, cdr(lst)) if n > 0 else car(lst) length = lambda lst, count=0: length(cdr(lst), count+1) if lst else count begin = lambda *args: args[-1] display = lambda lst: begin(w("%s " % car(lst)), display(cdr(lst))) if lst else w("nil\n") ``` where `w = sys.stdout.write` Linked lists have no practical value in Python. I've *never* used a linked list in Python for any problem except educational. Thomas Watnedal [suggested](http://stackoverflow.com/questions/280243/python-linked-list#280280) a good educational resource [How to Think Like a Computer Scientist, Chapter 17: Linked lists](http://greenteapress.com/thinkpython/html/chap17.html): A linked list is either: * the empty list, represented by None, or * a node that contains a cargo object and a reference to a linked list. ``` class Node: def __init__(self, cargo=None, next=None): self.car = cargo self.cdr = next def __str__(self): return str(self.car) def display(lst): if lst: w("%s " % lst) display(lst.cdr) else: w("nil\n") ```
Python Linked List
280,243
110
2008-11-11T07:31:21Z
3,538,133
13
2010-08-21T16:04:51Z
[ "python", "linked-list" ]
What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by `'(1 2 3 4 5)`. Python's lists, `[1, 2, 3, 4, 5]`, and tuples, `(1, 2, 3, 4, 5)`, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!
The accepted answer is rather complicated. Here is a more standard design: ``` L = LinkedList() L.insert(1) L.insert(1) L.insert(2) L.insert(4) print L L.clear() print L ``` It is a simple `LinkedList` class based on the straightforward C++ design and [Chapter 17: Linked lists](http://greenteapress.com/thinkpython/html/chap17.html), as recommended by [Thomas Watnedal](http://stackoverflow.com/questions/280243/python-linked-list/280280#280280). ``` class Node: def __init__(self, value = None, next = None): self.value = value self.next = next def __str__(self): return 'Node ['+str(self.value)+']' class LinkedList: def __init__(self): self.first = None self.last = None def insert(self, x): if self.first == None: self.first = Node(x, None) self.last = self.first elif self.last == self.first: self.last = Node(x, None) self.first.next = self.last else: current = Node(x, None) self.last.next = current self.last = current def __str__(self): if self.first != None: current = self.first out = 'LinkedList [\n' +str(current.value) +'\n' while current.next != None: current = current.next out += str(current.value) + '\n' return out + ']' return 'LinkedList []' def clear(self): self.__init__() ```
When is "self" required?
280,324
9
2008-11-11T08:24:00Z
280,561
7
2008-11-11T10:42:20Z
[ "python", "wxpython" ]
I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo. However, I'm looking through the *wxPython in Action* book and notice that "self" isn't used all the time. For example: ``` import wx class TextFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'Text Entry Example', size=(300, 100)) panel = wx.Panel(self, -1) basicLabel = wx.StaticText(panel, -1, "Basic Control:") basicText = wx.TextCtrl(panel, -1, "I've entered some text!", size=(175, -1)) basicText.SetInsertionPoint(0) pwdLabel = wx.StaticText(panel, -1, "Password:") pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1), style=wx.TE_PASSWORD) sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6) sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText]) panel.SetSizer(sizer) ``` The one below does use "self". ``` import wx class ButtonFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'Button Example', size=(300, 100)) panel = wx.Panel(self, -1) self.button = wx.Button(panel, -1, "Hello", pos=(50, 20)) self.Bind(wx.EVT_BUTTON, self.OnClick, self.button) self.button.SetDefault() def OnClick(self, event): self.button.SetLabel("Clicked") ``` If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb?
You use `self.attribute` to reference an attribute of your current instance. You use `wx.Frame.__init__()` to reference a method of the parent class. You don't use `self` if you only reference a local name (variable) of the method (function) you are in. These are not "rules of thumb," because there are no exceptions. --- What is probably confusing you in this particular example is that panel seems to be only a local name in the constructor, so it looks like the panel would disappear, once your constructor returns. If you look at the documentation to `wx.Panel`, though, you will see that *its* constructor attaches the panel to the parent window, so it will continue to exist, even after the constructor returns. Magic :)
Escaping regex string in Python
280,435
128
2008-11-11T09:33:29Z
280,441
174
2008-11-11T09:37:37Z
[ "python", "regex" ]
I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex? For example, the user wants to search for Word `(s)`: regex engine will take the `(s)` as a group. I want it to treat it like a string `"(s)"` . I can run `replace` on user input and replace the `(` with `\(` and the `)` with `\)` but the problem is I will need to do replace for every possible regex symbol. Do you know some better way ?
Use the `re.escape()` function for this: [4.2.3 `re` Module Contents](http://docs.python.org/library/re.html#re.escape) > **escape(string)** > > Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object. ``` def simplistic_plural(word, text): word_or_plural = re.escape(word) + 's?' return re.match(word_or_plural, text) ```
Escaping regex string in Python
280,435
128
2008-11-11T09:33:29Z
280,463
33
2008-11-11T09:49:25Z
[ "python", "regex" ]
I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex? For example, the user wants to search for Word `(s)`: regex engine will take the `(s)` as a group. I want it to treat it like a string `"(s)"` . I can run `replace` on user input and replace the `(` with `\(` and the `)` with `\)` but the problem is I will need to do replace for every possible regex symbol. Do you know some better way ?
You can use [re.escape()](http://docs.python.org/library/re.html#re.escape): > re.escape(string) > Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. ``` >>> import re >>> re.escape('^a.*$') '\\^a\\.\\*\\$' ```
Calculate poisson probability percentage
280,797
16
2008-11-11T12:51:43Z
280,843
20
2008-11-11T13:17:55Z
[ "python", "statistics", "poisson" ]
When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments: * an integer * an 'average' number and returns a float. In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers. What I really want is the percentage that this event will occur (it is a constant number and the array has every time different numbers - so is it an average?). for example: ``` print poisson(2.6,6) ``` returns `[1 3 3 0 1 3]` (and every time I run it, it's different). The number I get from calc/excel is 3.19 (`POISSON(6,2.16,0)*100`). Am I using the python's poisson wrong (no pun!) or am I missing something?
`scipy` has what you want ``` >>> scipy.stats.distributions <module 'scipy.stats.distributions' from '/home/coventry/lib/python2.5/site-packages/scipy/stats/distributions.pyc'> >>> scipy.stats.distributions.poisson.pmf(6, 2.6) array(0.031867055625524499) ``` It's worth noting that it's pretty easy to calculate by hand, [too](http://www.scipy.org/doc/api_docs/SciPy.stats.distributions.html#poisson).
Calculate poisson probability percentage
280,797
16
2008-11-11T12:51:43Z
280,862
12
2008-11-11T13:24:40Z
[ "python", "statistics", "poisson" ]
When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments: * an integer * an 'average' number and returns a float. In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers. What I really want is the percentage that this event will occur (it is a constant number and the array has every time different numbers - so is it an average?). for example: ``` print poisson(2.6,6) ``` returns `[1 3 3 0 1 3]` (and every time I run it, it's different). The number I get from calc/excel is 3.19 (`POISSON(6,2.16,0)*100`). Am I using the python's poisson wrong (no pun!) or am I missing something?
It is easy to do by hand, but you can overflow doing it that way. You can do the exponent and factorial in a loop to avoid the overflow: ``` def poisson_probability(actual, mean): # naive: math.exp(-mean) * mean**actual / factorial(actual) # iterative, to keep the components from getting too large or small: p = math.exp(-mean) for i in xrange(actual): p *= mean p /= i+1 return p ```
Controlling the mouse from Python in OS X
281,133
19
2008-11-11T15:04:43Z
281,330
7
2008-11-11T16:10:11Z
[ "python", "osx", "mouse" ]
What would be the easiest way to move the mouse around (and possibly click) using python on OS X? This is just for rapid prototyping, it doesn't have to be elegant. Thanks!
I dug through the source code of Synergy to find the call that generates mouse events: ``` #include <ApplicationServices/ApplicationServices.h> int to(int x, int y) { CGPoint newloc; CGEventRef eventRef; newloc.x = x; newloc.y = y; eventRef = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, newloc, kCGMouseButtonCenter); //Apparently, a bug in xcode requires this next line CGEventSetType(eventRef, kCGEventMouseMoved); CGEventPost(kCGSessionEventTap, eventRef); CFRelease(eventRef); return 0; } ``` Now to write Python bindings!
Controlling the mouse from Python in OS X
281,133
19
2008-11-11T15:04:43Z
281,366
8
2008-11-11T16:23:20Z
[ "python", "osx", "mouse" ]
What would be the easiest way to move the mouse around (and possibly click) using python on OS X? This is just for rapid prototyping, it doesn't have to be elegant. Thanks!
When I wanted to do it, I installed [Jython](http://www.jython.org/Project/) and used the [`java.awt.Robot`](http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Robot.html) class. If you need to make a CPython script this is obviously not suitable, but when you the flexibility to choose anything it is a nice cross-platform solution. ``` import java.awt robot = java.awt.Robot() robot.mouseMove(x, y) robot.mousePress(java.awt.event.InputEvent.BUTTON1_MASK) robot.mouseRelease(java.awt.event.InputEvent.BUTTON1_MASK) ```
Controlling the mouse from Python in OS X
281,133
19
2008-11-11T15:04:43Z
664,417
9
2009-03-19T23:15:07Z
[ "python", "osx", "mouse" ]
What would be the easiest way to move the mouse around (and possibly click) using python on OS X? This is just for rapid prototyping, it doesn't have to be elegant. Thanks!
Just try this code: ``` #!/usr/bin/python import objc class ETMouse(): def setMousePosition(self, x, y): bndl = objc.loadBundle('CoreGraphics', globals(), '/System/Library/Frameworks/ApplicationServices.framework') objc.loadBundleFunctions(bndl, globals(), [('CGWarpMouseCursorPosition', 'v{CGPoint=ff}')]) CGWarpMouseCursorPosition((x, y)) if __name__ == "__main__": et = ETMouse() et.setMousePosition(200, 200) ``` it works in OSX leopard 10.5.6
Controlling the mouse from Python in OS X
281,133
19
2008-11-11T15:04:43Z
8,202,674
19
2011-11-20T15:48:30Z
[ "python", "osx", "mouse" ]
What would be the easiest way to move the mouse around (and possibly click) using python on OS X? This is just for rapid prototyping, it doesn't have to be elegant. Thanks!
Try the code at <http://www.geekorgy.com/index.php/2010/06/python-mouse-click-and-move-mouse-in-apple-mac-osx-snow-leopard-10-6-x/>, pasted below in case the site disappears. It defines a couple of functions, mousemove and mouseclick, which hook into Apple's integration between Python and the platform's Quartz libraries. This code works on 10.6, and I'm using it on 10.7. The nice thing about this code is that it generates mouse events, which some solutions don't. I use it to control BBC iPlayer by sending mouse events to known button positions in their Flash player (very brittle I know). The mouse move events, in particular, are required as otherwise the Flash player never hides the mouse cursor. Functions like CGWarpMouseCursorPosition will not do this. ``` from Quartz.CoreGraphics import CGEventCreateMouseEvent from Quartz.CoreGraphics import CGEventPost from Quartz.CoreGraphics import kCGEventMouseMoved from Quartz.CoreGraphics import kCGEventLeftMouseDown from Quartz.CoreGraphics import kCGEventLeftMouseDown from Quartz.CoreGraphics import kCGEventLeftMouseUp from Quartz.CoreGraphics import kCGMouseButtonLeft from Quartz.CoreGraphics import kCGHIDEventTap def mouseEvent(type, posx, posy): theEvent = CGEventCreateMouseEvent( None, type, (posx,posy), kCGMouseButtonLeft) CGEventPost(kCGHIDEventTap, theEvent) def mousemove(posx,posy): mouseEvent(kCGEventMouseMoved, posx,posy); def mouseclick(posx,posy): # uncomment this line if you want to force the mouse # to MOVE to the click location first (I found it was not necessary). #mouseEvent(kCGEventMouseMoved, posx,posy); mouseEvent(kCGEventLeftMouseDown, posx,posy); mouseEvent(kCGEventLeftMouseUp, posx,posy); ```
Open explorer on a file
281,888
30
2008-11-11T19:24:56Z
281,911
33
2008-11-11T19:33:14Z
[ "python", "windows", "explorer" ]
In Python, how do I jump to a file in the Windows Explorer? I found a solution for jumping to folders: ``` import subprocess subprocess.Popen('explorer "C:\path\of\folder"') ``` but I have no solution for files.
From [Explorer.exe Command-Line Options for Windows XP](http://support.microsoft.com/kb/314853) ``` import subprocess subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"') ```
Python decorating functions before call
282,393
6
2008-11-11T22:42:44Z
282,399
21
2008-11-11T22:45:52Z
[ "python", "decorator" ]
I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?
With: ``` decorator(original_function)() ``` Without: ``` original_function() ``` A decorator is just a function which takes a function as an argument and returns another one. The @ syntax is totally optional. Perhaps a sift through some [documentation](https://wiki.python.org/moin/PythonDecorators) might help clarify things.
Django debugging with Emacs
283,294
20
2008-11-12T08:15:26Z
284,607
17
2008-11-12T16:57:37Z
[ "python", "django", "debugging", "emacs" ]
I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application? I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?
This isn't emacs specific, but you can use the Python debugger by adding the following to a Django view function: `import pdb; pdb.set_trace()` Now when you run the development server and view the page, your browser will appear to hang or load very slowly - switch over to your console, and you have access to the full debugger. You can inspect AND modify state of your application via an interactive shell - check out the Python documentation for the debugger, or this link for some [Python debugging examples](http://www.onlamp.com/pub/a/python/2005/09/01/debugger.html) --- If all you need is logging, add the following to your `settings.py`: ``` logging.basicConfig( level = logging.DEBUG, format = '%(asctime)s %(levelname)s %(message)s', filename = '/tmp/mylog.log', filemode = 'w' ) ``` Now you can log messages to `/tmp/mylog.log` by adding the following to any view function: ``` import logging logging.debug("Something happened") ```
Django debugging with Emacs
283,294
20
2008-11-12T08:15:26Z
1,665,783
13
2009-11-03T07:33:57Z
[ "python", "django", "debugging", "emacs" ]
I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application? I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?
Start pdb like this: `M-x` `pdb` Then, start the Django development server: ``` python manage.py runserver --noreload ``` Once you have the (Pdb) prompt, you need to do this: ``` import sys sys.path.append('/path/to/directory/containing/views.py') ``` Once you've done this, you should be able to set breakpoints normally. Just navigate to the line number you want, and `C-x` `SPC`
Is it possible to use wxPython inside IronPython?
283,447
4
2008-11-12T09:49:43Z
283,520
8
2008-11-12T10:27:31Z
[ "python", "wxpython", "ironpython" ]
When my IronPython program gets to the line ``` import wx ``` I get this message: ``` A first chance exception of type 'IronPython.Runtime.Exceptions.PythonImportErrorException' occurred in IronPython.dll Additional information: No module named _core_ ``` although I do have the file wx\\_core\_.pyd. Also, before attempting the import, I have the lines: ``` sys.path.append('c:\\Python24\\Lib\\site-packages') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx\\lib') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wxpython\\lib') sys.path.append('c:\\Python24\\Lib\\site-packages\\wxaddons') ``` which I hoped would let IronPython find everything it needed.
No, this won't work. Wx bindings (like most other "python bindings") are actually compiled against CPython. In this regards they are not just packages on sys.path to be found, as you have tried. They actually depend on CPython itself. [This rather dry document explains the process.](http://www.python.org/doc/2.5.2/ext/ext.html) Note: There was a mission by some of the crew at Resolver Systems to allow you to use CPython bindings with IronPython (called [IronClad](http://code.google.com/p/ironclad/)) but this is in its early stages, and I think they will concentrate on getting things like Numpy working first, GUI toolkits will always be the last, and hardest.
python list in sql query as parameter
283,645
45
2008-11-12T11:18:32Z
283,713
12
2008-11-12T11:52:22Z
[ "python", "sql" ]
I have a python list, say l ``` l = [1,5,8] ``` I want to write a sql query to get the data for all the elements of the list, say "select name from studens where id = |IN THE LIST l|" How do i accomlish this?
The SQL you want is ``` select name from studens where id in (1, 5, 8) ``` If you want to construct this from the python you could use ``` l = [1, 5, 8] sql_query = 'select name from studens where id in (' + ','.join(map(str, l)) + ')' ``` The [map](http://docs.python.org/library/functions.html#map) function will transform the list into a list of strings that can be glued together by commas using the [str.join](http://docs.python.org/library/stdtypes.html#str.join) method. Alternatively: ``` l = [1, 5, 8] sql_query = 'select name from studens where id in (' + ','.join((str(n) for n in l)) + ')' ``` if you prefer [generator expressions](http://docs.python.org/glossary.html#term-generator-expression) to the map function. UPDATE: [S. Lott](http://stackoverflow.com/users/10661/slott) mentions in the comments that the Python SQLite bindings don't support sequences. In that case, you might want ``` select name from studens where id = 1 or id = 5 or id = 8 ``` Generated by ``` sql_query = 'select name from studens where ' + ' or '.join(('id = ' + str(n) for n in l)) ```
python list in sql query as parameter
283,645
45
2008-11-12T11:18:32Z
283,801
51
2008-11-12T12:30:10Z
[ "python", "sql" ]
I have a python list, say l ``` l = [1,5,8] ``` I want to write a sql query to get the data for all the elements of the list, say "select name from studens where id = |IN THE LIST l|" How do i accomlish this?
Answers so far have been templating the values into a plain SQL string. That's absolutely fine for integers, but if we wanted to do it for strings we get the escaping issue. Here's a variant using a parameterised query that would work for both: ``` placeholder= '?' # For SQLite. See DBAPI paramstyle. placeholders= ', '.join(placeholder for unused in l) query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders cursor.execute(query, l) ```
Size of an open file object
283,707
33
2008-11-12T11:49:46Z
283,719
54
2008-11-12T11:55:30Z
[ "python" ]
Is there a way to find the size of a file object that is currently open? Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.
``` $ ls -la chardet-1.0.1.tgz -rwxr-xr-x 1 vinko vinko 179218 2008-10-20 17:49 chardet-1.0.1.tgz $ python Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('chardet-1.0.1.tgz','rb') >>> f.seek(0,2) >>> f.tell() 179218L ``` Adding ChrisJY's idea to the example ``` >>> import os >>> os.fstat(f.fileno()).st_size 179218L >>> ```
Size of an open file object
283,707
33
2008-11-12T11:49:46Z
283,725
7
2008-11-12T11:59:36Z
[ "python" ]
Is there a way to find the size of a file object that is currently open? Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.
Well, if the file object support the tell method, you can do: ``` current_size = f.tell() ``` That will tell you were it is currently writing. If you write in a sequential way this will be the size of the file. Otherwise, you can use the file system capabilities, i.e. `os.fstat` as suggested by others.
Pickled file won't load on Mac/Linux
283,766
4
2008-11-12T12:15:52Z
283,802
9
2008-11-12T12:30:35Z
[ "python", "linux", "osx", "cross-platform" ]
I have an application that imports data from a pickled file. It works just fine in Windows but Mac and Linux behaviour is odd. In OS X, the pickled file (file extension ".char") is unavailable as a selection unless I set the file type to \*.\*. Then, if I select a file that has the .char extension, it won't load, giving the error > ``` > unpickle_file = cPickle.load(char_file) > ``` > > ValueError: could not convert string to float However, if I create a file that doesn't have the .char extension, that file will load up just fine. In Linux, when I use the "file open" dialog, my pickled files aren't visible, whether or not they have a file extension. However, I can see them under Nautilus or Dolphin. They simply don't exist to my application though. --- **Edit** Here's the save code: ``` def createSaveFile(self): """Create the data files to be saved and save them. Creates a tuple comprised of a dictionary of general character information and the character's skills dictionary.""" if self.file_name: self.save_data = ({'Name':self.charAttribs.name, <snip> self.charAttribs.char_skills_dict) self.file = open(self.file_name, 'w') cPickle.dump(self.save_data, self.file) self.file.close() ``` Here's the open code: ``` def getCharFile(self, event): # wxGlade: CharSheet.<event_handler> """Retrieve pickled character file from disk.""" wildcard = "Character files (*.char) | *.char | All files (*.*) | *.*" openDialog = wx.FileDialog(None, "Choose a character file", os.getcwd(), "", wildcard, wx.OPEN | wx.CHANGE_DIR) if openDialog.ShowModal() == wx.ID_OK: self.path = openDialog.GetPath() try: char_file = open(self.path, "r") unpickle_file = cPickle.load(char_file) char_data, char_skills = unpickle_file self.displayCharacter(char_data, char_skills) except IOError: self.importError = wx.MessageDialog(self, "The character file is not available!", "Character Import Error", wx.OK | wx.ICON_ERROR) self.importError.ShowModal() self.importError.Destroy() openDialog.Destroy() ```
Probably you didn't open the file in binary mode when writing and/or reading the pickled data. In this case newline format conversion will occur, which can break the binary data. To open a file in binary mode you have to provide "b" as part of the mode string: ``` char_file = open('pickle.char', 'rb') ```
Outputting data from unit test in python
284,043
76
2008-11-12T14:10:27Z
284,110
21
2008-11-12T14:33:31Z
[ "python", "unit-testing" ]
If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string. For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata: ``` class TestBar(unittest.TestCase): def runTest(self): for t1, t2 in testdata: f = Foo(t1) self.assertEqual(f.bar(t2), 2) ``` If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.
You can use simple print statements, or any other way of writing to stdout. You can also invoke the Python debugger anywhere in your tests. If you use [nose](https://web.archive.org/web/20081120065052/http://www.somethingaboutorange.com/mrl/projects/nose) to run your tests (which I recommend), it will collect the stdout for each test and only show it to you if the test failed, so you don't have to live with the cluttered output when the tests pass. nose also has switches to automatically show variables mentioned in asserts, or to invoke the debugger on failed tests.
Outputting data from unit test in python
284,043
76
2008-11-12T14:10:27Z
284,192
14
2008-11-12T14:56:25Z
[ "python", "unit-testing" ]
If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string. For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata: ``` class TestBar(unittest.TestCase): def runTest(self): for t1, t2 in testdata: f = Foo(t1) self.assertEqual(f.bar(t2), 2) ``` If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.
I don't think this is quite what your looking for, there's no way to display variable values that don't fail, but this may help you get closer to outputting the results the way you want. You can use the **[TestResult object](http://docs.python.org/library/unittest.html#id3)** returned by the **TestRunner.run()** for results analysis and processing. Particularly, TestResult.errors and TestResult.failures About the TestResults Object: <http://docs.python.org/library/unittest.html#id3> And some code to point you in the right direction: ``` >>> import random >>> import unittest >>> >>> class TestSequenceFunctions(unittest.TestCase): ... def setUp(self): ... self.seq = range(5) ... def testshuffle(self): ... # make sure the shuffled sequence does not lose any elements ... random.shuffle(self.seq) ... self.seq.sort() ... self.assertEqual(self.seq, range(10)) ... def testchoice(self): ... element = random.choice(self.seq) ... error_test = 1/0 ... self.assert_(element in self.seq) ... def testsample(self): ... self.assertRaises(ValueError, random.sample, self.seq, 20) ... for element in random.sample(self.seq, 5): ... self.assert_(element in self.seq) ... >>> suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions) >>> testResult = unittest.TextTestRunner(verbosity=2).run(suite) testchoice (__main__.TestSequenceFunctions) ... ERROR testsample (__main__.TestSequenceFunctions) ... ok testshuffle (__main__.TestSequenceFunctions) ... FAIL ====================================================================== ERROR: testchoice (__main__.TestSequenceFunctions) ---------------------------------------------------------------------- Traceback (most recent call last): File "<stdin>", line 11, in testchoice ZeroDivisionError: integer division or modulo by zero ====================================================================== FAIL: testshuffle (__main__.TestSequenceFunctions) ---------------------------------------------------------------------- Traceback (most recent call last): File "<stdin>", line 8, in testshuffle AssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ---------------------------------------------------------------------- Ran 3 tests in 0.031s FAILED (failures=1, errors=1) >>> >>> testResult.errors [(<__main__.TestSequenceFunctions testMethod=testchoice>, 'Traceback (most recent call last):\n File "<stdin>" , line 11, in testchoice\nZeroDivisionError: integer division or modulo by zero\n')] >>> >>> testResult.failures [(<__main__.TestSequenceFunctions testMethod=testshuffle>, 'Traceback (most recent call last):\n File "<stdin> ", line 8, in testshuffle\nAssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n')] >>> ```
Outputting data from unit test in python
284,043
76
2008-11-12T14:10:27Z
284,326
51
2008-11-12T15:38:03Z
[ "python", "unit-testing" ]
If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string. For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata: ``` class TestBar(unittest.TestCase): def runTest(self): for t1, t2 in testdata: f = Foo(t1) self.assertEqual(f.bar(t2), 2) ``` If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.
We use the logging module for this. For example: ``` import logging class SomeTest( unittest.TestCase ): def testSomething( self ): log= logging.getLogger( "SomeTest.testSomething" ) log.debug( "this= %r", self.this ) log.debug( "that= %r", self.that ) # etc. self.assertEquals( 3.14, pi ) if __name__ == "__main__": logging.basicConfig( stream=sys.stderr ) logging.getLogger( "SomeTest.testSomething" ).setLevel( logging.DEBUG ) unittest.main() ``` That allows us to turn on debugging for specific tests which we know are failing and for which we want additional debugging information. My preferred method, however, isn't to spent a lot of time on debugging, but spend it writing more fine-grained tests to expose the problem.
Outputting data from unit test in python
284,043
76
2008-11-12T14:10:27Z
13,688,397
41
2012-12-03T17:17:16Z
[ "python", "unit-testing" ]
If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string. For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata: ``` class TestBar(unittest.TestCase): def runTest(self): for t1, t2 in testdata: f = Foo(t1) self.assertEqual(f.bar(t2), 2) ``` If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.
Very late answer for someone that, like me, comes here looking for a simple and quick answer. In Python 2.7 you could use an additional parameter `msg` to add information to the error message like this: ``` self.assertEqual(f.bar(t2), 2, msg='{0}, {1}'.format(t1, t2)) ``` Offical docs [here](http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertEqual)
Cross platform hidden file detection
284,115
13
2008-11-12T14:35:29Z
6,365,265
14
2011-06-15T22:37:28Z
[ "python", "cross-platform", "filesystems" ]
What is the best way to do cross-platform handling of hidden files? (preferably in Python, but other solutions still appreciated) Simply checking for a leading '.' works for \*nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?
Here's a script that runs on Python 2.5+ and should do what you're looking for: ``` import ctypes import os def is_hidden(filepath): name = os.path.basename(os.path.abspath(filepath)) return name.startswith('.') or has_hidden_attribute(filepath) def has_hidden_attribute(filepath): try: attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(filepath)) assert attrs != -1 result = bool(attrs & 2) except (AttributeError, AssertionError): result = False return result ``` I added something similar to has\_hidden\_attribute to [jaraco.windows](https://bitbucket.org/jaraco/jaraco.windows). If you have jaraco.windows >= 2.3: ``` from jaraco.windows import filesystem def has_hidden_attribute(filepath): return filesystem.GetFileAttributes(filepath).hidden ``` As Ben has pointed out, on Python 3.5, you can use the stdlib: ``` import os, stat def has_hidden_attribute(filepath): return bool(os.stat(filepath).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN) ``` Though you may still want to use jaraco.windows for the more Pythonic API.
Cross platform hidden file detection
284,115
13
2008-11-12T14:35:29Z
15,236,292
7
2013-03-05T23:42:04Z
[ "python", "cross-platform", "filesystems" ]
What is the best way to do cross-platform handling of hidden files? (preferably in Python, but other solutions still appreciated) Simply checking for a leading '.' works for \*nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?
Jason R. Coombs's answer is sufficient for Windows. And most POSIX GUI file managers/open dialogs/etc. probably follow the same "dot-prefix-means-hidden" convention as `ls`. But not Mac OS X. There are at least four ways a file or directory can be hidden in Finder, file open panels, etc.: * Dot prefix. * HFS+ invisible attribute. * Finder Info hidden flag. * Matches a special blacklist built into CoreFoundation (which is different on each OS version—e.g., `~/Library` is hidden in 10.7+, but not in 10.6). Trying to write your own code to handle all of that is not going to be easy. And you'll have to keep it up-to-date, as I'm willing to bet the blacklist will change with most OS versions, Finder Info will eventually go from deprecated to completely unsupported, extended attributes may be supported more broadly than HFS+, … But if you can require `pyobjc` (which is already included with recent Apple-supplied Python, and can be installed via `pip` otherwise), you can just call Apple's code: ``` import Foundation def is_hidden(path): url = Foundation.NSURL.fileURLWithPath_(path) return url.getResourceValue_forKey_error_(None, Foundation.NSURLIsHiddenKey, None)[0] def listdir_skipping_hidden(path): url = Foundation.NSURL.fileURLWithPath_(path) fm = Foundation.NSFileManager.defaultManager() urls = fm.contentsOfDirectoryAtURL_includingPropertiesForKeys_options_error_( url, [], Foundation.NSDirectoryEnumerationSkipsHiddenFiles, None)[0] return [u.path() for u in urls] ``` This should work on any Python that pyobjc supports, on OS X 10.6+. If you want 10.5 or earlier, directory enumeration flags didn't exist yet, so the only option is something like filtering something like `contentsOfDirectoryAtPath_error_` (or just `os.listdir`) on `is_hidden`. If you have to get by without `pyobjc`, you can drop down to the `CoreFoundation` equivalents, and use `ctypes`. The key functions are `CFURLCopyResourcePropertyForKey` for `is_hidden` and `CFURLEnumeratorCreateForDirectoryURL` for listing a directory. See <http://pastebin.com/aCUwTumB> for an implementation. I've tested with: * OS X 10.6, 32-bit python.org 3.3.0 * OS X 10.8, 32-bit Apple 2.7.2 * OS X 10.8, 64-bit Apple 2.7.2 * OS X 10.8, 64-bit python.org 3.3.0 It works as appropriate on each (e.g., it skips `~/Library` on 10.8, but shows it on 10.6). It *should* work on any OS X 10.6+ and any Python 2.6+. If you need OS X 10.5, you need to use the old APIs (or `os.listdir`) and filter on `is_hidden`. If you need Python 2.5, change the `bytes` checks to `str` checks (which of course breaks 3.x) and the `with` to an ugly `try`/`finally` or manual releasing. If anyone plans on putting this code into a library, I would strongly suggest checking for `pyobjc` first (`import Foundation` and, if you don't get an `ImportError` you win), and only using the `ctypes` code if it's not available. --- One last note: Some people looking for this answer are trying to reinvent a wheel they don't need to. Often, when people are doing something like this, they're building a GUI and want to, e.g., show a file browsers with an option to hide or show hidden files. Many of the popular cross-platform GUI frameworks (Qt, wx, etc.) have this support built in. (Also, many of them are open source, so you can read their code to see how they do it.) That may not answer your question—e.g., they may just be passing a "filter hidden files" flag to the platform's native file-browser dialog, but you're trying to build a console-mode file-browser and can't do that. But if it does, just use it.
Notebook widget in Tkinter
284,234
10
2008-11-12T15:10:26Z
284,695
9
2008-11-12T17:32:26Z
[ "python", "wxpython", "tabs", "tkinter" ]
Having played around a little with both Tkinter and wxPython, I like Tkinter much better in terms of how clean my source code looks. However, it doesn't seem to have as many features; in particular it doesn't have tabs (as in, the tabs at the top of a Firefox window). A little Googling on the subject offers a few suggestions. There's [a cookbook entry](http://code.activestate.com/recipes/188537/) with a class allowing you to use tabs, but it's very primitive. There's also [Python megawidgets](http://pmw.sourceforge.net/) on SourceForge, although this seems very old and gave me errors during installation. Does anyone have experience making tabbed GUIs in Tkinter? What did you use? Or is it simply the case that anyone who needs more powerful windowing components has to use wxPython?
On recent Python (> 2.7) versions, you can use the [`ttk`](https://docs.python.org/2/library/ttk.html) module, which provides access to the *Tk themed widget* set, which has been introduced in `Tk 8.5`. Here's how you import `ttk` in Python 2: ``` import ttk help(ttk.Notebook) ``` In Python 3, the [`ttk`](https://docs.python.org/3.4/library/tkinter.ttk.html?highlight=ttk#module-tkinter.ttk) module comes with the standard distributions as a submodule of [`tkinter`](https://docs.python.org/3.4/library/tkinter.html). Here's a simple working example based on an example from the [`TkDocs`](http://www.tkdocs.com/tutorial/complex.html) website: ``` from tkinter import ttk import tkinter as tk from tkinter.scrolledtext import ScrolledText def demo(): root = tk.Tk() root.title("ttk.Notebook") nb = ttk.Notebook(root) # adding Frames as pages for the ttk.Notebook # first page, which would get widgets gridded into it page1 = ttk.Frame(nb) # second page page2 = ttk.Frame(nb) text = ScrolledText(page2) text.pack(expand=1, fill="both") nb.add(page1, text='One') nb.add(page2, text='Two') nb.pack(expand=1, fill="both") root.mainloop() if __name__ == "__main__": demo() ``` Another alternative is to use the `NoteBook` widget from the [`tkinter.tix`](https://docs.python.org/3/library/tkinter.tix.html) library. To use `tkinter.tix`, you must have the `Tix` widgets installed, usually alongside your installation of the `Tk` widgets. To test your installation, try the following: ``` from tkinter import tix root = tix.Tk() root.tk.eval('package require Tix') ``` For more info, check out this [webpage](https://docs.python.org/3/library/tkinter.tix.html) on the PSF website. Note that `tix` is pretty old and not well-supported, so your best choice might be to go for `ttk.Notebook`.
How do you programmatically set an attribute in Python?
285,061
105
2008-11-12T19:33:07Z
285,076
156
2008-11-12T19:38:30Z
[ "python", "attributes", "object" ]
Suppose I have a python object `x` and a string `s`, how do I set the attribute `s` on `x`? So: ``` >>> x = SomeObject() >>> attr = 'myAttr' >>> # magic goes here >>> x.myAttr 'magic' ``` What's the magic? The goal of this, incidentally, is to cache calls to `x.__getattr__()`.
``` setattr(x, attr, 'magic') ``` For help on it: ``` >>> help(setattr) Help on built-in function setattr in module __builtin__: setattr(...) setattr(object, name, value) Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ``x.y = v''. ``` Edit: However, you should note (as pointed out in comment) that you can't do that to a "pure" instance of object. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.
How do you programmatically set an attribute in Python?
285,061
105
2008-11-12T19:33:07Z
285,086
27
2008-11-12T19:41:19Z
[ "python", "attributes", "object" ]
Suppose I have a python object `x` and a string `s`, how do I set the attribute `s` on `x`? So: ``` >>> x = SomeObject() >>> attr = 'myAttr' >>> # magic goes here >>> x.myAttr 'magic' ``` What's the magic? The goal of this, incidentally, is to cache calls to `x.__getattr__()`.
Usually, we define classes for this. ``` class XClass( object ): def __init__( self ): self.myAttr= None x= XClass() x.myAttr= 'magic' x.myAttr ``` However, you can, to an extent, do this with the `setattr` and `getattr` built-in functions. However, they don't work on instances of `object` directly. ``` >>> a= object() >>> setattr( a, 'hi', 'mom' ) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'object' object has no attribute 'hi' ``` They do, however, work on all kinds of simple classes. ``` class YClass( object ): pass y= YClass() setattr( y, 'myAttr', 'magic' ) y.myAttr ```
What Python tools can I use to interface with a website's API?
285,226
6
2008-11-12T20:28:55Z
285,437
8
2008-11-12T21:27:20Z
[ "python", "web-services", "twitter" ]
Let's say I wanted to make a python script interface with a site like Twitter. What would I use to do that? I'm used to using curl/wget from bash, but Python seems to be much nicer to use. What's the equivalent? (This isn't Python run from a webserver, but run locally via the command line)
For something like Twitter, you'll save yourself a ton of time by not reinventing the wheel. Try a library like [python-twitter](http://code.google.com/p/python-twitter/). This way, you can write your script, or even a full fledged application, that interfaces with Twitter, and you don't have to care about the implementation details. If you want to roll your own interface library, you're going to have to get familiar with [urllib](https://docs.python.org/library/urllib.html) and depending on what format they provide results, either [lxml](http://lxml.de/) (or some other xml parser) or [simplejson](http://undefined.org/python/#simplejson).
Exit codes in Python
285,289
76
2008-11-12T20:43:08Z
285,304
9
2008-11-12T20:46:28Z
[ "python", "exit-code" ]
I got a message saying `script xyz.py returned exit code 0`. What does this mean? What do the exit codes in Python mean? How many are there? Which ones are important?
Exit codes of 0 usually mean, "nothing wrong here." However if the programmer of the script didn't follow convention you may have to consult the source to see what it means. Usually a non-zero value is returned as an error code.
Exit codes in Python
285,289
76
2008-11-12T20:43:08Z
285,326
91
2008-11-12T20:50:48Z
[ "python", "exit-code" ]
I got a message saying `script xyz.py returned exit code 0`. What does this mean? What do the exit codes in Python mean? How many are there? Which ones are important?
What you're looking for in the script is calls to [`sys.exit()`](https://docs.python.org/2/library/sys.html#sys.exit). The argument to that method is returned to the environment as the exit code. It's fairly likely that the script is never calling the exit method, and that 0 is the default exit code.
Exit codes in Python
285,289
76
2008-11-12T20:43:08Z
285,451
43
2008-11-12T21:31:23Z
[ "python", "exit-code" ]
I got a message saying `script xyz.py returned exit code 0`. What does this mean? What do the exit codes in Python mean? How many are there? Which ones are important?
From [the documentation for `sys.exit`](https://docs.python.org/2/library/sys.html#sys.exit): > The optional argument arg can be an > integer giving the exit status > (defaulting to zero), or another type > of object. If it is an integer, zero > is considered “successful termination” > and any nonzero value is considered > “abnormal termination” by shells and > the like. Most systems require it to > be in the range 0-127, and produce > undefined results otherwise. Some > systems have a convention for > assigning specific meanings to > specific exit codes, but these are > generally underdeveloped; Unix > programs generally use 2 for command > line syntax errors and 1 for all other > kind of errors. One example where exit codes are used are in shell scripts. In bash you can check the special variable `$?` for the last exit status: ``` me@mini:~$ python -c ""; echo $? 0 me@mini:~$ python -c "import sys; sys.exit(0)"; echo $? 0 me@mini:~$ python -c "import sys; sys.exit(43)"; echo $? 43 ``` Personally I try to use the exit codes I find in `/usr/include/asm-generic/errno.h` (on a Linux system), but I don't know if this is the right thing to do.
Exit codes in Python
285,289
76
2008-11-12T20:43:08Z
286,444
16
2008-11-13T07:32:08Z
[ "python", "exit-code" ]
I got a message saying `script xyz.py returned exit code 0`. What does this mean? What do the exit codes in Python mean? How many are there? Which ones are important?
There is an [`errno`](http://docs.python.org/library/errno.html) module that defines standard exit codes: For example, **Permission denied** is error code **13**: ``` import errno, sys if can_access_resource(): do_something() else: sys.exit(errno.EACCES) ```
Exit codes in Python
285,289
76
2008-11-12T20:43:08Z
30,776,037
8
2015-06-11T08:53:44Z
[ "python", "exit-code" ]
I got a message saying `script xyz.py returned exit code 0`. What does this mean? What do the exit codes in Python mean? How many are there? Which ones are important?
For the record, you can use POSIX standard exit codes defined [here](https://docs.python.org/2/library/os.html#process-management). Example: ``` import sys, os try: config() except: sys.exit(os.EX_CONFIG) try: do_stuff() except: sys.exit(os.EX_SOFTWARE) sys.exit(os.EX_OK) # code 0, all ok ```
Python module to extract probable dates from strings?
285,408
13
2008-11-12T21:11:25Z
285,677
12
2008-11-12T22:46:58Z
[ "python" ]
I'm looking for a Python module that would take an arbitrary block of text, search it for something that looks like a date string, and build a DateTime object out of it. Something like [Date::Extract](http://search.cpan.org/~sartak/Date-Extract-0.03/lib/Date/Extract.pm) in Perl Thank you in advance.
The nearest equivalent is probably the [dateutil](http://labix.org/python-dateutil) module. Usage is: ``` >>> from dateutil.parser import parse >>> parse("Wed, Nov 12") datetime.datetime(2008, 11, 12, 0, 0) ``` Using the fuzzy parameter should ignore extraneous text. ie ``` >>> parse("the date was the 1st of December 2006 2:30pm", fuzzy=True) datetime.datetime(2006, 12, 1, 14, 30) ```
How to access a Python global variable from C?
285,455
5
2008-11-12T21:32:08Z
285,498
9
2008-11-12T21:46:13Z
[ "python", "c" ]
I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how? I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.
I'm not a python guru, but I found this question interesting so I googled around. [This](http://mail.python.org/pipermail/python-list/2007-September/508180.html) was the first hit on "python embedding API" - does it help? > If the attributes belong to the global > scope of a module, then you can use > "PyImport\_AddModule" to get a handle > to the module object. For example, if > you wanted to get the value of an > integer in the **main** module named > "foobar", you would do the following: > > ``` > PyObject *m = PyImport_AddModule("__main__"); > PyObject *v = PyObject_GetAttrString(m,"foobar"); > > int foobar = PyInt_AsLong(v); > > Py_DECREF(v); > ```
Decomposing HTML to link text and target
285,938
5
2008-11-13T00:38:56Z
285,941
8
2008-11-13T00:40:29Z
[ "python", "html", "regex", "beautifulsoup" ]
Given an HTML link like ``` <a href="urltxt" class="someclass" close="true">texttxt</a> ``` how can I isolate the url and the text? **Updates** I'm using Beautiful Soup, and am unable to figure out how to do that. I did ``` soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) links = soup.findAll('a') for link in links: print "link content:", link.content," and attr:",link.attrs ``` i get ``` *link content: None and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root /support.asp')]* ... ... ``` Why am i missing the content? edit: elaborated on 'stuck' as advised :)
Use [Beautiful Soup](http://crummy.com/software/BeautifulSoup). Doing it yourself is harder than it looks, you'll be better off using a tried and tested module. **EDIT:** I think you want: ``` soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read()) ``` By the way, it's a bad idea to try opening the URL there, as if it goes wrong it could get ugly. **EDIT 2:** This should show you all the links in a page: ``` import urlparse, urllib from BeautifulSoup import BeautifulSoup url = "http://www.example.com/index.html" source = urllib.urlopen(url).read() soup = BeautifulSoup(source) for item in soup.fetchall('a'): try: link = urlparse.urlparse(item['href'].lower()) except: # Not a valid link pass else: print link ```
Parse HTML via XPath
285,990
22
2008-11-13T01:05:59Z
289,167
7
2008-11-14T03:37:03Z
[ "python", "html", "ruby", "xpath", "parsing" ]
In .Net, I found this great library, [HtmlAgilityPack](http://www.codeplex.com/htmlagilitypack) that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?
In python, [ElementTidy](http://pypi.python.org/pypi/elementtidy/1.0-20050212) parses tag soup and produces an element tree, which allows querying using XPath: ``` >>> from elementtidy.TidyHTMLTreeBuilder import TidyHTMLTreeBuilder as TB >>> tb = TB() >>> tb.feed("<p>Hello world") >>> e= tb.close() >>> e.find(".//{http://www.w3.org/1999/xhtml}p") <Element {http://www.w3.org/1999/xhtml}p at 264eb8> ```
Parse HTML via XPath
285,990
22
2008-11-13T01:05:59Z
4,747,067
29
2011-01-20T12:24:30Z
[ "python", "html", "ruby", "xpath", "parsing" ]
In .Net, I found this great library, [HtmlAgilityPack](http://www.codeplex.com/htmlagilitypack) that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?
I'm surprised there isn't a single mention of lxml. It's blazingly fast and will work in any environment that allows CPython libraries. Here's how [you can parse HTML via XPATH using lxml](http://codespeak.net/lxml/xpathxslt.html). ``` >>> from lxml import etree >>> doc = '<foo><bar></bar></foo>' >>> tree = etree.HTML(doc) >>> r = tree.xpath('/foo/bar') >>> len(r) 1 >>> r[0].tag 'bar' >>> r = tree.xpath('bar') >>> r[0].tag 'bar' ```
Decimal place issues with floats and decimal.Decimal
286,061
2
2008-11-13T02:06:30Z
286,064
11
2008-11-13T02:09:08Z
[ "python", "floating-point", "decimal", "floating-accuracy" ]
I seem to be losing a lot of precision with floats. For example I need to solve a matrix: ``` 4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 ``` This is the code I use to import the matrix from a text file: ``` f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) ``` I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z: ``` x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 ``` Here is the code I use to rearrange the equations. `b` is a matrix of coefficients and `y` is the answer vector: ``` def equations(b,y): i=0 eqn=[] row=[] while(i<len(b)): j=0 row=[] while(j<len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn ``` However the answers I get back aren't precise to the decimal place. For example, upon rearranging the second equation from above, I should get: ``` y=-1.2-.2x+.6z ``` What I get is: ``` y=-1.2-0.20000000000000001x+0.59999999999999998z ``` This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the `Decimal` class but it does not work well with powers (i.e, `Decimal(x)**2`). Any ideas?
I'm not familiar enough with the Decimal class to help you out, but your problem is due to the fact that decimal fractions can often not be accurate represented in binary, so what you're seeing is the closest possible approximation; there's no way to avoid this problem without using a special class (like Decimal, probably). `EDIT:` What about the decimal class isn't working properly for you? As long as I start with a string, rather than a float, powers seem to work fine. ``` >>> import decimal >>> print(decimal.Decimal("1.2") ** 2) 1.44 ``` The [module documentation](http://docs.python.org/library/decimal.html) explains the need for and usage of `decimal.Decimal` pretty clearly, you should check it out if you haven't yet.
Decimal place issues with floats and decimal.Decimal
286,061
2
2008-11-13T02:06:30Z
286,068
14
2008-11-13T02:11:58Z
[ "python", "floating-point", "decimal", "floating-accuracy" ]
I seem to be losing a lot of precision with floats. For example I need to solve a matrix: ``` 4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 ``` This is the code I use to import the matrix from a text file: ``` f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) ``` I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z: ``` x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 ``` Here is the code I use to rearrange the equations. `b` is a matrix of coefficients and `y` is the answer vector: ``` def equations(b,y): i=0 eqn=[] row=[] while(i<len(b)): j=0 row=[] while(j<len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn ``` However the answers I get back aren't precise to the decimal place. For example, upon rearranging the second equation from above, I should get: ``` y=-1.2-.2x+.6z ``` What I get is: ``` y=-1.2-0.20000000000000001x+0.59999999999999998z ``` This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the `Decimal` class but it does not work well with powers (i.e, `Decimal(x)**2`). Any ideas?
IEEE floating point is binary, not decimal. There is no fixed length binary fraction that is exactly 0.1, or any multiple thereof. It is a repeating fraction, like 1/3 in decimal. Please read [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html) Other options besides a Decimal class are * using Common Lisp or [Python 2.6](http://docs.python.org/whatsnew/2.6.html#the-fractions-module) or another language with exact rationals * converting the doubles to close rationals using, e.g., [frap](http://www.ics.uci.edu/~eppstein/numth/frap.c)
What's the best way to transfer data from python to another application in windows?
286,614
8
2008-11-13T09:25:21Z
286,738
9
2008-11-13T10:20:33Z
[ "python", "winapi", "com", "data-transfer" ]
I'm developing an application with a team in .Net (C++) and provide a COM interface to interact with python and other languages. What we've found is that pushing data through COM turns out to be pretty slow. I've considered several alternatives: * dumping data to a file and sending the file path through com * Shared Memory via [mmap](http://docs.python.org/library/mmap.html?highlight=shared%20memory#module-mmap)? * Stream data through a socket directly? From your experience what's the best way to pass around data?
Staying within the Windows interprocess communication mechanisms, we had positive experience using *windows named pipes*. Using Windows overlapped IO and the `win32pipe` module from [pywin32](http://pywin32.sourceforge.net/). You can learn much about win32 and python in the [Python Programming On Win32](http://oreilly.com/catalog/9781565926219/index.html) book. The sending part simply writes to `r'\\.\pipe\mypipe'`. A listener (`ovpipe`) object holds an event handle, and waiting for a message with possible other events involves calling `win32event.WaitForMultipleObjects`. ``` rc = win32event.WaitForMultipleObjects( eventlist, # Objects to wait for. 0, # Wait for one object timeout) # timeout in milli-seconds. ``` Here is part of the python overlapped listener class: ``` import win32event import pywintypes import win32file import win32pipe class ovpipe: "Overlapped I/O named pipe class" def __init__(self): self.over=pywintypes.OVERLAPPED() evt=win32event.CreateEvent(None,1,0,None) self.over.hEvent=evt self.pname='mypipe' self.hpipe = win32pipe.CreateNamedPipe( r'\\.\pipe\mypipe', # pipe name win32pipe.PIPE_ACCESS_DUPLEX| # read/write access win32file.FILE_FLAG_OVERLAPPED, win32pipe.PIPE_TYPE_MESSAGE| # message-type pipe win32pipe.PIPE_WAIT, # blocking mode 1, # number of instances 512, # output buffer size 512, # input buffer size 2000, # client time-out None) # no security attributes self.buffer = win32file.AllocateReadBuffer(512) self.state='noconnected' self.chstate() def execmsg(self): "Translate the received message" pass def chstate(self): "Change the state of the pipe depending on current state" if self.state=='noconnected': win32pipe.ConnectNamedPipe(self.hpipe,self.over) self.state='connectwait' return -6 elif self.state=='connectwait': j,self.strbuf=win32file.ReadFile(self.hpipe,self.buffer,self.over) self.state='readwait' return -6 elif self.state=='readwait': size=win32file.GetOverlappedResult(self.hpipe,self.over,1) self.msg=self.strbuf[:size] ret=self.execmsg() self.state = 'noconnected' win32pipe.DisconnectNamedPipe(self.hpipe) return ret ```
Any AOP support library for Python?
286,958
23
2008-11-13T13:51:27Z
287,640
22
2008-11-13T17:39:10Z
[ "python", "aop" ]
I am trying to use some AOP in my Python programming, but I do not have any experience of the various libs that exists. So my question is : What AOP support exists for Python, and what are the advantages of the differents libraries between them ? Edit : I've found some, but I don't know how they compare : * [Aspyct](http://www.aspyct.org) * [Lightweight AOP for Python](http://www.cs.tut.fi/~ask/aspects/aspects.html) Edit2 : In which context will I use this ? I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionnality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack.
See S.Lott's link about Python decorators for some great examples, and see the [defining PEP for decorators](http://www.python.org/dev/peps/pep-0318/). Python had AOP since the beginning, it just didn't have an impressive name. In Python 2.4 the decorator syntax was added, which makes applying decorators very nice syntactically. Maybe if you want to apply decorators based on rules you would need a library, but if you're willing to mark the relevant functions/methods when you declare them you probably don't. Here's an example for a simple caching decorator (I wrote it for [this question](http://stackoverflow.com/questions/287085/what-does-args-and-kwargs-mean#287616)): ``` import pickle, functools def cache(f): _cache = {} def wrapper(*args, **kwargs): key = pickle.dumps((args, kwargs)) if key not in _cache: _cache[key] = f(*args, **kwargs) # call the wrapped function, save in cache return _cache[key] # read value from cache functools.update_wrapper(wrapper, f) # update wrapper's metadata return wrapper import time @cache def foo(n): time.sleep(2) return n*2 foo(10) # first call with parameter 10, sleeps foo(10) # returns immediately ```
Any AOP support library for Python?
286,958
23
2008-11-13T13:51:27Z
5,220,447
7
2011-03-07T13:48:30Z
[ "python", "aop" ]
I am trying to use some AOP in my Python programming, but I do not have any experience of the various libs that exists. So my question is : What AOP support exists for Python, and what are the advantages of the differents libraries between them ? Edit : I've found some, but I don't know how they compare : * [Aspyct](http://www.aspyct.org) * [Lightweight AOP for Python](http://www.cs.tut.fi/~ask/aspects/aspects.html) Edit2 : In which context will I use this ? I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionnality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack.
Another AOP library for python would be pytilities. It is currently the most powerful (, for as far as I know). pytilities homepage: <http://pytilities.sourceforge.net/> Its features are: * make reusable Aspect classes * apply multiple aspects to an instance or class * unapply aspects to an instance/class * add new attributes to an instance by using an aspect * apply advice to all attributes of an instance/class * ... It also has other goodies such as some special descriptors (see the documentation)
Python program start
287,204
11
2008-11-13T15:16:35Z
287,215
19
2008-11-13T15:20:28Z
[ "python" ]
Should I start a Python program with: ``` if__name__ == '__main__': some code... ``` And if so, why? I saw it many times but don't have a clue about it.
If your program is usable as a library but you also have a main program (e.g. to test the library), that construct lets others import the file as a library and not run your main program. If your program is named foo.py and you do "import foo" from another python file, `__name__` evaluates to `'foo'`, but if you run "python foo.py" from the command line, `__name__` evaluates to `'__main__'`. Note that you do need to insert a space between if and \_, and indent the main program: ``` if __name__ == '__main__': main program here ```
Python program start
287,204
11
2008-11-13T15:16:35Z
287,237
17
2008-11-13T15:26:28Z
[ "python" ]
Should I start a Python program with: ``` if__name__ == '__main__': some code... ``` And if so, why? I saw it many times but don't have a clue about it.
A better pattern is this: ``` def main(): ... if __name__ == '__main__': main() ``` This allows your code to be invoked by someone who imported it, while also making programs such as [pychecker](http://pychecker.sourceforge.net/) and [pylint](http://www.logilab.org/projects/pylint) work.
Python program start
287,204
11
2008-11-13T15:16:35Z
287,548
14
2008-11-13T17:09:51Z
[ "python" ]
Should I start a Python program with: ``` if__name__ == '__main__': some code... ``` And if so, why? I saw it many times but don't have a clue about it.
Guido Van Rossum [suggests](http://www.artima.com/weblogs/viewpost.jsp?thread=4829): ``` def main(argv=None): if argv is None: argv = sys.argv ... if __name__ == "__main__": sys.exit(main()) ``` This way you can run `main()` from somewhere else (supplying the arguments), and if you want to exit with an error code just `return 1` from `main()`, and it won't make an interactive interpreter exit by mistake.
Parsing C++ preprocessor #if statements
287,379
4
2008-11-13T16:18:37Z
287,395
7
2008-11-13T16:23:07Z
[ "python", "c++", "c", "parsing", "c-preprocessor" ]
I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler. I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &&, ||, !, brackets, relational operators, arithmetic, etc). Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python). The only implementation I know of is GCC, and that's much too complex for this task.
Instead of reinventing the wheel, download "unifdef". If you're on some flavour of Linux, you can probably find a package for it, otherwise it's on [FreshMeat](http://freshmeat.net/projects/unifdef/)
Parsing C++ preprocessor #if statements
287,379
4
2008-11-13T16:18:37Z
287,405
12
2008-11-13T16:25:25Z
[ "python", "c++", "c", "parsing", "c-preprocessor" ]
I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler. I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &&, ||, !, brackets, relational operators, arithmetic, etc). Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python). The only implementation I know of is GCC, and that's much too complex for this task.
How about just passing through the C preprocessor, and letting that do the job. It will get rid of all of them, so you might need to have a pre-preprocessor step and a post pre-processor step to protect things you don't want to be expanded. 1. Change all #include to @include 2. Pass file through preprocessor 3. Change @include back to #include
Parsing C++ preprocessor #if statements
287,379
4
2008-11-13T16:18:37Z
287,521
14
2008-11-13T17:02:13Z
[ "python", "c++", "c", "parsing", "c-preprocessor" ]
I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler. I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &&, ||, !, brackets, relational operators, arithmetic, etc). Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python). The only implementation I know of is GCC, and that's much too complex for this task.
As [KeithB said](http://stackoverflow.com/questions/287379/parsing-c-preprocessor-if-statements#287405), you could just let the preprocessor do this for you. But if you're not trying to hide things (ie., there may be stuff in the conditionally compiled code that you don't want or aren't permitted to give to some one else) a much simpler option would be to just put the proper `#define` directives in a header that's globally included. * your clients don't need to worry about `-D` options * you don't have to have some custom step in your build process * the code you give your clients isn't potentially semi-obfuscated * you don't introduce bugs because the tool does things subtly different from the C preprocessor * you don't have to maintain some custom tool
Python's ConfigParser unique keys per section
287,757
8
2008-11-13T18:20:11Z
287,942
11
2008-11-13T19:24:23Z
[ "python", "design", "configuration-files" ]
I read the part of [the docs](http://docs.python.org/library/configparser.html) and saw that the `ConfigParser` returns a list of key/value pairs for the options within a section. I figured that keys did not need to be unique within a section, otherwise the parser would just return a mapping. I designed my config file schema around this assumption, then sadly realized that this is not the case: ``` >>> from ConfigParser import ConfigParser >>> from StringIO import StringIO >>> fh = StringIO(""" ... [Some Section] ... spam: eggs ... spam: ham ... """) >>> parser = ConfigParser() >>> parser.readfp(fh) >>> print parser.items('Some Section') [('spam', 'ham')] ``` Then I went back and found the part of the docs that I *should* have read: > Sections are normally stored in a > builtin dictionary. An alternative > dictionary type can be passed to the > ConfigParser constructor. For example, > if a dictionary type is passed that > sorts its keys, the sections will be > sorted on write-back, as will be the > keys within each section. To keep my existing configuration file scheme (which I really like now ;) I'm thinking of passing a mapping-like object as mentioned above that accumulates values instead of clobbering them. Is there a simpler way to prevent key/value collapse that I'm missing? Instead of making a crazy adapter (that could break if `ConfigParser`'s implementation changes) should I just write a variant of the `ConfigParser` itself? I feel like this may be one of those 'duh' moments where I'm only seeing the difficult solutions. **[Edit:]** Here's a more precise example of how I'd like to use the same key multiple times: ``` [Ignored Paths] ignore-extension: .swp ignore-filename: tags ignore-directory: bin ``` I dislike the comma-delimited-list syntax because it's hard on the eyes when you scale it to many values; for example, a comma delimited list of fifty extensions would not be particularly readable.
ConfigParser isn't designed to handle such conditions. Furthermore, your config file doesn't make sense to me. ConfigParser gives you a dict-like structure for each section, so when you call parser.items(section), I'm expecting similar output to dict.items(), which is just a list of key/value tuples. I would never expect to see something like: ``` [('spam', 'eggs'), ('spam', 'ham')] ``` Not to mention, how would you expect the following to behave?: ``` parser.get('Some Section', 'spam') ``` Which is the intended way to retrieve values. If you want to store multiple values for the same key, I would suggest something like this in your config file: ``` [Some Section] spam: eggs, ham ``` And this in your code: ``` spam_values = [v.strip() for v in parser.get('Some Section', 'spam').split(',')] ``` Of course, this will only work for values that don't contain commas themselves or handle quoting. For that, you should employ a more advanced technique (see [this](http://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat) and [this](http://stackoverflow.com/questions/118458/how-can-i-join-a-list-into-a-string-caveat)). EDIT: If you don't mind the extra dependency, You could check out [ConfigObj](http://www.voidspace.org.uk/python/configobj.html), which natively supports lists as a value type.
Dictonaries and Lambda inside a class?
287,823
3
2008-11-13T18:44:08Z
287,867
7
2008-11-13T18:56:32Z
[ "python", "lambda" ]
How can i do something like this: ``` class Foo(): do_stuff = { "A" : lambda x: self.do_A(x), "B" : lambda x: self.do_B(x) } def __init__(self): print "hi" def run(self): muh = ['A', 'B', 'A'] for each in muh: self.do_stuff[each](each) def do_A(self, moo): print "A" def do_B(self, boo): print "B" if(__name__ == '__main__'): aFoo = Foo() aFoo.run() ``` This results in it giving an error that self isn't defined at the lambda function, but if i remove it. It says do\_A or do\_B isn't defined. *EDIT* I managed to figure it out. I need to change the lambda expression into something like this: ``` lambda x, y: x.do_A(y) ``` and i would call it like: ``` self.do_stuff[each](self, each) ``` Is this a terrible idea?
do\_stuff is not an instance variable in your example. It's more like a static variable. You need to define do\_stuff within a method (e.g., the **init** method) where you have a reference to self in order to make it an instance variable. I hope this example clarifies things for you: ``` class Foo: def __init__(self): self.do_stuff = { "A": self.do_A, "B": self.do_B } def run(self): for x in ["A", "B"]: self.do_stuff[x]("hi") def do_A(self, x): pass def do_B(self, x): pass ``` Note that the lambda functions aren't necessary. You can just store references to the functions themselves in your dictionary. The notation "self.do\_A" will automatically pass self as the first argument. EDIT: Does anyone know how to make underscores show properly in non-code-sample text? EDIT: WTH? The preview is showing underscores differently than the post.
Print in terminal with colors using Python?
287,871
1,024
2008-11-13T18:58:10Z
287,896
15
2008-11-13T19:06:23Z
[ "python", "unicode", "terminal", "ansi-colors" ]
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
For Windows you cannot print to console with colors unless you're using the win32api. For Linux it's as simple as using print, with the escape sequences outlined here: [Colors](http://www.linuxhowtos.org/Tips%20and%20Tricks/ansi_escape_sequences.htm) For the character to print like a box, it really depends on what font you are using for the console window. The pound symbol works well, but it depends on the font: ``` # ```
Print in terminal with colors using Python?
287,871
1,024
2008-11-13T18:58:10Z
287,919
12
2008-11-13T19:13:59Z
[ "python", "unicode", "terminal", "ansi-colors" ]
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
You can use the Python implementation of the curses library: <http://docs.python.org/library/curses.html> Also, run this and you'll find your box: ``` for i in range(255): print i, chr(i) ```
Print in terminal with colors using Python?
287,871
1,024
2008-11-13T18:58:10Z
287,934
53
2008-11-13T19:22:54Z
[ "python", "unicode", "terminal", "ansi-colors" ]
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
You want to learn about ANSI escape sequences. Here's a brief example: ``` CSI="\x1B[" reset=CSI+"m" print CSI+"31;40m" + "Colored Text" + CSI + "0m" ``` For more info see <http://en.wikipedia.org/wiki/ANSI_escape_code> For a block character, try a unicode character like \u2588: ``` print u"\u2588" ``` Putting it all together: ``` print CSI+"31;40m" + u"\u2588" + CSI + "0m" ```
Print in terminal with colors using Python?
287,871
1,024
2008-11-13T18:58:10Z
287,944
878
2008-11-13T19:25:07Z
[ "python", "unicode", "terminal", "ansi-colors" ]
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some python code from the [blender build scripts](https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py): ``` class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' ``` To use code like this, you can do something like ``` print bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC ``` This will work on unixes including OS X, linux and windows (provided you use [ANSICON](https://github.com/adoxa/ansicon), or in Windows 10 provided you enable [VT100 emulation](https://msdn.microsoft.com/en-us/library/mt638032)). There are ansi codes for setting the color, moving the cursor, and more. If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The [Python Curses HowTO](http://docs.python.org/howto/curses.html) is a good introduction. If you are not using extended ASCII (i.e. not on a PC), you are stuck with the ascii characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM [extended ascii character set](http://telecom.tbi.net/asc-ibm.html), you have many more options. Characters 176, 177, 178 and 219 are the "block characters". Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the [Dwarf Fortress Wiki](http://dwarffortresswiki.org/DF2014:Tilesets) see ([user-made tilesets](http://dwarffortresswiki.org/Tileset_repository)). The [Text Mode Demo Contest](http://en.wikipedia.org/wiki/TMDC) has more resources for doing graphics in text mode. Hmm.. I think got a little carried away on this answer. I am in the midst of planning an epic text-based adventure game, though. Good luck with your colored text!
Print in terminal with colors using Python?
287,871
1,024
2008-11-13T18:58:10Z
287,987
10
2008-11-13T19:38:57Z
[ "python", "unicode", "terminal", "ansi-colors" ]
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
If you are programming a game perhaps you would like to change the background color and use only spaces? For example: ``` print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m" ```
Print in terminal with colors using Python?
287,871
1,024
2008-11-13T18:58:10Z
288,556
21
2008-11-13T22:22:30Z
[ "python", "unicode", "terminal", "ansi-colors" ]
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
On Windows you can use module 'win32console' (available in some Python distributions) or module 'ctypes' (Python 2.5 and up) to access the Win32 API. To see complete code that supports both ways, see the [color console reporting code](http://code.google.com/p/testoob/source/browse/trunk/src/testoob/reporting/colored.py) from [Testoob](http://www.testoob.org). ctypes example: ``` import ctypes # Constants from the Windows API STD_OUTPUT_HANDLE = -11 FOREGROUND_RED = 0x0004 # text color contains red. def get_csbi_attributes(handle): # Based on IPython's winconsole.py, written by Alexander Belchenko import struct csbi = ctypes.create_string_buffer(22) res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi) assert res (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) return wattr handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) reset = get_csbi_attributes(handle) ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED) print "Cherry on top" ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset) ```
Print in terminal with colors using Python?
287,871
1,024
2008-11-13T18:58:10Z
293,633
409
2008-11-16T07:31:39Z
[ "python", "unicode", "terminal", "ansi-colors" ]
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
I'm surprised no one has mentioned the [Python termcolor module](http://pypi.python.org/pypi/termcolor). Usage is pretty simple: ``` from termcolor import colored print colored('hello', 'red'), colored('world', 'green') ``` It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...
Print in terminal with colors using Python?
287,871
1,024
2008-11-13T18:58:10Z
1,073,959
9
2009-07-02T11:59:17Z
[ "python", "unicode", "terminal", "ansi-colors" ]
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
Here's a curses example: ``` import curses def main(stdscr): stdscr.clear() if curses.has_colors(): for i in xrange(1, curses.COLORS): curses.init_pair(i, i, curses.COLOR_BLACK) stdscr.addstr("COLOR %d! " % i, curses.color_pair(i)) stdscr.addstr("BOLD! ", curses.color_pair(i) | curses.A_BOLD) stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT) stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE) stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK) stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM) stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE) stdscr.refresh() stdscr.getch() if __name__ == '__main__': print "init..." curses.wrapper(main) ```
Print in terminal with colors using Python?
287,871
1,024
2008-11-13T18:58:10Z
3,332,860
281
2010-07-26T07:07:14Z
[ "python", "unicode", "terminal", "ansi-colors" ]
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
The answer is [Colorama](http://pypi.python.org/pypi/colorama) for all cross-platform coloring in Python.
Print in terminal with colors using Python?
287,871
1,024
2008-11-13T18:58:10Z
8,548,994
51
2011-12-18T00:32:49Z
[ "python", "unicode", "terminal", "ansi-colors" ]
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
My favorite way is with the [Blessings](http://pypi.python.org/pypi/blessings/) library (full disclosure: I wrote it). For example: ``` from blessings import Terminal t = Terminal() print t.red('This is red.') print t.bold_bright_red_on_black('Bright red on black') ``` To print colored bricks, the most reliable way is to print spaces with background colors. I use this technique to draw the progress bar in [nose-progressive](http://pypi.python.org/pypi/nose-progressive/): ``` print t.on_green(' ') ``` You can print in specific locations as well: ``` with t.location(0, 5): print t.on_yellow(' ') ``` If you have to muck with other terminal capabilities in the course of your game, you can do that as well. You can use Python's standard string formatting to keep it readable: ``` print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t) ``` The nice thing about Blessings is that it does its best to work on all sorts of terminals, not just the (overwhelmingly common) ANSI-color ones. It also keeps unreadable escape sequences out of your code while remaining concise to use. Have fun!
Print in terminal with colors using Python?
287,871
1,024
2008-11-13T18:58:10Z
8,774,709
11
2012-01-08T01:40:35Z
[ "python", "unicode", "terminal", "ansi-colors" ]
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
You could use [CLINT](http://www.nicosphere.net/clint-command-line-library-for-python/): ``` from clint.textui import colored print colored.red('some warning message') print colored.green('nicely done!') ``` [Get it from GitHub](https://github.com/kennethreitz/clint).
Print in terminal with colors using Python?
287,871
1,024
2008-11-13T18:58:10Z
11,193,790
7
2012-06-25T16:59:39Z
[ "python", "unicode", "terminal", "ansi-colors" ]
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
If you are using Windows, then here you go! ``` # display text on a Windows console # Windows XP with Python27 or Python32 from ctypes import windll # needed for Python2/Python3 diff try: input = raw_input except: pass STD_OUTPUT_HANDLE = -11 stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) # look at the output and select the color you want # for instance hex E is yellow on black # hex 1E is yellow on blue # hex 2E is yellow on green and so on for color in range(0, 75): windll.kernel32.SetConsoleTextAttribute(stdout_handle, color) print("%X --> %s" % (color, "Have a fine day!")) input("Press Enter to go on ... ") ```