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 |
|---|---|---|---|---|---|---|---|---|---|
Unicode block of a character in python | 243,831 | 5 | 2008-10-28T15:56:18Z | 245,072 | 10 | 2008-10-28T22:13:30Z | [
"python",
"unicode",
"character-properties"
] | Is there a way to get the Unicode Block of a character in python? The [unicodedata](http://www.python.org/doc/2.5.2/lib/module-unicodedata.html) module doesn't seem to have what I need, and I couldn't find an external library for it.
Basically, I need the same functionality as [`Character.UnicodeBlock.of()`](http://ja... | I couldn't find one either. Strange!
Luckily, the number of Unicode blocks is quite manageably small.
This implementation accepts a one-character Unicode string, just like the functions in `unicodedata`. If your inputs are mostly ASCII, this linear search might even be faster than binary search using `bisect` or what... |
How to copy all properties of an object to another object, in Python? | 243,836 | 21 | 2008-10-28T15:58:11Z | 244,116 | 20 | 2008-10-28T17:16:27Z | [
"python"
] | Is there a library method to copy all the properties between two (already present) instances of the same class, in Python?
I mean, something like Apache Commons' PropertyUtilsBean.copyProperties()
Thanks! | If your class does not modify `__getitem__` or `__setitem__` for special attribute access all your attributes are stored in `__dict__` so you can do:
```
nobj.__dict__ = oobj.__dict__.copy() # just a shallow copy
```
If you use python properties you should look at `inspect.getmembers()` and filter out the ones yo... |
How to copy all properties of an object to another object, in Python? | 243,836 | 21 | 2008-10-28T15:58:11Z | 244,654 | 27 | 2008-10-28T20:06:09Z | [
"python"
] | Is there a library method to copy all the properties between two (already present) instances of the same class, in Python?
I mean, something like Apache Commons' PropertyUtilsBean.copyProperties()
Thanks! | Try `destination.__dict__.update(source.__dict__)`. |
What is the OCaml idiom equivalent to Python's range function? | 243,864 | 16 | 2008-10-28T16:06:33Z | 244,078 | 9 | 2008-10-28T17:07:22Z | [
"python",
"ocaml"
] | I want to create a list of integers from 1 to n. I can do this in Python using range(1, n+1), and in Haskell using: take n (iterate (1+) 1).
What is the right OCaml idiom for this? | Here you go:
```
let rec range i j = if i > j then [] else i :: (range (i+1) j)
```
Note that this is not tail-recursive. Modern Python versions even have a lazy range. |
What is the OCaml idiom equivalent to Python's range function? | 243,864 | 16 | 2008-10-28T16:06:33Z | 244,104 | 19 | 2008-10-28T17:13:42Z | [
"python",
"ocaml"
] | I want to create a list of integers from 1 to n. I can do this in Python using range(1, n+1), and in Haskell using: take n (iterate (1+) 1).
What is the right OCaml idiom for this? | There is no idiom that I know of, but here is a fairly natural definition using an infix operator:
```
# let (--) i j =
let rec aux n acc =
if n < i then acc else aux (n-1) (n :: acc)
in aux j [] ;;
val ( -- ) : int -> int -> int list = <fun>
# 1--2;;
- : int list = [1; 2]
# 1--5;;
- : int list = ... |
What is the OCaml idiom equivalent to Python's range function? | 243,864 | 16 | 2008-10-28T16:06:33Z | 2,926,149 | 10 | 2010-05-28T01:33:00Z | [
"python",
"ocaml"
] | I want to create a list of integers from 1 to n. I can do this in Python using range(1, n+1), and in Haskell using: take n (iterate (1+) 1).
What is the right OCaml idiom for this? | With [Batteries Included](http://batteries.forge.ocamlcore.org), you can write
```
let nums = List.of_enum (1--10);;
```
The `--` operator generates an enumeration from the first value to the second. The `--^` operator is similar, but enumerates a half-open interval (`1--^10` will enumerate from 1 through 9). |
How do I merge two python iterators? | 243,865 | 16 | 2008-10-28T16:07:12Z | 243,892 | 10 | 2008-10-28T16:12:19Z | [
"python",
"merge",
"iterator"
] | I have two iterators, a `list` and an `itertools.count` object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two:
```
>>> import itertools
>>> c = itertools.count(1)
>>> items = ['foo', 'bar']
>>> merged = imerge(items, c) # ... | I'd do something like this. This will be most time and space efficient, since you won't have the overhead of zipping objects together. This will also work if both `a` and `b` are infinite.
```
def imerge(a, b):
i1 = iter(a)
i2 = iter(b)
while True:
try:
yield i1.next()
yield... |
How do I merge two python iterators? | 243,865 | 16 | 2008-10-28T16:07:12Z | 243,902 | 32 | 2008-10-28T16:14:02Z | [
"python",
"merge",
"iterator"
] | I have two iterators, a `list` and an `itertools.count` object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two:
```
>>> import itertools
>>> c = itertools.count(1)
>>> items = ['foo', 'bar']
>>> merged = imerge(items, c) # ... | A generator will solve your problem nicely.
```
def imerge(a, b):
for i, j in itertools.izip(a,b):
yield i
yield j
``` |
How do I merge two python iterators? | 243,865 | 16 | 2008-10-28T16:07:12Z | 244,049 | 13 | 2008-10-28T16:59:35Z | [
"python",
"merge",
"iterator"
] | I have two iterators, a `list` and an `itertools.count` object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two:
```
>>> import itertools
>>> c = itertools.count(1)
>>> items = ['foo', 'bar']
>>> merged = imerge(items, c) # ... | You can do something that is almost exaclty what @Pramod first suggested.
```
def izipmerge(a, b):
for i, j in itertools.izip(a,b):
yield i
yield j
```
The advantage of this approach is that you won't run out of memory if both a and b are infinite. |
How do I merge two python iterators? | 243,865 | 16 | 2008-10-28T16:07:12Z | 345,415 | 8 | 2008-12-05T22:39:29Z | [
"python",
"merge",
"iterator"
] | I have two iterators, a `list` and an `itertools.count` object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two:
```
>>> import itertools
>>> c = itertools.count(1)
>>> items = ['foo', 'bar']
>>> merged = imerge(items, c) # ... | I also agree that itertools is not needed.
But why stop at 2?
```
def tmerge(*iterators):
for values in zip(*iterators):
for value in values:
yield value
```
handles any number of iterators from 0 on upwards.
UPDATE: DOH! A commenter pointed out that this won't work unless all the iterators are ... |
Which Eclipse package to download for pydev? | 243,962 | 52 | 2008-10-28T16:33:20Z | 243,981 | 26 | 2008-10-28T16:39:43Z | [
"python",
"eclipse",
"package",
"pydev"
] | I'm getting started with python, eclipse and pydev. Which Eclipse package should I choose? Nothing on the eclipse homepage tells me what to choose and python documentation assumes I have eclipse installed. Does which package I choose matter? | If you just plan on doing Python dev, I'd just go with [Platform Runtime Binary](http://download.eclipse.org/eclipse/downloads/).
After that, I'd follow the instructions <http://pydev.org/download.html> and <http://pydev.org/manual_101_root.html> to install PyDev.
I use the same setup for Python development. I also h... |
With Lua and Python embeddable, is there a place for Basic? | 244,138 | 6 | 2008-10-28T17:27:32Z | 244,304 | 10 | 2008-10-28T18:24:02Z | [
"python",
"scripting",
"lua",
"interpreter",
"basic"
] | I started off programming in Basic on the [ZX81](http://en.wikipedia.org/wiki/ZX81), then [BASICA](http://en.wikipedia.org/wiki/IBM_BASICA), [GW-BASIC](http://en.wikipedia.org/wiki/GW-BASIC), and [QBasic](http://en.wikipedia.org/wiki/QBasic). I moved on to C (Ah, Turbo C 3.1, I hardly knew ye...)
When I got started in... | [This may come off sounding more negative than it really is. I'm not saying Basic is the root of all evil, [others have said that](http://en.wikiquote.org/wiki/Edsger_Dijkstra). I'm saying it's a legacy we can afford to leave behind.]
**"because it was so easy to understand and so hard to make a mistake"** That's cert... |
Map two lists into one single list of dictionaries | 244,438 | 6 | 2008-10-28T19:06:54Z | 244,551 | 13 | 2008-10-28T19:35:22Z | [
"python",
"dictionary",
"list"
] | Imagine I have these python lists:
```
keys = ['name', 'age']
values = ['Monty', 42, 'Matt', 28, 'Frank', 33]
```
Is there a direct or at least a simple way to produce the following list of dictionaries ?
```
[
{'name': 'Monty', 'age': 42},
{'name': 'Matt', 'age': 28},
{'name': 'Frank', 'age': 33}
]
``` | Here is the zip way
```
def mapper(keys, values):
n = len(keys)
return [dict(zip(keys, values[i:i + n]))
for i in range(0, len(values), n)]
``` |
AJAX console window with ANSI/VT100 support? | 244,750 | 8 | 2008-10-28T20:32:24Z | 244,823 | 9 | 2008-10-28T20:49:22Z | [
"python",
"ajax",
"vt100"
] | I'm planning to write gateway web application, which would need "terminal window" with VT100/ANSI escape code support. Are there any AJAX based alternatives for such a task?
I'm thinking something like this: <http://tryruby.hobix.com/>
My preferred backend for the system is Python/Twisted/Pylons, but since I'm just p... | Try
[AnyTerm](http://wiki.kartbuilding.net/index.php/Anyterm)
[AjaxTerm](http://wiki.kartbuilding.net/index.php/Ajaxterm)
[WebShell](http://www-personal.umich.edu/~mressl/webshell/) |
AJAX console window with ANSI/VT100 support? | 244,750 | 8 | 2008-10-28T20:32:24Z | 963,694 | 7 | 2009-06-08T06:47:26Z | [
"python",
"ajax",
"vt100"
] | I'm planning to write gateway web application, which would need "terminal window" with VT100/ANSI escape code support. Are there any AJAX based alternatives for such a task?
I'm thinking something like this: <http://tryruby.hobix.com/>
My preferred backend for the system is Python/Twisted/Pylons, but since I'm just p... | There's also [Shell In A Box](http://shellinabox.com). |
What are "first class" objects? | 245,192 | 85 | 2008-10-28T22:58:47Z | 245,208 | 82 | 2008-10-28T23:04:22Z | [
"python",
"language-agnostic"
] | When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not?
EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"? | In short, it means there are no restrictions on the object's use. It's the same as
any other object.
A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have.
> Depending on the ... |
What are "first class" objects? | 245,192 | 85 | 2008-10-28T22:58:47Z | 245,209 | 14 | 2008-10-28T23:04:36Z | [
"python",
"language-agnostic"
] | When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not?
EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"? | âFirst classâ means you can operate on them in the usual manner. Most of the times, this just means you can pass these first-class citizens as arguments to functions, or return them from functions.
This is self-evident for objects but not always so evident for functions, or even classes:
```
void f(int n) { retur... |
What are "first class" objects? | 245,192 | 85 | 2008-10-28T22:58:47Z | 245,295 | 9 | 2008-10-28T23:49:30Z | [
"python",
"language-agnostic"
] | When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not?
EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"? | "When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?"
Yes.
Everything in Python is a proper object. Even things that are "primitive types" in other languages.
You find that an object like `2` actually has a fairly rich and sophisticated interface.
```
>>> ... |
What are "first class" objects? | 245,192 | 85 | 2008-10-28T22:58:47Z | 417,721 | 7 | 2009-01-06T19:03:53Z | [
"python",
"language-agnostic"
] | When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not?
EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"? | From a slide in [Structure and Interpretation of Computer Programs](http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/), lecture 2A (1986), which in turns quotes [Christopher Stracey](http://en.wikipedia.org/wiki/Christopher_Strachey):
**The rights and privileges of first-class citizens:**
* To b... |
Which library should I use to write an XLS from Linux / Python? | 245,225 | 7 | 2008-10-28T23:11:54Z | 245,275 | 16 | 2008-10-28T23:37:26Z | [
"java",
"python",
"xls",
"jexcelapi",
"hssf"
] | I'd love a *good* native Python library to write XLS, but it doesn't seem to exist. Happily, Jython does.
So I'm trying to decide between jexcelapi and Apache HSSF:
<http://www.andykhan.com/jexcelapi/tutorial.html#writing>
<http://poi.apache.org/hssf/quick-guide.html>
(I can't use COM automation because I'm not on Wi... | What's wrong with [xlwt](http://pypi.python.org/pypi/xlwt)? |
Running Django with FastCGI or with mod_python | 245,237 | 20 | 2008-10-28T23:16:23Z | 245,660 | 21 | 2008-10-29T03:06:03Z | [
"python",
"django",
"apache",
"fastcgi"
] | which would you recommend?
which is faster, reliable?
apache mod\_python or nginx/lighttpd FastCGI? | I've done both, and Apache/mod\_python tended to be easier to work with and more stable. But these days I've jumped over to Apache/mod\_wsgi, which is everything I've ever wanted and more:
* Easy management of daemon processes.
* As a result, **much** better process isolation (running multiple sites in the same Apache... |
How do I get the name of a function or method from within a Python function or method? | 245,304 | 36 | 2008-10-28T23:52:09Z | 245,333 | 15 | 2008-10-29T00:07:24Z | [
"python"
] | I feel like I should know this, but I haven't been able to figure it out...
I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more... | This decorator makes the name of the method available inside the function by passing it as a keyword argument.
```
from functools import wraps
def pass_func_name(func):
"Name of decorated function will be passed as keyword arg _func_name"
@wraps(func)
def _pass_name(*args, **kwds):
kwds['_func_name... |
How do I get the name of a function or method from within a Python function or method? | 245,304 | 36 | 2008-10-28T23:52:09Z | 245,346 | 52 | 2008-10-29T00:13:35Z | [
"python"
] | I feel like I should know this, but I haven't been able to figure it out...
I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more... | This seems to be the simplest way using module `inspect`:
```
import inspect
def somefunc(a,b,c):
print "My name is: %s" % inspect.stack()[0][3]
```
You could generalise this with:
```
def funcname():
return inspect.stack()[1][3]
def somefunc(a,b,c):
print "My name is: %s" % funcname()
```
Credit to [S... |
How do I get the name of a function or method from within a Python function or method? | 245,304 | 36 | 2008-10-28T23:52:09Z | 245,561 | 10 | 2008-10-29T01:58:33Z | [
"python"
] | I feel like I should know this, but I haven't been able to figure it out...
I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more... | ```
# file "foo.py"
import sys
import os
def LINE( back = 0 ):
return sys._getframe( back + 1 ).f_lineno
def FILE( back = 0 ):
return sys._getframe( back + 1 ).f_code.co_filename
def FUNC( back = 0):
return sys._getframe( back + 1 ).f_code.co_name
def WHERE( back = 0 ):
frame = sys._getframe( back + 1... |
How do I get the name of a function or method from within a Python function or method? | 245,304 | 36 | 2008-10-28T23:52:09Z | 245,581 | 21 | 2008-10-29T02:09:48Z | [
"python"
] | I feel like I should know this, but I haven't been able to figure it out...
I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more... | The answers involving introspection via `inspect` and the like are reasonable. But there may be another option, depending on your situation:
If your integration test is written with the [unittest](http://docs.python.org/library/unittest.html) module, then you could use `self.id()` within your TestCase. |
How do I draw text at an angle using python's PIL? | 245,447 | 15 | 2008-10-29T01:04:48Z | 245,892 | 22 | 2008-10-29T05:31:25Z | [
"python",
"python-imaging-library",
"imaging"
] | Using Python I want to be able to draw text at different angles using PIL.
For example, imagine you were drawing the number around the face of a clock. The number **3** would appear as expected whereas **12** would we drawn rotated counter-clockwise 90 degrees.
Therefore, I need to be able to draw many different stri... | Draw text into a temporary blank image, rotate that, then paste that onto the original image. You could wrap up the steps in a function. Good luck figuring out the exact coordinates to use - my cold-fogged brain isn't up to it right now.
This demo writes yellow text on a slant over an image:
```
# Demo to add rotated... |
How do I draw text at an angle using python's PIL? | 245,447 | 15 | 2008-10-29T01:04:48Z | 741,592 | 7 | 2009-04-12T10:48:23Z | [
"python",
"python-imaging-library",
"imaging"
] | Using Python I want to be able to draw text at different angles using PIL.
For example, imagine you were drawing the number around the face of a clock. The number **3** would appear as expected whereas **12** would we drawn rotated counter-clockwise 90 degrees.
Therefore, I need to be able to draw many different stri... | It's also usefull to know our text's size in pixels before we create an Image object. I used such code when drawing graphs. Then I got no problems e.g. with alignment of data labels (the image is exactly as big as the text).
```
(...)
img_main = Image.new("RGB", (200, 200))
font = ImageFont.load_default()
# Text to b... |
When is not a good time to use python generators? | 245,792 | 55 | 2008-10-29T04:25:02Z | 245,797 | 16 | 2008-10-29T04:28:58Z | [
"python",
"optimization",
"iterator",
"generator"
] | This is rather the inverse of [What can you use Python generator functions for?](http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for): python generators, generator expressions, and the `itertools` module are some of my favorite features of python these days. They're especially usef... | You should never favor [`zip`](http://docs.python.org/2/library/functions.html#zip) over [`izip`](http://docs.python.org/2/library/itertools.html#itertools.izip), `range` over `xrange`, or list comprehensions over generator comprehensions. In Python 3.0 `range` has `xrange`-like semantics and `zip` has `izip`-like sema... |
When is not a good time to use python generators? | 245,792 | 55 | 2008-10-29T04:25:02Z | 245,816 | 33 | 2008-10-29T04:42:05Z | [
"python",
"optimization",
"iterator",
"generator"
] | This is rather the inverse of [What can you use Python generator functions for?](http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for): python generators, generator expressions, and the `itertools` module are some of my favorite features of python these days. They're especially usef... | In general, don't use a generator when you need list operations, like len(), reversed(), and so on.
There may also be times when you don't want lazy evaluation (e.g. to do all the calculation up front so you can release a resource). In that case, a list expression might be better. |
When is not a good time to use python generators? | 245,792 | 55 | 2008-10-29T04:25:02Z | 246,481 | 21 | 2008-10-29T11:37:31Z | [
"python",
"optimization",
"iterator",
"generator"
] | This is rather the inverse of [What can you use Python generator functions for?](http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for): python generators, generator expressions, and the `itertools` module are some of my favorite features of python these days. They're especially usef... | Profile, Profile, Profile.
Profiling your code is the only way to know if what you're doing has any effect at all.
Most usages of xrange, generators, etc are over static size, small datasets. It's only when you get to large datasets that it really makes a difference. range() vs. xrange() is mostly just a matter of ma... |
When is not a good time to use python generators? | 245,792 | 55 | 2008-10-29T04:25:02Z | 26,635,939 | 24 | 2014-10-29T16:36:57Z | [
"python",
"optimization",
"iterator",
"generator"
] | This is rather the inverse of [What can you use Python generator functions for?](http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for): python generators, generator expressions, and the `itertools` module are some of my favorite features of python these days. They're especially usef... | **Use a list instead of a generator when:**
1) You need to access the data **multiple** times (i.e. cache the results instead of recomputing them):
```
for i in outer: # used once, okay to be a generator or return a list
for j in inner: # used multiple times, reusing a list is better
...
... |
How can I draw a bezier curve using Python's PIL? | 246,525 | 11 | 2008-10-29T11:59:08Z | 246,628 | 10 | 2008-10-29T12:39:15Z | [
"python",
"python-imaging-library",
"bezier",
"imaging"
] | I'm using Python's Imaging Library and I would like to draw some bezier curves.
I guess I could calculate pixel by pixel but I'm hoping there is something simpler. | A bezier curve isn't that hard to draw yourself. Given three points `A`, `B`, `C` you require three linear interpolations in order to draw the curve. We use the scalar `t` as the parameter for the linear interpolation:
```
P0 = A * t + (1 - t) * B
P1 = B * t + (1 - t) * C
```
This interpolates between two edges we've... |
How can I draw a bezier curve using Python's PIL? | 246,525 | 11 | 2008-10-29T11:59:08Z | 246,933 | 7 | 2008-10-29T14:09:59Z | [
"python",
"python-imaging-library",
"bezier",
"imaging"
] | I'm using Python's Imaging Library and I would like to draw some bezier curves.
I guess I could calculate pixel by pixel but I'm hoping there is something simpler. | You can use the [aggdraw](http://effbot.org/zone/aggdraw-index.htm) on top of PIL, bezier curves are [supported](http://effbot.org/zone/pythondoc-aggdraw.htm#aggdraw.Path-class).
**EDIT:**
I made an example only to discover there is a bug in the `Path` class regarding `curveto` :(
Here is the example anyway:
```
fr... |
How can I draw a bezier curve using Python's PIL? | 246,525 | 11 | 2008-10-29T11:59:08Z | 2,292,690 | 16 | 2010-02-18T22:23:02Z | [
"python",
"python-imaging-library",
"bezier",
"imaging"
] | I'm using Python's Imaging Library and I would like to draw some bezier curves.
I guess I could calculate pixel by pixel but I'm hoping there is something simpler. | ```
def make_bezier(xys):
# xys should be a sequence of 2-tuples (Bezier control points)
n = len(xys)
combinations = pascal_row(n-1)
def bezier(ts):
# This uses the generalized formula for bezier curves
# http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization
result = []
... |
How do I add tab completion to the Python shell? | 246,725 | 55 | 2008-10-29T13:09:10Z | 246,774 | 30 | 2008-10-29T13:21:43Z | [
"python",
"shell",
"interpreter"
] | When starting a django application using `python manage.py shell`, I get an InteractiveConsole shell - I can use tab completion, etc.
```
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveCo... | I think django does something like <https://docs.python.org/library/rlcompleter.html>
If you want to have a really good interactive interpreter have a look at
<http://ipython.scipy.org/>. |
How do I add tab completion to the Python shell? | 246,725 | 55 | 2008-10-29T13:09:10Z | 246,779 | 91 | 2008-10-29T13:24:39Z | [
"python",
"shell",
"interpreter"
] | When starting a django application using `python manage.py shell`, I get an InteractiveConsole shell - I can use tab completion, etc.
```
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveCo... | I may have found a way to do it.
Create a file .pythonrc
```
# ~/.pythonrc
# enable syntax completion
try:
import readline
except ImportError:
print("Module readline not available.")
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
```
then in your .bashrc file, add
```
export PYTHO... |
How do I add tab completion to the Python shell? | 246,725 | 55 | 2008-10-29T13:09:10Z | 247,513 | 21 | 2008-10-29T16:39:03Z | [
"python",
"shell",
"interpreter"
] | When starting a django application using `python manage.py shell`, I get an InteractiveConsole shell - I can use tab completion, etc.
```
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveCo... | For the record, this is covered in the tutorial: <http://docs.python.org/tutorial/interactive.html> |
How can I launch an instance of an application using Python? | 247,724 | 11 | 2008-10-29T17:40:12Z | 247,740 | 8 | 2008-10-29T17:44:31Z | [
"python",
"scripting",
"ipc"
] | I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script? | or
```
os.system("start excel.exe <path/to/file>")
```
(presuming it's in the path, and you're on windows)
and also on Windows, just `start <filename>` works, too - if it's an associated extension already (as xls would be) |
How can I launch an instance of an application using Python? | 247,724 | 11 | 2008-10-29T17:40:12Z | 248,080 | 10 | 2008-10-29T19:22:09Z | [
"python",
"scripting",
"ipc"
] | I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script? | While the `Popen` answers are reasonable for the general case, I would recommend `win32api` for this specific case, if you want to do something useful with it:
It goes something like this:
```
from win32com.client import Dispatch
xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Open('C:\\Documents and Settings\\G... |
Retrieving python module path | 247,770 | 351 | 2008-10-29T17:52:40Z | 248,066 | 13 | 2008-10-29T19:18:15Z | [
"python",
"module",
"inotify"
] | I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.
How do I retrieve a module's path in python? | This was trivial.
Each module has a `__file__` variable that shows its relative path from where you are right now.
Therefore, getting a directory for the module to notify it is simple as:
```
os.path.dirname(__file__)
``` |
Retrieving python module path | 247,770 | 351 | 2008-10-29T17:52:40Z | 248,862 | 385 | 2008-10-29T23:57:13Z | [
"python",
"module",
"inotify"
] | I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.
How do I retrieve a module's path in python? | ```
import a_module
print a_module.__file__
```
Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do
```
import os
path = os.path.dirname(amodule.__file__)
```
You can also try
```
path = os.path.abspath(amodule.__file__)
```
To get the directory to look for... |
Retrieving python module path | 247,770 | 351 | 2008-10-29T17:52:40Z | 4,431,672 | 12 | 2010-12-13T17:35:17Z | [
"python",
"module",
"inotify"
] | I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.
How do I retrieve a module's path in python? | ```
import os
path = os.path.abspath(__file__)
dir_path = os.path.dirname(path)
``` |
Retrieving python module path | 247,770 | 351 | 2008-10-29T17:52:40Z | 6,416,114 | 49 | 2011-06-20T19:05:40Z | [
"python",
"module",
"inotify"
] | I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.
How do I retrieve a module's path in python? | As the other answers have said, the best way to do this is with `__file__` (demonstrated again below). However, there is an important caveat, which is that `__file__` does NOT exist if you are running the module on its own (i.e. as `__main__`).
For example, say you have two files (both of which are on your PYTHONPATH)... |
Retrieving python module path | 247,770 | 351 | 2008-10-29T17:52:40Z | 12,154,601 | 121 | 2012-08-28T07:24:09Z | [
"python",
"module",
"inotify"
] | I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.
How do I retrieve a module's path in python? | There is `inspect` module in python.
## [Official documentation](http://docs.python.org/library/inspect.html)
> The inspect module provides several useful functions to help get
> information about live objects such as modules, classes, methods,
> functions, tracebacks, frame objects, and code objects. For example,
> ... |
Retrieving python module path | 247,770 | 351 | 2008-10-29T17:52:40Z | 16,826,913 | 22 | 2013-05-30T02:15:40Z | [
"python",
"module",
"inotify"
] | I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.
How do I retrieve a module's path in python? | I will try tackling a few variations on this question as well:
1. finding the path of the called script
2. finding the path of the currently executing script
3. finding the directory of the called script
(Some of these questions have been asked on SO, but have been closed as duplicates and redirected here.)
## Cavea... |
Retrieving python module path | 247,770 | 351 | 2008-10-29T17:52:40Z | 28,976,381 | 10 | 2015-03-11T00:10:44Z | [
"python",
"module",
"inotify"
] | I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.
How do I retrieve a module's path in python? | I don't get why no one is talking about this, but to me the simplest solution is using **imp.find\_module("modulename")** (documentation [here](https://docs.python.org/2/library/imp.html?highlight=import#module-imp)):
```
import imp
imp.find_module("os")
```
It gives a tuple with the path in second position:
```
(<o... |
Is there something between a normal user account and root? | 248,730 | 3 | 2008-10-29T23:02:30Z | 248,758 | 7 | 2008-10-29T23:11:01Z | [
"python",
"linux",
"root"
] | I'm developing an application that manages network interfaces on behalf of the user and it calls out to several external programs (such as ifconfig) that requires root to make changes. (Specifically, changing the IP address of a local interface, etc.) During development, I have been running the IDE as root (ugh) and th... | Your idea about the daemon has much merit, despite the complexity it introduces. As long as the actions don't require some user interface interaction *as root*, a daemon allows you to control what operations are allowed and disallowed.
However, you can use SUDO to create a controlled compromise between ROOT and normal... |
Python: using a recursive algorithm as a generator | 248,830 | 79 | 2008-10-29T23:45:56Z | 248,854 | 96 | 2008-10-29T23:53:47Z | [
"python",
"recursion",
"generator"
] | Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list ... | ```
def getPermutations(string, prefix=""):
if len(string) == 1:
yield prefix + string
else:
for i in xrange(len(string)):
for perm in getPermutations(string[:i] + string[i+1:], prefix+string[i]):
yield perm
```
Or without an accumulator:
```
def getPermutations(str... |
Python: using a recursive algorithm as a generator | 248,830 | 79 | 2008-10-29T23:45:56Z | 248,857 | 19 | 2008-10-29T23:54:51Z | [
"python",
"recursion",
"generator"
] | Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list ... | The interior call to getPermutations -- it's a generator, too.
```
def getPermutations(string, prefix=""):
if len(string) == 1:
yield prefix + string
else:
for i in range(len(string)):
getPermutations(string[:i]+string[i+1:], prefix+string[i]) # <-----
```
You need to iterate t... |
Python: using a recursive algorithm as a generator | 248,830 | 79 | 2008-10-29T23:45:56Z | 252,199 | 24 | 2008-10-31T00:05:38Z | [
"python",
"recursion",
"generator"
] | Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list ... | This avoids the `len(string)`-deep recursion, and is in general a nice way to handle generators-inside-generators:
```
from types import GeneratorType
def flatten(*stack):
stack = list(stack)
while stack:
try: x = stack[0].next()
except StopIteration:
stack.pop(0)
conti... |
I need a really good reason to use Python | 249,064 | 10 | 2008-10-30T01:59:48Z | 249,075 | 12 | 2008-10-30T02:04:09Z | [
"python"
] | I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like [IronRuby](http://en.wikipe... | Almost no problem **requires** a specific programming language, that's just not how things work.
The easiest way to get a new language into an environment like yours is to start a new work project in your own time in the new language. Make it do something you need doing, and write it on your own time. Use it yourself,... |
I need a really good reason to use Python | 249,064 | 10 | 2008-10-30T01:59:48Z | 249,101 | 28 | 2008-10-30T02:12:10Z | [
"python"
] | I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like [IronRuby](http://en.wikipe... | "Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?"
Nope.
Nothing succeeds like success. Use Python. Be successful. Make people jealous.
When asked why you're successful, you can talk about Python. Not before.
Choose projects wisely: things wh... |
Django: Arbitrary number of unnamed urls.py parameters | 249,110 | 16 | 2008-10-30T02:18:32Z | 249,524 | 11 | 2008-10-30T07:52:30Z | [
"python",
"django",
"django-urls"
] | I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:
```
/browse/<name1>/<value1>/<name2>/<value2>/ .... etc ....
```
where 'name' maps to a mo... | A possibility that you might consider is matching the entire string of possible values within the url pattern portion and pull out the specific pieces within your view. As an example:
```
urlpatterns = patterns('',
url(r'^browse/(?P<match>.+)/$', 'app.views.view', name='model_browse'),
)
def view(request, match):... |
Virtualenv on Ubuntu with no site-packages | 249,283 | 24 | 2008-10-30T04:32:52Z | 1,670,513 | 34 | 2009-11-03T22:20:07Z | [
"python",
"ubuntu",
"pygtk",
"virtualenv"
] | I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the --no-site-packages option, but doing this while developing a PyGTK app can be a bit tricky. The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --... | ```
$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv
$ cd myvirtualenv
$ source bin/activate
$ cd lib/python2.6/
$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/
$ ln -s /usr/lib/pymodules/python2.6/pygtk.pth
$ ln -s /usr/lib/pymodules/python2.6/pygtk.py
$ ln -s /usr/lib/pymodules/python2.6/cair... |
How to determine if a directory is on same partition | 249,775 | 6 | 2008-10-30T10:45:42Z | 249,796 | 11 | 2008-10-30T10:54:11Z | [
"python",
"linux",
"osx",
"filesystems"
] | Say I have an input file, and a target directory. How do I determine if the input file is on the same hard-drive (or partition) as the target directory?
What I want to do is the copy a file if it's on a different, but move it if it's the same. For example:
```
target_directory = "/Volumes/externalDrive/something/"
in... | In C, you would use `stat()` and compare the `st_dev` field. In python, `os.stat` should do the same. |
How can I add post-install scripts to easy_install / setuptools / distutils? | 250,038 | 30 | 2008-10-30T12:42:10Z | 253,103 | 7 | 2008-10-31T10:33:46Z | [
"python",
"setuptools",
"distutils"
] | I would like to be able to add a hook to my setup.py that will be run post-install (either when easy\_install'ing or when doing python setup.py install).
In my project, [PySmell](http://code.google.com/p/pysmell), I have some support files for Vim and Emacs. When a user installs PySmell the usual way, these files get ... | It depends on how the user installs your package. If the user actually runs "setup.py install", it's fairly easy: Just add another subcommand to the install command (say, install\_vim), whose run() method will copy the files you want in the places where you want them. You can add your subcommand to install.sub\_command... |
Lua as a general-purpose scripting language? | 250,151 | 33 | 2008-10-30T13:21:41Z | 250,158 | 10 | 2008-10-30T13:24:26Z | [
"python",
"scripting",
"lua"
] | When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".
Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?
Lua seems... | Just because it is "marketed" (in some general sense) as a special-purpose language for embedded script engines, does not mean that it is limited to that. In fact, WoW could probably just as well have chosen Python as their embedded scripting language. |
Lua as a general-purpose scripting language? | 250,151 | 33 | 2008-10-30T13:21:41Z | 250,168 | 9 | 2008-10-30T13:28:04Z | [
"python",
"scripting",
"lua"
] | When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".
Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?
Lua seems... | It's probably because Lua was designed as a scripting and extension language. On the [official site](http://www.lua.org/about.html) it's described as a powerful, fast, light-weight, embeddable scripting language. There's nothing stopping you from writing general purpose programs for it (if I recall correctly it ships w... |
Lua as a general-purpose scripting language? | 250,151 | 33 | 2008-10-30T13:21:41Z | 252,900 | 33 | 2008-10-31T08:48:29Z | [
"python",
"scripting",
"lua"
] | When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".
Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?
Lua seems... | Lua is a cool language, light-weight and extremely fast!
But the point is: **Is performance so important for those
tasks you mentioned?**
* Renaming a bunch of files
* Download some files from the web
* Webscraping
You write those programs once, and run them once, too maybe.
Why do you care about performance so much... |
Lua as a general-purpose scripting language? | 250,151 | 33 | 2008-10-30T13:21:41Z | 253,755 | 21 | 2008-10-31T14:40:55Z | [
"python",
"scripting",
"lua"
] | When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".
Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?
Lua seems... | Lua has fewer libraries than Python. But be sure to have a look at [LuaForge](http://luaforge.net/). It has a lot of interesting libs, like [LuaCURL](http://luaforge.net/projects/luacurl/), [wxLua](http://wxlua.sourceforge.net/) or [getopt](http://luaforge.net/projects/getopt/).
Then, visit [LuaRocks](http://luarocks.... |
Lua as a general-purpose scripting language? | 250,151 | 33 | 2008-10-30T13:21:41Z | 326,660 | 8 | 2008-11-28T20:56:38Z | [
"python",
"scripting",
"lua"
] | When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".
Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?
Lua seems... | This is a sociological question, not a programming question.
I use Lua for general-purpose scripting almost exclusively. But I had to write a few hundred lines of code so that Lua would play better with the shell. This included such tricks as
* Quoting a string so it is seen as one word by the shell
* Writing a funct... |
How can I optimize this Google App Engine code? | 250,209 | 5 | 2008-10-30T13:40:19Z | 250,395 | 7 | 2008-10-30T14:41:19Z | [
"python",
"google-app-engine",
"optimization"
] | I'm relatively new to the python world, but this seems very straight forward.
Google is yelling at me that this code needs to be optimized:
```
class AddLinks(webapp.RequestHandler):
def post(self):
# Hash the textarea input to generate pseudo-unique value
hash = md5.new(self.request.get('lin... | The main overhead here is the multiple individual puts to the datastore. If you can, store the links as a single entity, as Andre suggests. You can always split the links into an array and store it in a ListProperty.
If you do need an entity for each link, try this:
```
# For each line in the input, add to the databa... |
Python Regex - How to Get Positions of Matches | 250,271 | 50 | 2008-10-30T14:04:33Z | 250,303 | 65 | 2008-10-30T14:15:39Z | [
"python",
"regex"
] | How can I get the start and end positions of all matches using the `re` module? For example given the pattern `r'[a-z]'` and the string `'a1b2c3d4'` I'd want to get the positions where it finds each letter (ideally I'd like to get the text of the match back too). | ```
import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
print m.start(), m.group()
``` |
Python Regex - How to Get Positions of Matches | 250,271 | 50 | 2008-10-30T14:04:33Z | 250,306 | 27 | 2008-10-30T14:16:02Z | [
"python",
"regex"
] | How can I get the start and end positions of all matches using the `re` module? For example given the pattern `r'[a-z]'` and the string `'a1b2c3d4'` I'd want to get the positions where it finds each letter (ideally I'd like to get the text of the match back too). | Taken from
[*Regular Expression HOWTO*](http://docs.python.org/3.3/howto/regex.html)
> span() returns both start and end indexes in a single tuple. Since the
> match method only checks if the RE matches at the start of a string,
> start() will always be zero. However, the search method of RegexObject
> instances scan... |
How to scp in python? | 250,283 | 97 | 2008-10-30T14:09:21Z | 250,786 | 11 | 2008-10-30T16:18:00Z | [
"python",
"ssh",
"scp"
] | What's the most pythonic way to scp a file in Python? The only route I'm aware of is
```
os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )
```
which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you alread... | You might be interested in trying [Pexpect](http://www.noah.org/wiki/Pexpect) ([SourceForge project](http://sourceforge.net/projects/pexpect/)). This would allow you to deal with interactive prompts for your password.
Here's a snip of example usage (for ftp) from the main website:
```
# This connects to the openbs... |
How to scp in python? | 250,283 | 97 | 2008-10-30T14:09:21Z | 251,625 | 8 | 2008-10-30T20:22:43Z | [
"python",
"ssh",
"scp"
] | What's the most pythonic way to scp a file in Python? The only route I'm aware of is
```
os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )
```
which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you alread... | You could also check out [paramiko](http://www.lag.net/paramiko/). There's no scp module (yet), but it fully supports sftp.
[EDIT]
Sorry, missed the line where you mentioned paramiko.
The following module is simply an implementation of the scp protocol for paramiko.
If you don't want to use paramiko or conch (the only... |
How to scp in python? | 250,283 | 97 | 2008-10-30T14:09:21Z | 4,282,261 | 62 | 2010-11-26T03:03:37Z | [
"python",
"ssh",
"scp"
] | What's the most pythonic way to scp a file in Python? The only route I'm aware of is
```
os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )
```
which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you alread... | Try the module [paramiko\_scp](https://github.com/jbardin/scp.py). It's very easy to use. See the following example:
```
def createSSHClient(server, port, user, password):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.co... |
Truncate a string without ending in the middle of a word | 250,357 | 31 | 2008-10-30T14:32:20Z | 250,373 | 49 | 2008-10-30T14:36:03Z | [
"python",
"truncate"
] | I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.
For example:
```
Original: "This is really awesome."
"Dumb" truncate: "This is real..."
"Smart" truncate: "This is really..."
```
I'm looking for a way to accomplish the "smart" truncate from a... | I actually wrote a solution for this on a recent project of mine. I've compressed the majority of it down to be a little smaller.
```
def smart_truncate(content, length=100, suffix='...'):
if len(content) <= length:
return content
else:
return ' '.join(content[:length+1].split(' ')[0:-1]) + suf... |
Truncate a string without ending in the middle of a word | 250,357 | 31 | 2008-10-30T14:32:20Z | 250,406 | 36 | 2008-10-30T14:43:16Z | [
"python",
"truncate"
] | I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.
For example:
```
Original: "This is really awesome."
"Dumb" truncate: "This is real..."
"Smart" truncate: "This is really..."
```
I'm looking for a way to accomplish the "smart" truncate from a... | Here's a slightly better version of the last line in Adam's solution:
```
return content[:length].rsplit(' ', 1)[0]+suffix
```
(This is slightly more efficient, and returns a more sensible result in the case there are no spaces in the front of the string.) |
Truncate a string without ending in the middle of a word | 250,357 | 31 | 2008-10-30T14:32:20Z | 250,471 | 7 | 2008-10-30T14:59:41Z | [
"python",
"truncate"
] | I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.
For example:
```
Original: "This is really awesome."
"Dumb" truncate: "This is real..."
"Smart" truncate: "This is really..."
```
I'm looking for a way to accomplish the "smart" truncate from a... | ```
def smart_truncate1(text, max_length=100, suffix='...'):
"""Returns a string of at most `max_length` characters, cutting
only at word-boundaries. If the string was truncated, `suffix`
will be appended.
"""
if len(text) > max_length:
pattern = r'^(.{0,%d}\S)\s.*' % (max_length-len(suffix... |
Truncate a string without ending in the middle of a word | 250,357 | 31 | 2008-10-30T14:32:20Z | 250,684 | 11 | 2008-10-30T15:47:04Z | [
"python",
"truncate"
] | I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.
For example:
```
Original: "This is really awesome."
"Dumb" truncate: "This is real..."
"Smart" truncate: "This is really..."
```
I'm looking for a way to accomplish the "smart" truncate from a... | There are a few subtleties that may or may not be issues for you, such as handling of tabs (Eg. if you're displaying them as 8 spaces, but treating them as 1 character internally), handling various flavours of breaking and non-breaking whitespace, or allowing breaking on hyphenation etc. If any of this is desirable, yo... |
What do you like about Django? | 250,397 | 6 | 2008-10-30T14:41:38Z | 250,459 | 8 | 2008-10-30T14:57:22Z | [
"python",
"django"
] | I started to learn Django a few days ago, and as i dive into it it seems that I'm starting to like it even more.
Trying to migrate from other language.
I won't say which one, as the purpose of this question is not to bash anything.
So i would like to know your opinion about Django.
What do you like about it?
What... | ***What do I like about it :***
* Very simple ORM
* clear separation of template / controller
* django-admin
* pluggable apps : it seems to me that the Django community really nailed that one !
***What made me switch :***
* mainly curiosity
* I heard a lot of good things about it from a colleague
* I wanted somethin... |
What do you like about Django? | 250,397 | 6 | 2008-10-30T14:41:38Z | 250,461 | 8 | 2008-10-30T14:57:53Z | [
"python",
"django"
] | I started to learn Django a few days ago, and as i dive into it it seems that I'm starting to like it even more.
Trying to migrate from other language.
I won't say which one, as the purpose of this question is not to bash anything.
So i would like to know your opinion about Django.
What do you like about it?
What... | ### What do you like about it?
URL dispatching: I was never a big fan of "/foo.php" is the file "foo.php" on my server, and if I want nicer URLs I need to mess around with mod\_rewrite and keep that in line with what my logic in foo expects.
ORM: Because 90%+ of your queries, in my experience, do not need to be writt... |
How to get a function name as a string in Python? | 251,464 | 306 | 2008-10-30T19:38:24Z | 251,469 | 32 | 2008-10-30T19:39:19Z | [
"python",
"string",
"function"
] | In Python, how do I get a function name as a string without calling the function?
```
def my_function():
pass
print get_function_name_as_string(my_function) # my_function is not in quotes
```
should output `"my_function"`.
Is this available in python? If not, any idea how to write `get_function_name_as_string` ... | ```
my_function.func_name
```
There are also other fun properties of functions. Type `dir(func_name)` to list them. `func_name.func_code.co_code` is the compiled function, stored as a string.
```
import dis
dis.dis(my_function)
```
will display the code in *almost* human readable format. :) |
How to get a function name as a string in Python? | 251,464 | 306 | 2008-10-30T19:38:24Z | 255,297 | 357 | 2008-11-01T00:07:17Z | [
"python",
"string",
"function"
] | In Python, how do I get a function name as a string without calling the function?
```
def my_function():
pass
print get_function_name_as_string(my_function) # my_function is not in quotes
```
should output `"my_function"`.
Is this available in python? If not, any idea how to write `get_function_name_as_string` ... | ```
my_function.__name__
```
Using `__name__` is the preferred method as it applies uniformly. Unlike `func_name`, it works on built-in functions as well:
```
>>> import time
>>> time.time.func_name
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'builtin_function_or_method' object h... |
How to get a function name as a string in Python? | 251,464 | 306 | 2008-10-30T19:38:24Z | 13,514,318 | 116 | 2012-11-22T13:59:49Z | [
"python",
"string",
"function"
] | In Python, how do I get a function name as a string without calling the function?
```
def my_function():
pass
print get_function_name_as_string(my_function) # my_function is not in quotes
```
should output `"my_function"`.
Is this available in python? If not, any idea how to write `get_function_name_as_string` ... | You could also use
```
import sys
this_function_name = sys._getframe().f_code.co_name
``` |
How to get a function name as a string in Python? | 251,464 | 306 | 2008-10-30T19:38:24Z | 20,714,270 | 21 | 2013-12-21T00:59:58Z | [
"python",
"string",
"function"
] | In Python, how do I get a function name as a string without calling the function?
```
def my_function():
pass
print get_function_name_as_string(my_function) # my_function is not in quotes
```
should output `"my_function"`.
Is this available in python? If not, any idea how to write `get_function_name_as_string` ... | This function will return the caller's function name.
```
def func_name():
import traceback
return traceback.extract_stack(None, 2)[0][2]
```
It is like Albert Vonpupp's answer with a friendly wrapper. |
Possible Google Riddle? | 252,221 | 11 | 2008-10-31T00:14:12Z | 260,580 | 15 | 2008-11-04T01:46:39Z | [
"python"
] | My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.
[t-shirt](http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg)
So, I have a couple of guesses as to what it means, but I was just wondering if ther... | I emailed the Website Optimizer Team, and they said "There's no secret code, unless you find one. :)" |
How can I use a DLL file from Python? | 252,417 | 105 | 2008-10-31T02:01:48Z | 252,473 | 88 | 2008-10-31T02:43:41Z | [
"python",
"dll"
] | What is the easiest way to use a DLL file from within Python?
Specifically, how can this be done *without* writing any additional wrapper C++ code to expose the functionality to Python?
Native Python functionality is strongly preferred over using a third-party library. | For ease of use, [ctypes](http://docs.python.org/library/ctypes.html) is the way to go.
The following example of ctypes is from actual code I've written (in Python 2.5). This has been, by far, the easiest way I've found for doing what you ask.
```
import ctypes
# Load DLL into memory.
hllDll = ctypes.WinDLL ("c:\\P... |
How can I use a DLL file from Python? | 252,417 | 105 | 2008-10-31T02:01:48Z | 3,173,926 | 32 | 2010-07-04T06:28:31Z | [
"python",
"dll"
] | What is the easiest way to use a DLL file from within Python?
Specifically, how can this be done *without* writing any additional wrapper C++ code to expose the functionality to Python?
Native Python functionality is strongly preferred over using a third-party library. | [This page](http://web.archive.org/web/20111006042404/http://www.knowledgetantra.com/component/content/article/2-python/1-call-dll-function-in-python.html) is a very simple example of calling functions from a DLL file.
> It's very easy to call a DLL function in Python. I have a self-made DLL file with two functions: `... |
Why won't Django 1.0 admin application work? | 252,531 | 5 | 2008-10-31T03:35:19Z | 252,621 | 12 | 2008-10-31T04:50:27Z | [
"python",
"django",
"admin"
] | I've just started playing with Django and am loosely following the tutorial with my own set of basic requirements. The models I've sketched out so far are a lot more comprehensive than the tutorial, but they compile fine. Otherwise, everything should have been the same.
My problem is with the admin application. I can ... | It's because you left out a `/` in `urls.py`. Change the admin line to the following:
```
(r'^admin/(.*)', admin.site.root),
```
I checked this on my server and got the same error with your line from `urls.py`. |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 252,704 | 72 | 2008-10-31T05:57:32Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | `append` appends a single element. `extend` appends a list of elements.
Note that if you pass a list to append, it still adds one element:
```
>>> a = [1, 2, 3]
>>> a.append([4, 5, 6])
>>> a
[1, 2, 3, [4, 5, 6]]
``` |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 252,705 | 388 | 2008-10-31T05:57:37Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | `append` adds an element to a list, `extend` concatenates the first list with another list (or another iterable not necessarily a list.)
```
>>> li = ['a', 'b', 'mpilgrim', 'z', 'example']
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', '... |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 252,711 | 2,392 | 2008-10-31T06:02:25Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | [`append`](https://docs.python.org/2/library/array.html?#array.array.append): Appends object at end.
```
x = [1, 2, 3]
x.append([4, 5])
print (x)
```
gives you: `[1, 2, 3, [4, 5]]`
---
[`extend`](https://docs.python.org/2/library/array.html?#array.array.extend): Extends list by appending elements from the iterable.... |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 252,918 | 50 | 2008-10-31T09:03:22Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | Good answers, but don't forget, any iterable will do for `extend` (not just list):
```
l.extend(xrange(5))
``` |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 262,132 | 197 | 2008-11-04T15:19:52Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | And in this context it can also be good to remember that strings are also iterable.
```
>>> a = [1, 2]
>>> a
[1, 2]
>>> a.extend('hey')
>>> a
[1, 2, 'h', 'e', 'y']
``` |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 5,605,403 | 31 | 2011-04-09T13:46:02Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | Like `Ali A` said, any iterable will do for the extend,
here is an example for dictionary argument,
```
>>> li=[1,2,3]
>>> li.extend({4:5,6:7})
>>> li
[1, 2, 3, 4, 6]
>>>
```
as you can see, only `keys` are added to the list. |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 12,045,242 | 28 | 2012-08-20T21:11:00Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | The following two snippets are semantically equivalent:
```
for item in iterator:
a_list.append(item)
```
and
```
a_list.extend(iterator)
```
The latter may be faster as the loop is implemented in C. |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 16,510,635 | 10 | 2013-05-12T18:21:40Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | `extend()` can be used with an iterator argument. Here is an example. You wish to make a list out of a list of lists this way:
from
```
list2d = [[1,2,3],[4,5,6], [7], [8,9]]
```
you want
```
>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]
```
You may use `itertools.chain.from_iterable()` to do so. This method's output is an ite... |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 16,511,403 | 10 | 2013-05-12T19:51:07Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | append(object) - Updates the list by adding an object to the list.
```
x = [20]
# list passed to the append(object) method is treated as a single object.
x.append([21,22,23])
#hence the resultant list length will be 2
print x
--> [20, [21,22,23]]
```
extend(list) - Essentially concatenates 2 lists.
```
x = [20]
#t... |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 18,442,908 | 20 | 2013-08-26T11:21:12Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | You can use "+" for returning extend, instead of extending in place.
```
l1=range(10)
l1+[11]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
l2=range(10,1,-1)
l1+l2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2]
```
Similarly `+=` for in place behavior, but with slight differences from `append` & `extend`. One o... |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 19,707,477 | 22 | 2013-10-31T13:12:10Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | The append() method adds a single item to the end of the list.
```
x = [1, 2, 3]
x.append([4, 5])
x.append('abc')
print x
# gives you
[1, 2, 3, [4, 5], 'abc']
```
The extend() method takes one argument, a list, and appends each of the items of the argument to the original list. (Lists are implemented as classes. âC... |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 24,632,188 | 8 | 2014-07-08T12:42:52Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | This is the equivalent of `append` and `extend` using the `+` operator:
```
>>> x = [1,2,3]
>>> x
[1, 2, 3]
>>> x = x + [4,5,6] # Extend
>>> x
[1, 2, 3, 4, 5, 6]
>>> x = x + [[7,8]] # Append
>>> x
[1, 2, 3, 4, 5, 6, [7, 8]]
``` |
append vs. extend | 252,703 | 1,581 | 2008-10-31T05:55:36Z | 28,119,966 | 58 | 2015-01-23T22:44:37Z | [
"python",
"list",
"append",
"extend"
] | What's the difference between the list methods `append()` and `extend()`? | > # What is the difference between the list methods append and extend?
* `append` adds its argument as a single element to the end of a list. The length of the list itself will increase by one.
* `extend` iterates over its argument adding each element to the list, extending the list. The length of the list will increa... |
What Python bindings are there for CVS or SVN? | 253,375 | 13 | 2008-10-31T12:51:14Z | 253,390 | 8 | 2008-10-31T13:01:31Z | [
"python",
"svn",
"version-control",
"cvs"
] | I once did a cursory search and found no good CVS bindings for Python. I wanted to be able to write helper scripts to do some fine-grained manipulation of the repository and projects in it. I had to resort to using `popen` and checking `stdout` and `stderr` and then parsing those. It was messy and error-prone.
Are the... | For cvs, [pyCVS](http://pycvs.sourceforge.net/) may be worth a look.
For svn, there is [pysvn](http://pysvn.tigris.org/), which is pretty good. |
In Python, is there a concise way of comparing whether the contents of two text files are the same? | 254,350 | 29 | 2008-10-31T17:47:39Z | 254,357 | 40 | 2008-10-31T17:50:04Z | [
"python"
] | I don't care what the differences are. I just want to know whether the contents are different. | The low level way:
```
from __future__ import with_statement
with open(filename1) as f1:
with open(filename2) as f2:
if f1.read() == f2.read():
...
```
The high level way:
```
import filecmp
if filecmp.cmp(filename1, filename2, shallow=False):
...
``` |
In Python, is there a concise way of comparing whether the contents of two text files are the same? | 254,350 | 29 | 2008-10-31T17:47:39Z | 254,373 | 20 | 2008-10-31T17:56:15Z | [
"python"
] | I don't care what the differences are. I just want to know whether the contents are different. | If you're going for even basic efficiency, you probably want to check the file size first:
```
if os.path.getsize(filename1) == os.path.getsize(filename2):
if open('filename1','r').read() == open('filename2','r').read():
# Files are the same.
```
This saves you reading every line of two files that aren't even t... |
Tiny python executable? | 254,635 | 8 | 2008-10-31T19:20:30Z | 254,723 | 9 | 2008-10-31T19:51:46Z | [
"python",
"executable",
"pyinstaller"
] | I plan to use PyInstaller to create a stand-alone python executable. PythonInstaller comes with built-in support for UPX and uses it to compress the executable but they are still really huge (about 2,7 mb).
Is there any way to create even smaller Python executables? For example using a shrinked python.dll or something... | If you recompile pythonxy.dll, you can omit modules that you don't need. Going by size, stripping off the unicode database and the CJK codes creates the largest code reduction. This, of course, assumes that you don't need these. Remove the modules from the pythoncore project, and also remove them from PC/config.c |
Converting datetime to POSIX time | 255,035 | 36 | 2008-10-31T21:38:02Z | 255,053 | 44 | 2008-10-31T21:44:35Z | [
"python",
"datetime",
"posix"
] | How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way. | ```
import time, datetime
d = datetime.datetime.now()
print time.mktime(d.timetuple())
``` |
Converting datetime to POSIX time | 255,035 | 36 | 2008-10-31T21:38:02Z | 5,872,022 | 19 | 2011-05-03T15:39:15Z | [
"python",
"datetime",
"posix"
] | How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way. | For UTC calculations, `calendar.timegm` is the inverse of `time.gmtime`.
```
import calendar, datetime
d = datetime.datetime.utcnow()
print calendar.timegm(d.timetuple())
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.