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 ...
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 =...
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, do...
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 restructu...
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 restructu...
(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...
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 restructu...
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 restructu...
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 restructu...
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,fi...
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 restructu...
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 ambig...
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 restructu...
``` 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 restructu...
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 modu...
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 restructu...
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...
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 restructu...
``` 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 restructu...
## 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 ...
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 restructu...
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...
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 restructu...
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.*whate...
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 ...
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 ...
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 ...
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(f...
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 ...
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,...
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 ...
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...
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 ...
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....
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 ...
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__` me...
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 ...
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/excepti...
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 ...
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 = mode...
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_object...
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 = mode...
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 ...
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 yo...
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 Open...
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 wa...
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 wa...
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,...
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 referen...
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 r...
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 referen...
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): ...
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 referen...
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 ...
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 referen...
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 referen...
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 ...
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 referen...
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/ht...
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): ...
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...
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 c...
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. ...
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 c...
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 constan...
`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 han...
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 constan...
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:...
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, newl...
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-pl...
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(), [(...
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 librari...
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 clar...
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...
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 n...
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 a...
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...
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 t...
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= ',...
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.se...
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, givi...
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, th...
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 stdo...
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, th...
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 r...
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, th...
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.assertEqu...
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, th...
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...
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 hidi...
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 = ct...
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 hidi...
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+ invisib...
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 sugg...
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://d...
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 ...
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. ``` >...
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 implemen...
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 con...
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 Decembe...
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 re...
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\_AddMo...
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 li...
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...
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 ...
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(".//{htt...
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 ...
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.HTM...
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: bi...
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, proba...
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: bi...
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.ht...
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...
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...
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]...
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 syn...
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]...
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 ...
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 "py...
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 e...
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 stateme...
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 stateme...
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...
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 stateme...
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 e...
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 ...
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 exp...
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" ...
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__(sel...
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 f...
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 ...
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: HEA...
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.p...
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" th...
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.col...
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 ...
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) # lo...