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
Can I use a decorator to mutate the local scope of a function in Python?
591,200
8
2009-02-26T16:03:08Z
591,295
8
2009-02-26T16:23:43Z
[ "python", "decorator" ]
Is there any way of writing a decorator such that the following would work? ``` assert 'z' not in globals() @my_decorator def func(x, y): print z ``` --- EDIT: moved from anwser In answer to hop's "why?": syntax sugar / DRY. It's not about caching, it's about calculating z (and z1, z2, z3, ...) based upon the ...
I don't know about the local scope, but you could provide an alternative global name space temporarily. Something like: ``` import types def my_decorator(fn): def decorated(*args,**kw): my_globals={} my_globals.update(globals()) my_globals['z']='value of z' call_fn=types.FunctionTy...
Can I use a decorator to mutate the local scope of a function in Python?
591,200
8
2009-02-26T16:03:08Z
592,019
10
2009-02-26T19:20:17Z
[ "python", "decorator" ]
Is there any way of writing a decorator such that the following would work? ``` assert 'z' not in globals() @my_decorator def func(x, y): print z ``` --- EDIT: moved from anwser In answer to hop's "why?": syntax sugar / DRY. It's not about caching, it's about calculating z (and z1, z2, z3, ...) based upon the ...
Echoing Hop's answer 1. Don't do it. 2. Seriously, don't do this. Lisp and Ruby are more appropriate languages for writing your own custom syntax. Use one of those. Or find a cleaner way to do this 3. If you must, you want dynamic scoped variables, not lexically scoped. Python doesn't have dynamically scoped variable...
When using random, which form returns an equal 50% chance?
591,253
6
2009-02-26T16:15:37Z
591,294
12
2009-02-26T16:23:32Z
[ "python", "random" ]
I'm guessing that most built in random generators return something like this: ``` [0.0, 1.0) ``` so if I would like a 50% chance would I use something like this: ``` if random() < .5 ``` or something like: ``` if random() <= .5 ``` Thanks for the help.
Ah, the old ".5" problem. Here's the answer: If you're going to divide 10 things into two **equal** parts, you need 5 things in each part. 0 thru 4 in the first part, 5-9 in the second part. So... `< .5` is correct.
How can you programmatically tell the CPython interpreter to enter interactive mode when done?
591,520
8
2009-02-26T17:21:57Z
591,531
13
2009-02-26T17:25:18Z
[ "cpython", "python" ]
If you invoke the cpython interpreter with the -i option, it will enter the interactive mode upon completing any commands or scripts it has been given to run. Is there a way, within a program to get the interpreter to do this even when it has not been given -i? The obvious use case is in debugging by interactively insp...
You want the [code module](http://docs.python.org/library/code.html). ``` #!/usr/bin/env python import code code.interact("Enter Here") ```
In Python what is the preferred way to create and manage threads?
592,143
2
2009-02-26T19:54:47Z
592,170
8
2009-02-26T20:00:54Z
[ "python", "multithreading" ]
Python provides several methods to create threads. Which provides the best API and the most control? Thanks.
When necessary, the [threading](http://docs.python.org/library/threading.html) module and its high-level interface is preferred. Of course, many people suggest that it's rarely/never necessary, and threads aren't very nice to deal with. The thread module may be necessary for some weird use-case or other, but I've never...
Fast way to determine if a PID exists on (Windows)?
592,256
8
2009-02-26T20:19:23Z
592,788
8
2009-02-26T22:41:23Z
[ "python", "c", "winapi", "pid" ]
I realize "fast" is a bit subjective so I'll explain with some context. I'm working on a Python module called [**psutil**](http://code.google.com/p/psutil/) for reading process information in a cross-platform way. One of the functions is a `pid_exists(pid)` function for determining if a PID is in the current process li...
[OpenProcess](http://msdn.microsoft.com/en-us/library/ms684320%28VS.85%29.aspx) could tell you w/o enumerating all. I have no idea how fast. **EDIT**: note that you also need `GetExitCodeProcess` to verify the state of the process even if you get a handle from `OpenProcess`.
Any reasons not to use SQLObject over SQLAlchemy?
592,332
13
2009-02-26T20:37:30Z
592,348
8
2009-02-26T20:41:48Z
[ "python", "orm", "sqlalchemy", "sqlobject" ]
I don't expect to need much more than basic CRUD type functionality. I know that SQLAlchemy is more flexible, but the syntax etc of sqlobject just seem to be a bit easier to get up and going with.
I think SQLObject is more pythonic/simpler, so if it works for you, then stick with it. SQLAlchemy takes a little more to learn, but can do more advanced things if you need that.
Why doesn't Python have static variables?
592,931
42
2009-02-26T23:28:09Z
593,046
73
2009-02-27T00:04:02Z
[ "python" ]
There is a [questions asking how to simulate static variables in python](http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python). Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.) Why doesn't Python support s...
The idea behind this omission is that static variables are only useful in two situations: when you really should be using a class and when you really should be using a generator. If you want to attach stateful information to a function, what you need is a class. A trivially simple class, perhaps, but a class nonethele...
Why doesn't Python have static variables?
592,931
42
2009-02-26T23:28:09Z
593,226
19
2009-02-27T01:41:57Z
[ "python" ]
There is a [questions asking how to simulate static variables in python](http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python). Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.) Why doesn't Python support s...
One alternative to a class is a function attribute: ``` def foo(arg): if not hasattr(foo, 'cache'): foo.cache = get_data_dict() return foo.cache[arg] ``` While a class is probably cleaner, this technique can be useful and is nicer, in my opinion, then a global.
Why doesn't Python have static variables?
592,931
42
2009-02-26T23:28:09Z
623,043
8
2009-03-08T04:39:27Z
[ "python" ]
There is a [questions asking how to simulate static variables in python](http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python). Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.) Why doesn't Python support s...
In Python 3, I would use a closure: ``` def makefoo(): x = 0 def foo(): nonlocal x x += 1 return x return foo foo = makefoo() print(foo()) print(foo()) ```
Python for mathematics students?
593,685
7
2009-02-27T06:10:16Z
593,694
8
2009-02-27T06:13:05Z
[ "python", "math" ]
I need to deliver one and half hour seminar on programming for students at the department of mathematics. I have chosen python as language. 1. What should be content of my presentation ? 2. What are good resources available ? 3. What is necessity of programming for maths students? 4. How will knowledge of programming...
Do the getting started guide to scipy? [http://www.scipy.org/Getting\_Started](http://www.scipy.org/Getting%5FStarted)
Python for mathematics students?
593,685
7
2009-02-27T06:10:16Z
593,833
7
2009-02-27T07:22:18Z
[ "python", "math" ]
I need to deliver one and half hour seminar on programming for students at the department of mathematics. I have chosen python as language. 1. What should be content of my presentation ? 2. What are good resources available ? 3. What is necessity of programming for maths students? 4. How will knowledge of programming...
Sage: <http://www.sagemath.org/>
Equation parsing in Python
594,266
26
2009-02-27T10:42:07Z
594,294
9
2009-02-27T10:51:37Z
[ "python", "parsing", "equation" ]
How can I (easily) take a string such as `"sin(x)*x^2"` which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of `x`?
``` f = parser.parse('sin(x)*x^2').to_pyfunc() ``` Where `parser` could be defined using PLY, pyparsing, builtin tokenizer, parser, ast. Don't use `eval` on user input.
Equation parsing in Python
594,266
26
2009-02-27T10:42:07Z
594,360
37
2009-02-27T11:12:34Z
[ "python", "parsing", "equation" ]
How can I (easily) take a string such as `"sin(x)*x^2"` which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of `x`?
Python's own internal compiler can parse this, if you use Python notation. If your change the notation slightly, you'll be happier. ``` import compiler eq= "sin(x)*x**2" ast= compiler.parse( eq ) ``` You get an abstract syntax tree that you can work with.
Equation parsing in Python
594,266
26
2009-02-27T10:42:07Z
2,537,691
7
2010-03-29T12:11:39Z
[ "python", "parsing", "equation" ]
How can I (easily) take a string such as `"sin(x)*x^2"` which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of `x`?
pyparsing might do what you want (http://pyparsing.wikispaces.com/) especially if the strings are from an untrusted source. See also <http://pyparsing.wikispaces.com/file/view/fourFn.py> for a fairly full-featured calculator built with it.
Equation parsing in Python
594,266
26
2009-02-27T10:42:07Z
5,936,822
18
2011-05-09T12:23:11Z
[ "python", "parsing", "equation" ]
How can I (easily) take a string such as `"sin(x)*x^2"` which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of `x`?
You can use Python `parser`: ``` import parser formula = "sin(x)*x**2" code = parser.expr(formula).compile() from math import sin x = 10 print eval(code) ``` It performs better than pure `eval`.
Choosing between different switch-case replacements in Python - dictionary or if-elif-else?
594,442
15
2009-02-27T11:47:51Z
594,532
8
2009-02-27T12:21:10Z
[ "python", "switch-statement" ]
I recently read the questions that recommend against using switch-case statements in languages that do support it. As far as Python goes, I've seen a number of switch case replacements, such as: 1. Using a dictionary (Many variants) 2. Using a Tuple 3. Using a function decorator (<http://code.activestate.com/recipes/4...
In the first example I would certainly stick with the if-else statement. In fact I don't see a reason not to use if-else unless 1. You find (using e.g. the profile module) that the if statement is a bottleneck (very unlikely IMO unless you have a huge number of cases that do very little) 2. The code using a dictionary...
Choosing between different switch-case replacements in Python - dictionary or if-elif-else?
594,442
15
2009-02-27T11:47:51Z
594,622
22
2009-02-27T12:51:21Z
[ "python", "switch-statement" ]
I recently read the questions that recommend against using switch-case statements in languages that do support it. As far as Python goes, I've seen a number of switch case replacements, such as: 1. Using a dictionary (Many variants) 2. Using a Tuple 3. Using a function decorator (<http://code.activestate.com/recipes/4...
Sigh. Too much hand-wringing over the wrong part of the problem. The switch statement is not the issue. There are many ways of expressing "alternative" that don't add **meaning**. The issue is **meaning** -- not technical statement choices. There are three common patterns. * **Mapping a key to an object**. Use a dic...
Email body is a string sometimes and a list sometimes. Why?
594,545
7
2009-02-27T12:24:39Z
594,566
10
2009-02-27T12:31:24Z
[ "python", "email", "message", "payload" ]
My application is written in python. What I am doing is I am running a script on each email received by postfix and do something with the email content. Procmail is responsible for running the script taking the email as input. The problem started when I was converting the input message(may be text) to email\_message ob...
As crazy as it might seem, the reason for the sometimes string, sometimes list-semantics are [given in the documentation](http://docs.python.org/library/email.parser.html#email.message%5Ffrom%5Fstring). Basically, multipart messages are returned as lists.
Email body is a string sometimes and a list sometimes. Why?
594,545
7
2009-02-27T12:24:39Z
594,633
11
2009-02-27T12:53:42Z
[ "python", "email", "message", "payload" ]
My application is written in python. What I am doing is I am running a script on each email received by postfix and do something with the email content. Procmail is responsible for running the script taking the email as input. The problem started when I was converting the input message(may be text) to email\_message ob...
Well, the answers are correct, you should read the docs, but for an example of a generic way: ``` def get_first_text_part(msg): maintype = msg.get_content_maintype() if maintype == 'multipart': for part in msg.get_payload(): if part.get_content_maintype() == 'text': return p...
Email body is a string sometimes and a list sometimes. Why?
594,545
7
2009-02-27T12:24:39Z
3,543,831
8
2010-08-22T23:04:49Z
[ "python", "email", "message", "payload" ]
My application is written in python. What I am doing is I am running a script on each email received by postfix and do something with the email content. Procmail is responsible for running the script taking the email as input. The problem started when I was converting the input message(may be text) to email\_message ob...
Rather than simply looking for a sub-part, use walk() to iterate through the message contents ``` def walkMsg(msg): for part in msg.walk(): if part.get_content_type() == "multipart/alternative": continue yield part.get_payload(decode=1) ``` The walk() method returns an iterator that you can loop with ...
Make a python property with the same name as the class member name
594,856
5
2009-02-27T13:58:53Z
594,892
17
2009-02-27T14:09:00Z
[ "python" ]
Is it possible in python to create a property with the same name as the member variable name of the class. e.g. ``` Class X: ... self.i = 10 # marker ... property(fget = get_i, fset = set_i) ``` Please tell me how I can do so. Because if I do so, for the statement at marker I get stack overflow for th...
> Is it possible in python to create a property with the same name as the member variable name No. properties, members and methods all share the same namespace. > the statement at marker I get stack overflow Clearly. You try to set i, which calls the setter for property i, which tries to set i, which calls the sette...
How to load an RSA key from a PEM file and use it in python-crypto
595,114
8
2009-02-27T15:01:59Z
606,702
11
2009-03-03T14:57:27Z
[ "python", "cryptography" ]
I have not found a way to load an RSA private key from a PEM file to use it in python-crypto (signature). python-openssl can load a PEM file but the PKey object can't be used to retrieved key information (p, q, ...) to use with Crypto.PublicKey.construct().
I recommend M2Crypto instead of python-crypto. You will need M2Crypto to parse PEM anyway and its EVP api frees your code from depending on a particular algorithm. ``` private = """ -----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBANQNY7RD9BarYRsmMazM1hd7a+u3QeMPFZQ7Ic+BmmeWHvvVP4Yj yu1t6vAut7mKkaDeKbT3yiGVUgAEUaWMXqECAwEA...
What's the Python function like sum() but for multiplication? product()?
595,374
91
2009-02-27T16:06:36Z
595,384
16
2009-02-27T16:09:09Z
[ "python", "builtin", "pep" ]
Python's [`sum()`](http://docs.python.org/library/functions.html#sum) function returns the sum of numbers in an iterable. ``` sum([3,4,5]) == 3 + 4 + 5 == 12 ``` I'm looking for the function that returns the product instead. ``` somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60 ``` I'm pretty sure such a function exists...
``` Numeric.product ``` ( or ``` reduce(lambda x,y:x*y,[3,4,5]) ``` )
What's the Python function like sum() but for multiplication? product()?
595,374
91
2009-02-27T16:06:36Z
595,391
12
2009-02-27T16:10:46Z
[ "python", "builtin", "pep" ]
Python's [`sum()`](http://docs.python.org/library/functions.html#sum) function returns the sum of numbers in an iterable. ``` sum([3,4,5]) == 3 + 4 + 5 == 12 ``` I'm looking for the function that returns the product instead. ``` somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60 ``` I'm pretty sure such a function exists...
Use this ``` def prod( iterable ): p= 1 for n in iterable: p *= n return p ``` Since there's no built-in `prod` function.
What's the Python function like sum() but for multiplication? product()?
595,374
91
2009-02-27T16:06:36Z
595,396
38
2009-02-27T16:11:54Z
[ "python", "builtin", "pep" ]
Python's [`sum()`](http://docs.python.org/library/functions.html#sum) function returns the sum of numbers in an iterable. ``` sum([3,4,5]) == 3 + 4 + 5 == 12 ``` I'm looking for the function that returns the product instead. ``` somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60 ``` I'm pretty sure such a function exists...
There isn't one built in, but it's simple to roll your own, as demonstrated [here](http://stackoverflow.com/questions/493853/which-python-module-is-suitable-for-data-manipulation-in-a-list/494034#494034): ``` import operator def prod(factors): return reduce(operator.mul, factors, 1) ``` See answers to this questi...
What's the Python function like sum() but for multiplication? product()?
595,374
91
2009-02-27T16:06:36Z
595,409
141
2009-02-27T16:13:48Z
[ "python", "builtin", "pep" ]
Python's [`sum()`](http://docs.python.org/library/functions.html#sum) function returns the sum of numbers in an iterable. ``` sum([3,4,5]) == 3 + 4 + 5 == 12 ``` I'm looking for the function that returns the product instead. ``` somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60 ``` I'm pretty sure such a function exists...
Actually, Guido vetoed the idea: <http://bugs.python.org/issue1093> But, as noted in that issue, you can make one pretty easily: ``` from functools import reduce # Valid in Python 2.6+, required in Python 3 import operator reduce(operator.mul, (3, 4, 5), 1) ```
What's the Python function like sum() but for multiplication? product()?
595,374
91
2009-02-27T16:06:36Z
6,364,663
20
2011-06-15T21:33:14Z
[ "python", "builtin", "pep" ]
Python's [`sum()`](http://docs.python.org/library/functions.html#sum) function returns the sum of numbers in an iterable. ``` sum([3,4,5]) == 3 + 4 + 5 == 12 ``` I'm looking for the function that returns the product instead. ``` somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60 ``` I'm pretty sure such a function exists...
There's a [`prod()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.prod.html) in numpy that does what you're asking for.
How do I use python for web development without relying on a framework?
596,729
28
2009-02-27T21:20:50Z
596,807
36
2009-02-27T21:45:58Z
[ "python", "performance", "web.py" ]
I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing *python*. The only thing I have found so far that lets me do this in the most obvious way possible is [web.py](http://webpy.org/) but ...
The way to go is [wsgi](http://wsgi.org). WSGI is the **Web Server Gateway Interface**. It is a specification for web servers and application servers to communicate with web applications (though it can also be used for more than that). **It is a Python standard, described in detail in [PEP 333](http://www.python.org/d...
How do I use python for web development without relying on a framework?
596,729
28
2009-02-27T21:20:50Z
596,811
9
2009-02-27T21:46:50Z
[ "python", "performance", "web.py" ]
I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing *python*. The only thing I have found so far that lets me do this in the most obvious way possible is [web.py](http://webpy.org/) but ...
You could also check [cherrypy](http://cherrypy.org). The focus of cherrypy is in being a framework that lets you write python. Cherrypy has its own pretty good webserver, but it is wsgi-compatible so you can run cherrypy applications in apache via mod\_wsgi. Here is hello world in cherrypy: ``` import cherrypy class...
How do I use python for web development without relying on a framework?
596,729
28
2009-02-27T21:20:50Z
596,877
18
2009-02-27T22:11:40Z
[ "python", "performance", "web.py" ]
I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing *python*. The only thing I have found so far that lets me do this in the most obvious way possible is [web.py](http://webpy.org/) but ...
It's hilarious how, even prompted with a question asking how to write without a framework, everyone still piles in to promote their favourite framework. The OP whinges about not wanting a “heavyweight framework”, and the replies mention *Twisted*, of all things?! Come now, really. Yes, it *is* perfectly possible t...
How do I use python for web development without relying on a framework?
596,729
28
2009-02-27T21:20:50Z
596,910
8
2009-02-27T22:23:49Z
[ "python", "performance", "web.py" ]
I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing *python*. The only thing I have found so far that lets me do this in the most obvious way possible is [web.py](http://webpy.org/) but ...
+1 to all the answers with WSGI. Eric Florenzo wrote a great blog post lately you should read: [Writing Blazing Fast, Infinitely Scalable, Pure-WSGI Utilities](http://www.eflorenzano.com/blog/post/writing-blazing-fast-infinitely-scalable-pure-wsgi/). This will give you a better idea of pure WSGI beyond Hello World. Al...
xml.dom.minidom: Getting CDATA values
597,058
10
2009-02-27T23:20:56Z
597,107
21
2009-02-27T23:40:50Z
[ "python", "xml" ]
I'm able to get the value in the image tag (see XML below), but not the Category tag. The difference is one is a CDATA section and the other is just a string. Any help would be appreciated. ``` from xml.dom import minidom xml = """<?xml version="1.0" ?> <ProductData> <ITEM Id="0471195"> <Category> ...
> p.getElementsByTagName('Category')[0].firstChild minidom does not flatten away <![CDATA[ sections to plain text, it leaves them as DOM CDATASection nodes. (Arguably it should, at least optionally. DOM Level 3 LS defaults to flattening them, for what it's worth, but minidom is much older than DOM L3.) So the firstCh...
Converting an object into a subclass in Python?
597,199
14
2009-02-28T00:34:11Z
597,243
11
2009-02-28T00:57:05Z
[ "python" ]
Lets say I have a library function that I cannot change that produces an object of class A, and I have created a class B that inherits from A. What is the most straightforward way of using the library function to produce an object of class B? edit- I was asked in a comment for more detail, so here goes: PyTables is ...
Since the library function returns an A, you can't make it return a B without changing it. One thing you can do is write a function to take the fields of the A instance and copy them over into a new B instance: ``` class A: # defined by the library def __init__(self, field): self.field = field class B(A)...
Converting an object into a subclass in Python?
597,199
14
2009-02-28T00:34:11Z
597,324
13
2009-02-28T01:40:07Z
[ "python" ]
Lets say I have a library function that I cannot change that produces an object of class A, and I have created a class B that inherits from A. What is the most straightforward way of using the library function to produce an object of class B? edit- I was asked in a comment for more detail, so here goes: PyTables is ...
This can be done if the initializer of the subclass can handle it, or you write an explicit upgrader. Here is an example: ``` class A(object): def __init__(self): self.x = 1 class B(A): def __init__(self): super(B, self).__init__() self._init_B() def _init_B(self): self.x +...
How to create MS Paint clone with Python and pygame
597,369
9
2009-02-28T02:13:08Z
597,401
11
2009-02-28T02:50:16Z
[ "python", "mouse", "pygame", "draw", "paint" ]
As I see it, there are two ways to handle mouse events to draw a picture. The first is to detect when the mouse moves and draw a line to where the mouse is, shown [here](http://www.cs.iupui.edu/~aharris/pygame/ch05/paint.py). However, the problem with this is that with a large brush size, many gaps appear between each...
Why not do both? Draw a circle at each endpoint and a line between the two. **EDIT** rofl, just couldn't stop myself. Actually, you don't want to use pygame.draw.line because it cheats. It fills a 1 pixel wide row or column (depending on angle of attack) of pixels. If you do go at a roughly perpendicular angle, 0 de...
How to concisely cascade through multiple regex statements in Python
597,476
6
2009-02-28T04:06:31Z
597,493
21
2009-02-28T04:31:57Z
[ "python", "regex", "coding-style" ]
My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth. I could do something like this: ``` if ...
Generally speaking, in these sorts of situations, you want to make the code "data driven". That is, put the important information in a container, and loop through it. In your case, the important information is (string, function) pairs. ``` import re def fun1(): print('fun1') def fun2(): print('fun2') def f...
Why does @foo.setter in Python not work for me?
598,077
102
2009-02-28T14:33:50Z
598,090
22
2009-02-28T14:43:22Z
[ "python", "decorator", "new-style-class" ]
So, I'm playing with decorators in Python 2.6, and I'm having some trouble getting them to work. Here is my class file: ``` class testDec: @property def x(self): print 'called getter' return self._x @x.setter def x(self, value): print 'called setter' self._x = value ...
You need to use new-style classes which you do by deriving your class from object: ``` class testDec(object): .... ``` Then it should work.
Why does @foo.setter in Python not work for me?
598,077
102
2009-02-28T14:33:50Z
598,092
213
2009-02-28T14:43:40Z
[ "python", "decorator", "new-style-class" ]
So, I'm playing with decorators in Python 2.6, and I'm having some trouble getting them to work. Here is my class file: ``` class testDec: @property def x(self): print 'called getter' return self._x @x.setter def x(self, value): print 'called setter' self._x = value ...
You seem to be using [classic old-style classes](https://docs.python.org/2/glossary.html#term-classic-class). In order for [properties](https://docs.python.org/2/library/functions.html#property) to work correctly you need to use [new-style classes](https://docs.python.org/2/glossary.html#term-new-style-class) instead (...
Why does @foo.setter in Python not work for me?
598,077
102
2009-02-28T14:33:50Z
17,395,735
34
2013-06-30T23:20:33Z
[ "python", "decorator", "new-style-class" ]
So, I'm playing with decorators in Python 2.6, and I'm having some trouble getting them to work. Here is my class file: ``` class testDec: @property def x(self): print 'called getter' return self._x @x.setter def x(self, value): print 'called setter' self._x = value ...
Just a note for other people who stumble here looking for this exception: both functions need to have the same name. Naming the methods as follows will result in an exception: ``` @property def x(self): pass @x.setter def x_setter(self, value): pass ``` Instead give both methods the same name ``` @property def x(se...
Cheap exception handling in Python?
598,157
22
2009-02-28T15:30:19Z
598,168
24
2009-02-28T15:40:15Z
[ "python", "performance", "exception-handling" ]
I read in an earlier [answer](http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731) that exception handling is cheap in Python so we shouldn't do pre-conditional checking. I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a st...
You might find this post helpful: [**Try / Except Performance in Python: A Simple Test**](http://paltman.com/2008/jan/18/try-except-performance-in-python-a-simple-test/) where Patrick Altman did some simple testing to see what the performance is in various scenarios pre-conditional checking (specific to dictionary keys...
Cheap exception handling in Python?
598,157
22
2009-02-28T15:30:19Z
598,219
8
2009-02-28T16:04:16Z
[ "python", "performance", "exception-handling" ]
I read in an earlier [answer](http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731) that exception handling is cheap in Python so we shouldn't do pre-conditional checking. I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a st...
With Python, it is easy to check different possibilities for speed - get to know the [timeit module](http://docs.python.org/library/timeit.html#module-timeit) : > ... example session (using the command line) that compare the cost of using hasattr() vs. try/except to test for missing and present object attributes. ```...
Cheap exception handling in Python?
598,157
22
2009-02-28T15:30:19Z
598,221
33
2009-02-28T16:05:27Z
[ "python", "performance", "exception-handling" ]
I read in an earlier [answer](http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731) that exception handling is cheap in Python so we shouldn't do pre-conditional checking. I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a st...
Don't sweat the small stuff. You've already picked one of the slower scripting languages out there, so trying to optimize down to the opcode is not going to help you much. The reason to choose an interpreted, dynamic language like Python is to optimize your time, not the CPU's. If you use common language idioms, then ...
Cheap exception handling in Python?
598,157
22
2009-02-28T15:30:19Z
598,227
9
2009-02-28T16:07:32Z
[ "python", "performance", "exception-handling" ]
I read in an earlier [answer](http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731) that exception handling is cheap in Python so we shouldn't do pre-conditional checking. I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a st...
"Can someone explain this to me?" Depends. Here's one explanation, but it's not helpful. Your question stems from your assumptions. Since the real world conflicts with your assumptions, it must mean your assumptions are wrong. Not much of an explanation, but that's why you're asking. "Exception handling means a dyna...
Cheap exception handling in Python?
598,157
22
2009-02-28T15:30:19Z
598,559
20
2009-02-28T19:50:34Z
[ "python", "performance", "exception-handling" ]
I read in an earlier [answer](http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731) that exception handling is cheap in Python so we shouldn't do pre-conditional checking. I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a st...
Putting aside the performance measurements that others have said, the guiding principle is often structured as "it is easier to ask forgiveness than ask permission" vs. "look before you leap." Consider these two snippets: ``` # Look before you leap if not os.path.exists(filename): raise SomeError("Cannot open con...
When is it (not) appropriate to bundle dependencies with an application?
598,299
12
2009-02-28T16:59:37Z
598,397
8
2009-02-28T18:03:58Z
[ "python", "dependencies", "distribution", "packaging" ]
**Summary** I recently had a conversation with the creator of a framework that one of my applications depends on. During that conversation he mentioned as a sort of aside that it would make my life simpler if I just bundled his framework with my application and delivered to the end user a version that I knew was consi...
I favor bundling dependencies, *if* it's not feasible to use a system for automatic dependency resolution (i.e. setuptools), and *if* you can do it without introducing version conflicts. You still have to consider your application and your audience; serious developers or enthusiasts are more likely to want to work with...
Searching a list of objects in Python
598,398
32
2009-02-28T18:06:20Z
598,407
45
2009-02-28T18:11:05Z
[ "python" ]
Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do. For instance: ``` class Data: pass myList = []...
You can get a list of *all* matching elements with a list comprehension: ``` [x for x in myList if x.n == 30] # list of all elements with .n==30 ``` If you simply want to determine if the list contains *any* element that matches and do it (relatively) efficiently, you can do ``` def contains(list, filter): for ...
Searching a list of objects in Python
598,398
32
2009-02-28T18:06:20Z
598,415
20
2009-02-28T18:19:28Z
[ "python" ]
Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do. For instance: ``` class Data: pass myList = []...
``` [x for x in myList if x.n == 30] # list of all matches any(x.n == 30 for x in myList) # if there is any matches [i for i,x in enumerate(myList) if x.n == 30] # indices of all matches def first(iterable, default=None): for item in iterable: return item return default first(x ...
Searching a list of objects in Python
598,398
32
2009-02-28T18:06:20Z
598,417
32
2009-02-28T18:20:01Z
[ "python" ]
Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do. For instance: ``` class Data: pass myList = []...
Just for completeness, let's not forget the Simplest Thing That Could Possibly Work: ``` for i in list: if i.n == 5: # do something with it print "YAY! Found one!" ```
Searching a list of objects in Python
598,398
32
2009-02-28T18:06:20Z
598,424
18
2009-02-28T18:22:06Z
[ "python" ]
Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do. For instance: ``` class Data: pass myList = []...
``` filter(lambda x: x.n == 5, myList) ```
Searching a list of objects in Python
598,398
32
2009-02-28T18:06:20Z
598,427
7
2009-02-28T18:23:29Z
[ "python" ]
Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do. For instance: ``` class Data: pass myList = []...
You can use `in` to look for an item in a collection, and a list comprehension to extract the field you are interested in. This (works for lists, sets, tuples, and anything that defines `__contains__` or `__getitem__`). ``` if 5 in [data.n for data in myList]: print "Found it" ``` See also: * [Contains Method](h...
Searching a list of objects in Python
598,398
32
2009-02-28T18:06:20Z
598,602
31
2009-02-28T20:15:28Z
[ "python" ]
Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do. For instance: ``` class Data: pass myList = []...
**Simple, Elegant, and Powerful:** A generator expression in conjuction with a builtin… (python 2.5+) ``` any(x for x in mylist if x.n == 10) ``` Uses the Python [`any()`](http://docs.python.org/2/library/functions.html#any) builtin, which is defined as follows: > **any(iterable)** `->` > Return True if any eleme...
What SHOULDN'T Django's admin interface be used for?
598,577
4
2009-02-28T20:00:03Z
598,580
7
2009-02-28T20:03:46Z
[ "python", "django", "administration" ]
I've been applying Django's automatic administration capabilities to some applications who had previously been very difficult to administer. I'm thinking of a lot of ways to apply it to other applications we use (including using it to replace some internal apps altogether). Before I go overboard though, is there anythi...
User-specific privileges. I myself had been trying to work it into that-- some of the new (and at least at the time, undocumented) features (from newforms-admin) make it actually possible. Depending on how fine you want the control to be, though, you can end up getting very, very deep into the Django/admin internals. J...
AppEngine: Query datastore for records with <missing> value
598,605
20
2009-02-28T20:16:28Z
598,975
30
2009-03-01T00:26:57Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
I created a new property for my db model in the Google App Engine Datastore. Old: ``` class Logo(db.Model): name = db.StringProperty() image = db.BlobProperty() ``` New: ``` class Logo(db.Model): name = db.StringProperty() image = db.BlobProperty() is_approved = db.BooleanProperty(default=False) ``` How ...
According to the App Engine documentation on [Queries and Indexes](http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html#Introducing%5FIndexes), there is a distinction between entities that have *no* value for a property, and those that have a *null* value for it; and "Entities Without a Filtere...
External classes in Python
598,668
4
2009-02-28T20:54:02Z
598,686
12
2009-02-28T21:03:54Z
[ "python", "python-module", "python-import" ]
I'm just beginning Python, and I'd like to use an external RSS class. Where do I put that class and how do I import it? I'd like to eventually be able to share python programs.
**About the `import` statement:** (a good writeup is at <http://effbot.org/zone/import-confusion.htm> and the python tutorial goes into detail at <http://docs.python.org/tutorial/modules.html> ) There are two normal ways to import code into a python program. 1. Modules 2. Packages A module is **simply** a file that...
How to match a text node then follow parent nodes using XPath
598,722
14
2009-02-28T21:33:20Z
598,732
22
2009-02-28T21:40:19Z
[ "python", "html", "xpath", "lxml" ]
I'm trying to parse some HTML with XPath. Following the simplified XML example below, I want to match the string 'Text 1', then grab the contents of the relevant `content` node. ``` <doc> <block> <title>Text 1</title> <content>Stuff I want</content> </block> <block> <title>Text 2</...
Do you want that? ``` //title[text()='Text 1']/../content/text() ```
How to match a text node then follow parent nodes using XPath
598,722
14
2009-02-28T21:33:20Z
599,061
15
2009-03-01T01:37:19Z
[ "python", "html", "xpath", "lxml" ]
I'm trying to parse some HTML with XPath. Following the simplified XML example below, I want to match the string 'Text 1', then grab the contents of the relevant `content` node. ``` <doc> <block> <title>Text 1</title> <content>Stuff I want</content> </block> <block> <title>Text 2</...
**Use**: ``` string(/*/*/title[. = 'Text 1']/following-sibling::content) ``` **This represents at least two improvements** as compared to the currently accepted solution of Johannes Weiß: 1. **The very expensive abbreviation "//"** (usually causing the whole XML document to be scanned) **is avoided** as it should b...
Python HTML removal
598,817
6
2009-02-28T22:39:55Z
598,824
7
2009-02-28T22:43:17Z
[ "python", "string" ]
How can I remove all HTML from a string in Python? For example, how can I turn: ``` blah blah <a href="blah">link</a> ``` into ``` blah blah link ``` Thanks!
You can use a regular expression to remove all the tags: ``` >>> import re >>> s = 'blah blah <a href="blah">link</a>' >>> re.sub('<[^>]*>', '', s) 'blah blah link' ```
Python HTML removal
598,817
6
2009-02-28T22:39:55Z
599,080
18
2009-03-01T02:00:18Z
[ "python", "string" ]
How can I remove all HTML from a string in Python? For example, how can I turn: ``` blah blah <a href="blah">link</a> ``` into ``` blah blah link ``` Thanks!
When your regular expression solution hits a wall, try this super easy (and reliable) [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) program. ``` from BeautifulSoup import BeautifulSoup html = "<a> Keep me </a>" soup = BeautifulSoup(html) text_parts = soup.findAll(text=True) text = ''.join(text_parts...
Python HTML removal
598,817
6
2009-02-28T22:39:55Z
599,924
10
2009-03-01T14:45:46Z
[ "python", "string" ]
How can I remove all HTML from a string in Python? For example, how can I turn: ``` blah blah <a href="blah">link</a> ``` into ``` blah blah link ``` Thanks!
There is also a small library called [stripogram](http://pypi.python.org/pypi/stripogram) which can be used to strip away some or all HTML tags. You can use it like this: ``` from stripogram import html2text, html2safehtml # Only allow <b>, <a>, <i>, <br>, and <p> tags clean_html = html2safehtml(original_html,valid_t...
How to pass information using an HTTP redirect (in Django)
599,280
19
2009-03-01T05:02:13Z
599,704
11
2009-03-01T11:56:07Z
[ "python", "django", "http" ]
I have a view that accepts a form submission and updates a model. After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page. How can I "pass" this message to the other page? HttpResponseRedirect only accepts a [URL](http://en.wikip...
This is a built-in feature of Django, called "messages" See <http://docs.djangoproject.com/en/dev/topics/auth/#messages> From the documentation: > A message is associated with a User. > There's no concept of expiration or > timestamps. > > Messages are used by the Django admin > after successful actions. For example...
How to pass information using an HTTP redirect (in Django)
599,280
19
2009-03-01T05:02:13Z
600,593
8
2009-03-01T21:41:14Z
[ "python", "django", "http" ]
I have a view that accepts a form submission and updates a model. After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page. How can I "pass" this message to the other page? HttpResponseRedirect only accepts a [URL](http://en.wikip...
You can use django-flashcookie app <http://bitbucket.org/offline/django-flashcookie/wiki/Home> it can send multiple messages and have unlimited types of messages. Lets say you want one message type for warning and one for error messages, you can write ``` def simple_action(request): ... request.flash['notice'...
Why doesn't the weakref work on this bound method?
599,430
8
2009-03-01T07:23:20Z
599,486
9
2009-03-01T08:16:06Z
[ "python", "weak-references" ]
I have a project where i'm trying to use weakrefs with callbacks, and I don't understand what I'm doing wrong. I have created simplified test that shows the exact behavior i'm confused with. Why is it that in this test test\_a works as expected, but the weakref for self.MyCallbackB disappears between the class initial...
You want a [WeakMethod](http://code.activestate.com/recipes/81253/). An explanation why your solution doesn't work can be found in the discussion of the recipe: > Normal weakref.refs to bound methods don't quite work the way one expects, because bound methods are first-class objects; **weakrefs to bound methods are d...
How do I tell a file from directory in Python?
599,474
7
2009-03-01T08:11:13Z
599,481
14
2009-03-01T08:14:03Z
[ "python", "file", "directory" ]
When using os.listdir method I need to tell which item in the resulting list is a directory or just a file. I've faced a problem when I had to go through all the directories in this list, and then add a file in every single directory. Is there a way to go through this list and remove all files from it? If it isn't po...
Use `os.path.isdir` to filter out the directories. Possibly something like ``` dirs = filter(os.path.isdir, os.listdir('/path')) for dir in dirs: # add your file ```
How do I tell a file from directory in Python?
599,474
7
2009-03-01T08:11:13Z
599,650
7
2009-03-01T11:18:53Z
[ "python", "file", "directory" ]
When using os.listdir method I need to tell which item in the resulting list is a directory or just a file. I've faced a problem when I had to go through all the directories in this list, and then add a file in every single directory. Is there a way to go through this list and remove all files from it? If it isn't po...
This might be faster: ``` current, dirs, files = os.walk('/path').next() ``` The list of directories will be in the `dirs` variable.
Python string prints as [u'String']
599,625
59
2009-03-01T10:48:45Z
599,653
53
2009-03-01T11:22:11Z
[ "python", "unicode", "ascii" ]
This will surely be an easy one but it is really bugging me. I have a script that reads in a webpage and uses [Beautiful Soup](https://www.crummy.com/software/BeautifulSoup/) to parse it. From the *soup* I extract all the links as my final goal is to print out the link.contents. All of the text that I am parsing is A...
`[u'ABC']` would be a one-element list of unicode strings. [Beautiful Soup always produces Unicode](http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit). So you need to convert the list to a single unicode string, and then convert that to ASCII. I don't kn...
Python string prints as [u'String']
599,625
59
2009-03-01T10:48:45Z
599,681
13
2009-03-01T11:40:24Z
[ "python", "unicode", "ascii" ]
This will surely be an easy one but it is really bugging me. I have a script that reads in a webpage and uses [Beautiful Soup](https://www.crummy.com/software/BeautifulSoup/) to parse it. From the *soup* I extract all the links as my final goal is to print out the link.contents. All of the text that I am parsing is A...
You probably have a list containing one unicode string. The `repr` of this is `[u'String']`. You can convert this to a list of byte strings using any variation of the following: ``` # Functional style. print map(lambda x: x.encode('ascii'), my_list) # List comprehension. print [x.encode('ascii') for x in my_list] #...
How to remove the left part of a string?
599,953
63
2009-03-01T15:19:38Z
599,962
97
2009-03-01T15:26:56Z
[ "python", "string" ]
I have some simple python code that searches files for a string e.g. `path=c:\path`, whereby the `c:\path` may vary. The current code is: ``` def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line conten...
If the string is fixed you can simply use: ``` if line.startswith("Path="): return line[5:] ``` which gives you everything from position 5 on in the string (a string is also a sequence so these sequence operators work here, too). Or you can split the line at the first `=`: ``` if "=" in line: param, value =...
How to remove the left part of a string?
599,953
63
2009-03-01T15:19:38Z
599,979
15
2009-03-01T15:43:50Z
[ "python", "string" ]
I have some simple python code that searches files for a string e.g. `path=c:\path`, whereby the `c:\path` may vary. The current code is: ``` def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line conten...
For slicing (conditional or non-conditional) in general I prefer what a colleague suggested recently; Use replacement with an empty string. Easier to read the code, less code (sometimes) and less risk of specifying the wrong number of characters. Ok; I do not use Python, but in other languages I do prefer this approach...
How to remove the left part of a string?
599,953
63
2009-03-01T15:19:38Z
600,195
80
2009-03-01T18:03:24Z
[ "python", "string" ]
I have some simple python code that searches files for a string e.g. `path=c:\path`, whereby the `c:\path` may vary. The current code is: ``` def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line conten...
### Remove prefix from a string ``` # ... if line.startswith(prefix): return line[len(prefix):] ``` ### Split on the first occurrence of the separator via `str.partition()` ``` def findvar(filename, varname="Path", sep="=") : for line in open(filename): if line.startswith(varname + sep): he...
How to remove the left part of a string?
599,953
63
2009-03-01T15:19:38Z
5,293,388
7
2011-03-13T23:58:33Z
[ "python", "string" ]
I have some simple python code that searches files for a string e.g. `path=c:\path`, whereby the `c:\path` may vary. The current code is: ``` def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line conten...
I prefer the looks of pop to indexing: ``` value = line.split("Path=").pop() ``` to ``` value = line.split("Path=")[1] param, value = line.split("Path=") ```
How to remove the left part of a string?
599,953
63
2009-03-01T15:19:38Z
7,440,332
7
2011-09-16T04:59:30Z
[ "python", "string" ]
I have some simple python code that searches files for a string e.g. `path=c:\path`, whereby the `c:\path` may vary. The current code is: ``` def findPath( i_file) : lines = open( i_file ).readlines() for line in lines : if line.startswith( "Path=" ) : return # what to do here in order to get line conten...
``` def removePrefix(text, prefix): return text[len(prefix):] if text.startswith(prefix) else text ``` Couldn't resist doing this in one line. Requires Python 2.5+.
Python: Choosing between modules and classes
600,190
8
2009-03-01T18:00:39Z
600,201
13
2009-03-01T18:06:47Z
[ "python", "design" ]
In my application I have to maintain some global application state and global application wide methods like currently connected users, total number of answers, create an application config file etc. There are two options: 1. Make a separate appstate.py file with global variables with functions over them. It looks fine...
Sounds like the classic conundrum :-) In Python, there's nothing dirty or shameful about choosing to use a module if that's the best approach. After all, modules, functions, and the like are, in fact, first-class citizens in the language, and offer introspection and other properties that many other languages use object...
mkdir -p functionality in Python
600,268
441
2009-03-01T18:49:39Z
600,612
635
2009-03-01T21:51:46Z
[ "python", "mkdir" ]
Is there a way to get functionality similar to `mkdir -p` on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?
`mkdir -p` functionality as follows: ``` import errno import os def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise ``` ### Update For Python ≥ 3.2, `os.m...
mkdir -p functionality in Python
600,268
441
2009-03-01T18:49:39Z
600,879
11
2009-03-02T00:09:10Z
[ "python", "mkdir" ]
Is there a way to get functionality similar to `mkdir -p` on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?
`mkdir -p` gives you an error if you the file already exists: ``` $ touch /tmp/foo $ mkdir -p /tmp/foo mkdir: cannot create directory `/tmp/foo': File exists ``` So a refinement to the previous suggestions would be to re-`raise` the exception if `os.path.isdir` returns `False` (when checking for `errno.EEXIST`). (Up...
mkdir -p functionality in Python
600,268
441
2009-03-01T18:49:39Z
600,940
113
2009-03-02T00:48:58Z
[ "python", "mkdir" ]
Is there a way to get functionality similar to `mkdir -p` on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?
This is easier than trapping the exception: ``` import os if not os.path.exists(...): os.makedirs(...) ``` **Disclaimer** This approach requires two system calls which is more susceptible to race conditions under certain environments/conditions. If you're writing something more sophisticated than a simple throwaw...
mkdir -p functionality in Python
600,268
441
2009-03-01T18:49:39Z
11,101,867
95
2012-06-19T13:21:48Z
[ "python", "mkdir" ]
Is there a way to get functionality similar to `mkdir -p` on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?
In Python >=3.2, that's ``` os.makedirs(path, exist_ok=True) ``` In earlier versions, use [@tzot's answer](http://stackoverflow.com/a/600612/11343).
mkdir -p functionality in Python
600,268
441
2009-03-01T18:49:39Z
11,860,637
9
2012-08-08T08:31:24Z
[ "python", "mkdir" ]
Is there a way to get functionality similar to `mkdir -p` on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?
As mentioned in the other solutions, we want to be able to hit the file system once while mimicking the behaviour of `mkdir -p`. I don't think that this is possible to do, but we should get as close as possible. Code first, explanation later: ``` import os import errno def mkdir_p(path): """ 'mkdir -p' in Python...
mkdir -p functionality in Python
600,268
441
2009-03-01T18:49:39Z
14,347,436
30
2013-01-15T21:39:43Z
[ "python", "mkdir" ]
Is there a way to get functionality similar to `mkdir -p` on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?
Recently, I found this [distutils.dir\_util.mkpath](http://docs.python.org/2/distutils/apiref.html#distutils.dir_util.mkpath): ``` In [17]: from distutils.dir_util import mkpath In [18]: mkpath('./foo/bar') Out[18]: ['foo', 'foo/bar'] ```
Python error when using urllib.open
600,389
21
2009-03-01T19:56:54Z
600,394
50
2009-03-01T20:00:08Z
[ "python", "urllib" ]
When I run this: ``` import urllib feed = urllib.urlopen("http://www.yahoo.com") print feed ``` I get this output in the interactive window (PythonWin): ``` <addinfourl at 48213968 whose fp = <socket._fileobject object at 0x02E14070>> ``` I'm expecting to get the source of the above URL. I know this has worked on...
Try this: `print feed.read()` See Python docs [here](http://docs.python.org/library/urllib.html).
Python error when using urllib.open
600,389
21
2009-03-01T19:56:54Z
600,396
15
2009-03-01T20:00:35Z
[ "python", "urllib" ]
When I run this: ``` import urllib feed = urllib.urlopen("http://www.yahoo.com") print feed ``` I get this output in the interactive window (PythonWin): ``` <addinfourl at 48213968 whose fp = <socket._fileobject object at 0x02E14070>> ``` I'm expecting to get the source of the above URL. I know this has worked on...
urllib.urlopen actually returns a file-like object so to retrieve the contents you will need to use: ``` import urllib feed = urllib.urlopen("http://www.yahoo.com") print feed.read() ```
What features would a *perfect* Python debugger have?
600,401
3
2009-03-01T20:04:20Z
600,489
7
2009-03-01T20:50:13Z
[ "python", "ide", "debugging" ]
Please tell me which features you wish your current Python debugger had. I'm creating a new Python IDE/debugger and am looking forward to challenging requests!
I use [winpdb](http://winpdb.org/) and I like it very much. I think a new debugger would need to have at least its features. It has some GUI nuisiances though, so maybe you fix it or take some ideas from it to write your own. [Winpdb](http://winpdb.org/) is a **platform independent** graphical GPL Python debugger with...
Why does Google Search return HTTP Error 403?
600,536
16
2009-03-01T21:16:25Z
600,551
23
2009-03-01T21:22:09Z
[ "python", "google-search" ]
Consider the following Python code: ``` 30 url = "http://www.google.com/search?hl=en&safe=off&q=Monkey" 31 url_object = urllib.request.urlopen(url); 32 print(url_object.read()); ``` When this is run, an Exception is thrown: ``` File "/usr/local/lib/python3.0/urllib/request.py", line 485, in http_error_de...
If you want to do Google searches "properly" through a programming interface, take a look at [Google APIs](http://code.google.com/more/). Not only are these the official way of searching Google, they are also not likely to change if Google changes their result page layout.
Why does Google Search return HTTP Error 403?
600,536
16
2009-03-01T21:16:25Z
854,782
21
2009-05-12T20:46:05Z
[ "python", "google-search" ]
Consider the following Python code: ``` 30 url = "http://www.google.com/search?hl=en&safe=off&q=Monkey" 31 url_object = urllib.request.urlopen(url); 32 print(url_object.read()); ``` When this is run, an Exception is thrown: ``` File "/usr/local/lib/python3.0/urllib/request.py", line 485, in http_error_de...
this should do the trick ``` user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7' url = "http://www.google.com/search?hl=en&safe=off&q=Monkey" headers={'User-Agent':user_agent,} request=urllib2.Request(url,None,headers) //The assembled request response = urllib2....
BOO Vs IronPython
600,539
16
2009-03-01T21:17:30Z
600,552
11
2009-03-01T21:22:36Z
[ "python", "clr", "ironpython", "boo" ]
What is the difference between [IronPython](http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython) and [BOO](http://boo.codehaus.org/)? Is there a need for 2 Python-like languages?
IronPython is a python implementation wheras Boo is another language with a python-esque syntax. One major difference is that Boo is statically typed by default. I'm sure there are more differences, I've only looked at Boo briefly, but I've been meaning to look at bit deeper (so many languages so little time!). Here ...
BOO Vs IronPython
600,539
16
2009-03-01T21:17:30Z
601,106
18
2009-03-02T02:41:34Z
[ "python", "clr", "ironpython", "boo" ]
What is the difference between [IronPython](http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython) and [BOO](http://boo.codehaus.org/)? Is there a need for 2 Python-like languages?
[IronPython](http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython) is designed to be a faithful implementation of Python on the .NET platform. Version 1 targets Python 2.4 for compatibility, and version 2 targets version 2.5 (although most of the Python standard library modules implemented in C aren't supporte...
VIM: Save and Run at the same time?
601,039
23
2009-03-02T01:54:29Z
601,084
20
2009-03-02T02:27:33Z
[ "python", "vim" ]
I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command. Thanks for your help.
**Option 1:** Write a function similar to this and place it in your startup settings: ``` function myex() execute ':w' execute ':!!' endfunction ``` You could even map a key combo to it-- look a the docs. --- **Option 2 (better):** Look at the documentation for remapping keystrokes - you may be able to acco...
VIM: Save and Run at the same time?
601,039
23
2009-03-02T01:54:29Z
602,315
9
2009-03-02T13:15:39Z
[ "python", "vim" ]
I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command. Thanks for your help.
Use the [autowrite](http://vimdoc.sourceforge.net/htmldoc/options.html#%27autowrite%27) option: ``` :set autowrite ``` > Write the contents of the file, if it has been modified, on each :next, :rewind, :last, :first, :previous, :stop, :suspend, :tag, **:!**, :make, CTRL-] and CTRL-^ command [...]
VIM: Save and Run at the same time?
601,039
23
2009-03-02T01:54:29Z
619,380
34
2009-03-06T16:10:53Z
[ "python", "vim" ]
I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command. Thanks for your help.
Okay, the simplest form of what you're looking for is the pipe command. It allows you to run multiple cmdline commands on the same line. In your case, the two commands are write \`w\` and execute current file \`! %:p\`. If you have a specific command you run for you current file, the second command becomes, e.g. \`!pyt...
Recommendations for Python development on a Mac?
601,236
8
2009-03-02T04:04:06Z
601,252
9
2009-03-02T04:15:18Z
[ "python", "osx" ]
I bought a low-end MacBook about a month ago and am finally getting around to configuring it for Python. I've done most of my Python work in Windows up until now, and am finding the choices for OS X a little daunting. It looks like there are at least five options to use for Python development: * "Stock" Apple Python *...
One advantage I see in using the "stock" Python that's included with Mac OS X is that it makes deployment to other Macs a piece of cake. I don't know what your deployment scenario is, but for me this is important. My code has to run on any number of Macs at work, and I try to minimize the amount of work it takes to run...
Best way to create a NumPy array from a dictionary?
601,477
8
2009-03-02T06:57:43Z
601,582
8
2009-03-02T08:02:56Z
[ "python", "numpy" ]
I'm just starting with NumPy so I may be missing some core concepts... What's the best way to create a NumPy array from a dictionary whose values are lists? Something like this: ``` d = { 1: [10,20,30] , 2: [50,60], 3: [100,200,300,400,500] } ``` Should turn into something like: ``` data = [ [10,20,30,?,?], [5...
You don't need to create numpy arrays to call numpy.std(). You can call numpy.std() in a loop over all the values of your dictionary. The list will be converted to a numpy array on the fly to compute the standard variation. The downside of this method is that the main loop will be in python and not in C. But I guess t...
Python Table engine binding for Tokyo Cabinet
601,865
12
2009-03-02T10:18:23Z
897,843
7
2009-05-22T13:25:52Z
[ "python", "tokyo-cabinet" ]
I am looking for python bindings for Table engine of Tokyo cabinet. I tried [Pytc](http://pypi.python.org/pypi/pytc) but can only find Hash and B-tree engine support. Is there any other bindings available?
Here is an implementation of search of table engine using PyTyrant: <http://github.com/ericflo/pytyrant/tree/master>
How to write meaningful docstrings?
601,900
23
2009-03-02T10:39:52Z
601,991
12
2009-03-02T11:25:15Z
[ "python", "comments", "docstring" ]
What, in Your opinion is a meaningful docstring? What do You expect to be described there? For example, consider this Python class's `__init__`: ``` def __init__(self, name, value, displayName=None, matchingRule="strict"): """ name - field name value - field value displayName - nice display name, if e...
I agree with "Anything that you can't tell from the method's signature". It might also mean to explain what a method/function returns. You might also want to use [Sphinx](http://sphinx.pocoo.org/) (and reStructuredText syntax) for documentation purposes inside your docstrings. That way you can include this in your doc...
How to write meaningful docstrings?
601,900
23
2009-03-02T10:39:52Z
602,224
8
2009-03-02T12:51:32Z
[ "python", "comments", "docstring" ]
What, in Your opinion is a meaningful docstring? What do You expect to be described there? For example, consider this Python class's `__init__`: ``` def __init__(self, name, value, displayName=None, matchingRule="strict"): """ name - field name value - field value displayName - nice display name, if e...
From [PEP 8](http://www.python.org/dev/peps/pep-0008/): > Conventions for writing good documentation strings (a.k.a. > "docstrings") are immortalized in [PEP 257](http://www.python.org/dev/peps/pep-0257/). > > * Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for ...
Should I check the types of constructor arguments (and at other places too)?
602,046
9
2009-03-02T11:55:04Z
602,078
8
2009-03-02T12:04:19Z
[ "python", "typechecking" ]
Python discourages checking the types. But in many cases this may be useful: 1. Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later. 2. Checking functions arguments. 3. In properties. If someone sets a wrong ...
The simple answer is **No**, use Polymorphism, Exceptions etc. 1. In the case of constructor arguments being of the wrong type, an exception will be thrown when executing code that depend s on the parameter being of a particular type. If it is a weird, domain specific thing, raise your own Exception. Surround blocks o...
Should I check the types of constructor arguments (and at other places too)?
602,046
9
2009-03-02T11:55:04Z
602,097
11
2009-03-02T12:12:01Z
[ "python", "typechecking" ]
Python discourages checking the types. But in many cases this may be useful: 1. Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later. 2. Checking functions arguments. 3. In properties. If someone sets a wrong ...
The answer is almost always "no". The general idea in Python, Ruby, and some other languages us called "[Duck Typing](http://en.wikipedia.org/wiki/Duck%5Ftyping)". You shouldn't care what something is, only how it works. In other words, "if all you want is something that quacks, you don't need to check that it's actual...
Do many Python libraries have relatively low code quality?
602,096
14
2009-03-02T12:11:56Z
602,139
21
2009-03-02T12:26:45Z
[ "python", "conventions" ]
**Edit:** Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously righ...
Regarding documentation, it's not just Python. If there is one single factor that is preventing the wider adoption of OSS it is, IMHO, the truly dreadful level of documentation of most OSS projects. This starts at the code level and extends to the user docs. Can I just say to anyone working on OSS: a) Comment your cod...
Do many Python libraries have relatively low code quality?
602,096
14
2009-03-02T12:11:56Z
602,172
7
2009-03-02T12:37:26Z
[ "python", "conventions" ]
**Edit:** Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously righ...
> Instead the authors each seem to follow their own glorious convention. And sometimes the conventions are not even consistent with the same file of a library Welcome to the wonderful code of the real world! FWIW Python code I have met is no better or worse than that in any other language. (Well, better than the ave...
Do many Python libraries have relatively low code quality?
602,096
14
2009-03-02T12:11:56Z
603,872
7
2009-03-02T20:27:56Z
[ "python", "conventions" ]
**Edit:** Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously righ...
The first thing you need to realize is that Python did not spring, fully formed, from the head of Guido sometime around version 2.x. It's grown over the course of the past twenty years. In fact, a number of the things you mention (unittest, for example, and PEP-8), didn't even exist when some of the standard libraries...
Evil code from the Python standard library
602,445
7
2009-03-02T14:03:39Z
602,460
10
2009-03-02T14:12:17Z
[ "python", "std" ]
So, we have had this: <http://lucumr.pocoo.org/2009/3/1/the-1000-speedup-or-the-stdlib-sucks>. It demonstrates a rather bad bug that is probably costing the universe a load of cycles even as we speak. It's fixed now, which is great. So what parts of the standard library have you noticed to be evil? I would expect all...
Never attribute to malice that which can be adequately explained by stupidity.