title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
python csv into dictionary | 1,898,305 | 9 | 2009-12-14T00:08:45Z | 2,545,452 | 8 | 2010-03-30T13:19:24Z | [
"python",
"csv"
] | I am pretty new to python. I need to create a class that loads csv data into a dictionary.
I want to be able to control the keys and value
So let say the following code, I can pull out worker1.name or worker1.age anytime i want.
```
class ageName(object):
'''class to represent a person'''
def __init__(self, name, age... | I second Mark's suggestion. In particular, look at DictReader from csv module that allows reading a comma separated (or delimited in general) file as a dictionary.
Look at [PyMotW's coverage of csv module](http://www.doughellmann.com/PyMOTW/csv/) for a quick reference and examples of usage of DictReader, DictWriter |
python csv into dictionary | 1,898,305 | 9 | 2009-12-14T00:08:45Z | 18,079,331 | 9 | 2013-08-06T11:48:06Z | [
"python",
"csv"
] | I am pretty new to python. I need to create a class that loads csv data into a dictionary.
I want to be able to control the keys and value
So let say the following code, I can pull out worker1.name or worker1.age anytime i want.
```
class ageName(object):
'''class to represent a person'''
def __init__(self, name, age... | I know this is a pretty old question, but it's impossible to read this, and not think of the amazing new(ish) Python library, `pandas`. Its main unit of analysis is a think called a DataFrame which is modelled after the way R handles data.
Let's say you have a (very silly) csv file called `example.csv` which looks lik... |
What is the difference between the __int__ and __index__ methods in Python 3? | 1,898,310 | 16 | 2009-12-14T00:11:34Z | 1,898,333 | 12 | 2009-12-14T00:18:21Z | [
"python",
"casting"
] | [The Data Model section of the Python 3.2 documentation](http://docs.python.org/release/3.2.1/reference/datamodel.html) provides the following descriptions for the `__int__` and `__index__` methods:
> ### `object.__int__(self)`
>
> Called to implement the built-in [function `int()`]. Should return [an integer].
>
> ##... | See [PEP 357](http://www.python.org/dev/peps/pep-0357/): Allowing Any Object to be Used for Slicing.
> The `nb_int` method is used for coercion and so means something
> fundamentally different than what is requested here. This PEP
> proposes a method for something that *can* already be thought of as
> an integer commu... |
Django Template Slice - Reversing Order | 1,898,544 | 8 | 2009-12-14T01:50:50Z | 1,898,587 | 8 | 2009-12-14T02:04:34Z | [
"python",
"django",
"django-templates"
] | Thanks to a very helpful hint from another question I learned I can limit the amount of values in a list by slicing it in the template as such:
```
{% for comment in thread.comment_set.all|slice:":3" %}
```
Now I would like to get the last 3 results of my comments so I figured a simple ":-3" or "-3" would do the tric... | I haven't seen the dictsortreversed filter used too often, and according to the docs it takes a key to sort by
```
{% for comment in thread.comment_set.all|dictsortreversed:"name"|slice:"3" %}
``` |
Django Template Slice - Reversing Order | 1,898,544 | 8 | 2009-12-14T01:50:50Z | 1,898,692 | 11 | 2009-12-14T03:00:43Z | [
"python",
"django",
"django-templates"
] | Thanks to a very helpful hint from another question I learned I can limit the amount of values in a list by slicing it in the template as such:
```
{% for comment in thread.comment_set.all|slice:":3" %}
```
Now I would like to get the last 3 results of my comments so I figured a simple ":-3" or "-3" would do the tric... | Django's database queries are evaluated lazily, so the result of `thread.comment_set.all` is a QuerySet, not a list. A QuerySet supports many list-like functions, but not negative slicing, so the indexing error is not coming from the template filter itself. (If you're curious, slices on QuerySet objects get translated ... |
Remove whitespace in Python using string.whitespace | 1,898,656 | 45 | 2009-12-14T02:30:34Z | 1,898,835 | 139 | 2009-12-14T03:59:41Z | [
"python",
"string",
"whitespace"
] | Python's string.whitespace is great:
```
>>> string.whitespace
'\t\n\x0b\x0c\r '
```
How do I use this with a string without resorting to manually typing in '\t|\n|... etc for regex?
For example, it should be able to turn:
"Please \n don't \t hurt \x0b me."
into
"Please don't hurt me."
I'd probably want to keep t... | There is a special-case shortcut for exactly this use case!
If you call `str.split` without an argument, it splits on runs of whitespace instead of single characters. So:
```
>>> ' '.join("Please \n don't \t hurt \x0b me.".split())
"Please don't hurt me."
``` |
Remove whitespace in Python using string.whitespace | 1,898,656 | 45 | 2009-12-14T02:30:34Z | 1,898,927 | 13 | 2009-12-14T04:29:39Z | [
"python",
"string",
"whitespace"
] | Python's string.whitespace is great:
```
>>> string.whitespace
'\t\n\x0b\x0c\r '
```
How do I use this with a string without resorting to manually typing in '\t|\n|... etc for regex?
For example, it should be able to turn:
"Please \n don't \t hurt \x0b me."
into
"Please don't hurt me."
I'd probably want to keep t... | What's wrong with the `\s` character class?
```
>>> import re
>>> pattern = re.compile(r'\s+')
>>> re.sub(pattern, ' ', "Please \n don't \t hurt \x0b me.")
"Please don't hurt me."
``` |
Remove whitespace in Python using string.whitespace | 1,898,656 | 45 | 2009-12-14T02:30:34Z | 1,900,041 | 9 | 2009-12-14T10:09:26Z | [
"python",
"string",
"whitespace"
] | Python's string.whitespace is great:
```
>>> string.whitespace
'\t\n\x0b\x0c\r '
```
How do I use this with a string without resorting to manually typing in '\t|\n|... etc for regex?
For example, it should be able to turn:
"Please \n don't \t hurt \x0b me."
into
"Please don't hurt me."
I'd probably want to keep t... | Let's make some reasonable assumptions:
(1) You really want to replace any run of whitespace characters with a single space (a run is of length 1 or greater).
(2) You would like the same code to work with minimal changes under Python 2.X with unicode objects.
(3) You don't want your code to assume things that are no... |
Tree Transformations Using Visitor Pattern | 1,898,967 | 7 | 2009-12-14T04:41:00Z | 1,900,050 | 8 | 2009-12-14T10:11:11Z | [
"java",
"python",
"tree",
"abstract-syntax-tree",
"visitor-pattern"
] | (Disclaimer: these examples are given in the context of building a compiler, but this question is all about the Visitor pattern and does not require any knowledge of compiler theory.) I'm going through Andrew Appel's Modern Compiler Implementation in Java to try to teach myself compiler theory (so no, this isn't homewo... | A SAX parser is a kind of visitor. To avoid adding a return value to the method, you can use a stack:
```
class Visitor {
Stack<Node> stack = new Stack<Node>();
// . . .
void visitPlus(PlusExp pe) {
pe.left.accept(this);
pe.right.accept(this);
Node b = stack.pop();
Node a =... |
PyLint "Unable to import" error - how to set PYTHONPATH? | 1,899,436 | 50 | 2009-12-14T07:22:05Z | 1,899,506 | 8 | 2009-12-14T07:45:20Z | [
"python",
"virtualenv",
"pylint",
"pythonpath"
] | I'm running PyLint from inside Wing IDE on Windows. I have a sub-directory (package) in my project and inside the package I import a module from the top level, ie.
```
__init__.py
myapp.py
one.py
subdir\
__init__.py
two.py
```
Inside `two.py` I have `import one` and this works fine at runtime, because the top... | Do you have an empty `__init__.py` file in both directories to let python know that the dirs are modules?
The basic outline when you are not running from within the folder (ie maybe from pylint's, though I haven't used that) is:
```
topdir\
__init__.py
functions_etc.py
subdir\
__init__.py
other_function... |
PyLint "Unable to import" error - how to set PYTHONPATH? | 1,899,436 | 50 | 2009-12-14T07:22:05Z | 3,065,082 | 43 | 2010-06-17T19:46:38Z | [
"python",
"virtualenv",
"pylint",
"pythonpath"
] | I'm running PyLint from inside Wing IDE on Windows. I have a sub-directory (package) in my project and inside the package I import a module from the top level, ie.
```
__init__.py
myapp.py
one.py
subdir\
__init__.py
two.py
```
Inside `two.py` I have `import one` and this works fine at runtime, because the top... | There are two options I'm aware of.
One, change the `PYTHONPATH` environment variable to include the directory above your module.
Alternatively, edit `~/.pylintrc` to include the directory above your module, like this:
```
[General]
init-hook='import sys; sys.path.append("/path/to/root")'
```
(Or in other version o... |
How to access a standard-library module in Python when there is a local module with the same name? | 1,900,189 | 12 | 2009-12-14T10:49:52Z | 1,900,333 | 17 | 2009-12-14T11:21:00Z | [
"python",
"import",
"module",
"standard-library"
] | How can a standard-library module (say math) be accessed when a file prog.py is placed in the same directory as a local module with the same name (math.py)?
I'm asking this question because I would like to create a package `uncertainties` that one can use as
```
import uncertainties
from uncertainties.math import *
`... | You are looking for Absolute/Relative imports from [PEP 328](https://www.python.org/dev/peps/pep-0328/), available with [2.5 and upward](http://docs.python.org/whatsnew/2.5.html#pep-328).
> In Python 2.5, you can switch importâs behaviour to absolute imports using a from \_\_future\_\_ import absolute\_import direct... |
Compile a string to Ruby bytecode for better performance -- like compile() in Python | 1,900,327 | 4 | 2009-12-14T11:19:25Z | 1,900,489 | 7 | 2009-12-14T11:55:25Z | [
"python",
"ruby",
"compilation",
"eval"
] | I have a string (authenticated, trusted, etc.) containing source code intended to run within a Ruby loop, quickly. In Python, I would compile the string into an abstract syntax tree and `eval()` or `exec()` it later:
```
# Python 3 example
given_code = 'n % 2 == 1'
pred = compile(given_code, '<given>', 'eval')
print("... | Based on the solution of jhs, but directly using the lambda as the loop body (the `&` calls `to_proc` on the lambda and passes it as block to the select function).
```
given_code = 'n % 2 == 1'
pred = eval "lambda { |n| #{given_code} }"
p all = (1..10).select(&pred)
``` |
Transitioning from desktop app written in C++ to a web-based app | 1,900,868 | 5 | 2009-12-14T13:16:34Z | 1,900,952 | 10 | 2009-12-14T13:33:09Z | [
"c#",
"c++",
"python",
"dll",
"web-based"
] | We have a mature Windows desktop application written in C++. The application's GUI sits on top of a windows DLL that does most of the work for the GUI (it's kind of the engine). It, too, is written in C++. We are considering transitioning the Windows app to be a web-based app for various reasons.
What I would like to ... | > See also [Can a huge existing
> application be ported to the web?
> How?](http://stackoverflow.com/questions/1025042/can-a-huge-existing-application-be-ported-to-the-web-how/1027917#1027917)
Sorry there are no good solutions, just less bad ones....
Firstly as you already develop for windows I am assuming that you a... |
Write variable to file, including name | 1,900,956 | 7 | 2009-12-14T13:34:33Z | 1,901,002 | 11 | 2009-12-14T13:44:18Z | [
"python"
] | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, bu... | use `pickle`
```
import pickle
dict = {'one': 1, 'two': 2}
file = open('dump.txt', 'w')
pickle.dump(dict, file)
file.close()
```
and to read it again
```
file = open('dump.txt', 'r')
dict = pickle.load(file)
```
EDIT: Guess I misread your question, sorry ... but pickle might help all the same. :) |
Write variable to file, including name | 1,900,956 | 7 | 2009-12-14T13:34:33Z | 1,901,016 | 23 | 2009-12-14T13:46:03Z | [
"python"
] | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, bu... | the `repr` function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.
```
>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'on... |
Write variable to file, including name | 1,900,956 | 7 | 2009-12-14T13:34:33Z | 1,901,103 | 14 | 2009-12-14T14:01:55Z | [
"python"
] | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, bu... | Is something like this what you're looking for?
```
def write_vars_to_file(_f, **vars):
for (name, val) in vars.items():
_f.write("%s = %s\n" % (name, repr(val)))
```
Usage:
```
>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}
``` |
Django template and the locals trick | 1,901,525 | 47 | 2009-12-14T15:22:03Z | 1,901,554 | 11 | 2009-12-14T15:26:39Z | [
"python",
"django"
] | The django books gives the local trick in order to avoid to type a long list of parameters as context dictionnary <http://www.djangobook.com/en/2.0/chapter04/>
It recommends this to lazy programmers but points out some overhead which may have an impact on performance.
I would like to know if some of you are using the... | I don't like it, personally. There's probably no reason for my preference, other than the old Python dictum "Explicit is better than implicit". I like to know exactly what's going into my templates. |
Django template and the locals trick | 1,901,525 | 47 | 2009-12-14T15:22:03Z | 1,901,720 | 73 | 2009-12-14T15:55:07Z | [
"python",
"django"
] | The django books gives the local trick in order to avoid to type a long list of parameters as context dictionnary <http://www.djangobook.com/en/2.0/chapter04/>
It recommends this to lazy programmers but points out some overhead which may have an impact on performance.
I would like to know if some of you are using the... | I don't like repetition -- I think "DRY", "Don't Repeat Yourself", is a key programming principle. As a consequence, I have indeed used `locals()` in similar situations. Django template rendering is far from the only situation of this kind: the general case is "a function or operator which accepts a dict, but doesn't m... |
Django template and the locals trick | 1,901,525 | 47 | 2009-12-14T15:22:03Z | 1,902,962 | 26 | 2009-12-14T19:31:33Z | [
"python",
"django"
] | The django books gives the local trick in order to avoid to type a long list of parameters as context dictionnary <http://www.djangobook.com/en/2.0/chapter04/>
It recommends this to lazy programmers but points out some overhead which may have an impact on performance.
I would like to know if some of you are using the... | I often thought of doing the following, but I am not sure if it is really helpful.
```
class MyStruct(object):
pass
def my_view(request, id):
c = MyStruct()
c.customer = ..
c.invoice = ..
c.date = ..
return render_to_response('xxx,html',c.__dict__)
``` |
vim and python scripts debugging | 1,901,528 | 26 | 2009-12-14T13:02:33Z | 1,902,220 | 22 | 2009-12-14T17:17:09Z | [
"python",
"vim"
] | Are there any ways to debug python scripts not leaving vim in \*nix systems (executing the script, setting up breakpoints, showing variables in watch-list, etc)? | Use [pdb](http://docs.python.org/library/pdb.html):
```
import pdb
def main():
list = [1,2,3]
pdb.set_trace()
list = [2,3,4]
if __name__ == '__main__':
main()
```
Now run using `:!python %` and you'll hit your breakpoint and be able to debug interactively like in [gdb](http://en.wikipedia.org/wiki/GNU_Debu... |
What is the standard sort order for Python release/version numbers? | 1,901,612 | 3 | 2009-12-14T15:35:32Z | 1,901,690 | 8 | 2009-12-14T15:49:29Z | [
"python",
"easy-install",
"pip"
] | Python's `pip` and `easy_install` follow some rules to sort packages by their release numbers. What are the rules for numbering beta/release/bugfix releases so these tools will know which is the newest? | This is a sore point for many folks. `setuptools` and `easy_install` have some rather bizarre rules in an attempt to play nice with everybody. You can read the full rules in `setuptools`'s `parse_version` method, but here's the summary:
* Version numbers are broken up by dots into a tuple of that many segments. 4.5.6.... |
Python Mechanize + GAEpython code | 1,902,079 | 5 | 2009-12-14T16:52:38Z | 2,056,543 | 10 | 2010-01-13T12:23:29Z | [
"python",
"google-app-engine",
"mechanize-python"
] | I am aware of previous questions regarding mechanize + Google App Engine,
[What pure Python library should I use to scrape a website?](http://stackoverflow.com/questions/1563165/what-pure-python-library-should-i-use-to-scrape-a-website)
and [Mechanize and Google App Engine](http://stackoverflow.com/questions/1389893/me... | I have solved this problem, just change the code of mechanize.\_http.py, about line 43,
from:
```
try:
socket._fileobject("fake socket", close=True)
except TypeError:
# python <= 2.4
create_readline_wrapper = socket._fileobject
else:
def create_readline_wrapper(fh):
return socket._fileobject(fh... |
NLTK - how to find out what corpora are installed from within python? | 1,902,967 | 4 | 2009-12-14T19:32:25Z | 1,903,002 | 7 | 2009-12-14T19:39:49Z | [
"python",
"nlp",
"nltk",
"corpus"
] | I'm trying to load some corpora I installed with the NLTK installer but I got a:
```
>>> from nltk.corpus import machado
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name machado
```
But in the download manager (`nltk.download()`) the package mach... | try
```
import nltk.corpus
dir(nltk.corpus)
```
at which point, it probably told you something about `__LazyModule__...` so do `dir(nltk.corpus)` again.
If that doesn't work, try tab-completion in iPython. |
Is Google App Engine right for me? | 1,903,065 | 9 | 2009-12-14T19:51:01Z | 1,904,610 | 8 | 2009-12-15T01:01:00Z | [
"python",
"google-app-engine",
"web2py"
] | I am thinking about using Google App Engine.It is going to be a huge website. In that case, what is your piece of advice using Google App Engine. I heard GAE has restrictions like we cannot store images or files more than 1MB limit(they are going to change this from what I read in the GAE roadmap),query is limited to 1... | Having developed a smallish site with GAE, I have some thoughts
* If you mean "huge" like "the next YouTube", then GAE might be a great fit, because of the previously mentioned scaling.
* If you mean "huge" like "massively complex, with a whole slew of screens, models, and features", then GAE might not be a good fit. ... |
How can I "zip sort" parallel numpy arrays? | 1,903,462 | 22 | 2009-12-14T21:00:03Z | 1,903,579 | 30 | 2009-12-14T21:19:39Z | [
"python",
"sorting",
"numpy"
] | If I have two parallel lists and want to sort them by the order of the elements in the first, it's very easy:
```
>>> a = [2, 3, 1]
>>> b = [4, 6, 2]
>>> a, b = zip(*sorted(zip(a,b)))
>>> print a
(1, 2, 3)
>>> print b
(2, 4, 6)
```
How can I do the same using numpy arrays without unpacking them into conventional Pyth... | `b[a.argsort()]` should do the trick.
Here's how it works. First you need to find a permutation that sorts a. `argsort` is a method that computes this:
```
>>> a = numpy.array([2, 3, 1])
>>> p = a.argsort()
>>> p
[2, 0, 1]
```
You can easily check that this is right:
```
>>> a[p]
array([1, 2, 3])
```
Now apply the... |
How can I "zip sort" parallel numpy arrays? | 1,903,462 | 22 | 2009-12-14T21:00:03Z | 1,903,997 | 14 | 2009-12-14T22:35:41Z | [
"python",
"sorting",
"numpy"
] | If I have two parallel lists and want to sort them by the order of the elements in the first, it's very easy:
```
>>> a = [2, 3, 1]
>>> b = [4, 6, 2]
>>> a, b = zip(*sorted(zip(a,b)))
>>> print a
(1, 2, 3)
>>> print b
(2, 4, 6)
```
How can I do the same using numpy arrays without unpacking them into conventional Pyth... | Here's an approach that creates no intermediate Python lists, though it does require a NumPy "record array" to use for the sorting. If your two input arrays are actually related (like columns in a spreadsheet) then this might open up an advantageous way of dealing with your data in general, rather than keeping two dist... |
why list comprehension is called so in python? | 1,903,980 | 7 | 2009-12-14T22:32:11Z | 1,904,054 | 7 | 2009-12-14T22:46:34Z | [
"python",
"naming-conventions",
"list-comprehension"
] | No flaming please, asking as a community wiki so nobody gets reputation here.
I know python is not the first language to have list comprehension.
I'm just interest in the history of the name.
I'm particularly interested in why it's called **comprehension** | The name comes from the concept of a [set-comprehension](http://en.wikipedia.org/wiki/Set-builder%5Fnotation)
*Comprehension* is used here to mean **complete inclusion** or **complete description**. A set-comprehension is a (usually short) complete description of a set, not an exhaustive (and possibly infinite) enumer... |
Django + MySQL on Mac OS 10.6.2 Snow Leopard | 1,904,039 | 9 | 2009-12-14T22:43:19Z | 1,914,329 | 21 | 2009-12-16T12:18:31Z | [
"python",
"mysql",
"django",
"osx-snow-leopard"
] | There were some excellent answers to this question already, however, they are now outdated.
I've been able to get the module installed, but "python manage.py runserver" fails with
```
iMac:myproject drhoden$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_ru... | I have ultimately solved my own problem, with of course, the subconscious and conscious help from the many posts, blogs, and mail logs I've read. I would give links if I could remember.
In a nutshell, I reinstalled EVERYTHING using MacPorts.
After editing ~/.bash\_profile and commenting out all the previous modificat... |
Python Observer Pattern: Examples, Tips? | 1,904,351 | 24 | 2009-12-14T23:51:31Z | 1,925,836 | 30 | 2009-12-18T01:59:40Z | [
"python",
"design",
"design-patterns",
"listener",
"observer-pattern"
] | Are there any exemplary examples of the GoF Observer implemented in Python? I have a bit code which currently has bits of debugging code laced through the key class (currently generating messages to stderr if a magic env is set). Additionally, the class has an interface for incrementally return results as well as stori... | > However it does lack flexibility.
Well... actually, this looks like a good design to me if an asynchronous API is what you want. It usually is. Maybe all you need is to switch from stderr to Python's [`logging`](http://docs.python.org/library/logging.html) module, which has a sort of publish/subscribe model of its o... |
Python Observer Pattern: Examples, Tips? | 1,904,351 | 24 | 2009-12-14T23:51:31Z | 1,926,336 | 8 | 2009-12-18T04:48:29Z | [
"python",
"design",
"design-patterns",
"listener",
"observer-pattern"
] | Are there any exemplary examples of the GoF Observer implemented in Python? I have a bit code which currently has bits of debugging code laced through the key class (currently generating messages to stderr if a magic env is set). Additionally, the class has an interface for incrementally return results as well as stori... | A few more approaches...
### Example: the logging module
Maybe all you need is to switch from stderr to Python's [`logging`](http://docs.python.org/library/logging.html#datagramhandler) module, which has a powerful publish/subscribe model.
It's easy to get started producing log records.
```
# producer
import loggin... |
Python Observer Pattern: Examples, Tips? | 1,904,351 | 24 | 2009-12-14T23:51:31Z | 27,315,715 | 7 | 2014-12-05T12:17:00Z | [
"python",
"design",
"design-patterns",
"listener",
"observer-pattern"
] | Are there any exemplary examples of the GoF Observer implemented in Python? I have a bit code which currently has bits of debugging code laced through the key class (currently generating messages to stderr if a magic env is set). Additionally, the class has an interface for incrementally return results as well as stori... | I think people in the other answers overdo it. You can easily achieve events in Python with less than 15 lines of code.
You simple have two classes: `Event` and `Observer`. Any class that wants to listen for an event, needs to inherit Observer and set to listen (observe) for a specific event. When an `Event` is instan... |
Read the first line of a file using Python | 1,904,394 | 71 | 2009-12-15T00:00:48Z | 1,904,409 | 15 | 2009-12-15T00:04:01Z | [
"python",
"file"
] | How would you get only the first line of a file as a string with Python? | ```
infile = open('filename.txt', 'r')
firstLine = infile.readline()
``` |
Read the first line of a file using Python | 1,904,394 | 71 | 2009-12-15T00:00:48Z | 1,904,455 | 136 | 2009-12-15T00:17:17Z | [
"python",
"file"
] | How would you get only the first line of a file as a string with Python? | Use the `.readline()` method ([Python 2 docs](https://docs.python.org/2/library/stdtypes.html#file.readline), [Python 3 docs](https://docs.python.org/3/library/io.html#io.IOBase.readline)):
```
with open('myfile.txt', 'r') as f:
first_line = f.readline()
```
Some notes:
1. As noted in the docs, unless it is the ... |
Read the first line of a file using Python | 1,904,394 | 71 | 2009-12-15T00:00:48Z | 1,904,563 | 10 | 2009-12-15T00:45:08Z | [
"python",
"file"
] | How would you get only the first line of a file as a string with Python? | ```
fline=open("myfile").readline().rstrip()
``` |
Read the first line of a file using Python | 1,904,394 | 71 | 2009-12-15T00:00:48Z | 1,904,928 | 7 | 2009-12-15T02:55:17Z | [
"python",
"file"
] | How would you get only the first line of a file as a string with Python? | To go back to the beginning of an open file, do this:
```
my_file.seek(0)
``` |
Is there any Python syntax highlighter for Visual Studio 2010? | 1,904,681 | 13 | 2009-12-15T01:22:31Z | 1,906,833 | 13 | 2009-12-15T11:29:46Z | [
"python",
"visual-studio-2010",
"ironpython",
"syntax-highlighting"
] | When I used Visual Studio 2008 I could install [IronPython](http://www.codeplex.com/wikipage?ProjectName=IronPython) + [IronPython Integrated IDE](http://ironpythonstudio.codeplex.com/) + [Visual Studio Shell Integrated Mode](http://www.microsoft.com/downloads/details.aspx?FamilyID=40646580-97FA-4698-B65F-620D4B4B1ED7&... | **[Python Tools for Visual Studio 2010](http://pytools.codeplex.com/)**
[IronPython.Net](http://ironpython.net/)
**This Extension is no longer available. See Jeff Hardy's comment below.**
Try IronPython Extensions for VisualStudio 2010:
<http://visualstudiogallery.msdn.microsoft.com/de-de/a0ffaffc-d1c2-4b6c-a9d1-3a... |
Is there any Python syntax highlighter for Visual Studio 2010? | 1,904,681 | 13 | 2009-12-15T01:22:31Z | 6,562,629 | 10 | 2011-07-03T11:36:37Z | [
"python",
"visual-studio-2010",
"ironpython",
"syntax-highlighting"
] | When I used Visual Studio 2008 I could install [IronPython](http://www.codeplex.com/wikipage?ProjectName=IronPython) + [IronPython Integrated IDE](http://ironpythonstudio.codeplex.com/) + [Visual Studio Shell Integrated Mode](http://www.microsoft.com/downloads/details.aspx?FamilyID=40646580-97FA-4698-B65F-620D4B4B1ED7&... | Here is the latest update (July 2011):
[Python Tools for Visual Studio 2010](http://pytools.codeplex.com/) |
In python, is there a setdefault() equivalent for getting object attributes? | 1,904,723 | 12 | 2009-12-15T01:37:09Z | 1,905,593 | 16 | 2009-12-15T06:39:09Z | [
"python"
] | Python's [setdefault](http://docs.python.org/library/stdtypes.html#dict.setdefault) allows you to get a value from a dictionary, but if the key doesn't exist, then you assign the based on parameter `default`. You then fetch whatever is at the key in the dictionary.
Without manipulating an object's `__dict__`Is there a... | Note that the currently accepted answer will, if the attribute doesn't exist already, have called hasattr(), setattr() and getattr(). This would be necessary only if the OP had done something like overriding setattr and/or getattr -- in which case the OP is not the innocent enquirer we took him for. Otherwise calling a... |
Py2exe: Are manifest files and w9xpopen.exe required when compiling a web server without GUI interface? | 1,904,724 | 10 | 2009-12-15T01:37:17Z | 1,904,750 | 10 | 2009-12-15T01:44:31Z | [
"python",
"windows",
"py2exe",
"cherrypy"
] | I'm using Py2exe to compile a CherryPy (3.1) server using Python 2.6 (32-bit) on Windows 7 Pro (64-bit).
This server will run without a GUI.
Questions:
1. Do I need to be concerned about adding a manifest file for this application if it runs without a GUI?
2. Do I need to include w9xpopen.exe with my exe?
So far, m... | w9xpopen.exe is for windows 95/98, So If you don't use those you will not need it.
You can add `dll_excludes=['w9xpopen.exe']` in your setup file for py2exe to exclude that.
and of course you will not need manifest file if you don't use GUI too. |
Install libxml2 and associated python bindings - Windows | 1,904,752 | 25 | 2009-12-15T01:44:59Z | 1,904,784 | 26 | 2009-12-15T01:57:42Z | [
"python",
"windows",
"libxml2"
] | I am attempting to install libxml2 so that I can setup the python bindings and eventually use lxml.
However I am unable to work out here on earth I am supposed to be unzipping the files.
I haven't been able to google successfully.
Do I need Cygwin/MinGW for the installation to be successful?
At the moment I have the... | If you don't have special reasons to compile from source, you can use [prebuilt binaries](https://pypi.python.org/pypi/lxml) for lxml |
Install libxml2 and associated python bindings - Windows | 1,904,752 | 25 | 2009-12-15T01:44:59Z | 9,056,298 | 28 | 2012-01-29T20:04:47Z | [
"python",
"windows",
"libxml2"
] | I am attempting to install libxml2 so that I can setup the python bindings and eventually use lxml.
However I am unable to work out here on earth I am supposed to be unzipping the files.
I haven't been able to google successfully.
Do I need Cygwin/MinGW for the installation to be successful?
At the moment I have the... | The Windows binaries of the latest version of lxml (as well as a wide range of other Python packages) are available on <http://www.lfd.uci.edu/~gohlke/pythonlibs/> |
Is IronPython usable as a replacement for CPython? | 1,905,023 | 4 | 2009-12-15T03:41:48Z | 1,905,168 | 8 | 2009-12-15T04:27:03Z | [
"python",
"ironpython",
"dynamic-language-runtime",
"cpython"
] | Has IronPython gotten to a point where you can just drop it in as a replacement for CPython?
To clarify: I mean can IronPython run applications originally written for CPython (no .NET involved, of course) | Yes, pretty much, at least on Windows with "real" (Microsoft) .NET underneath. If you're depending on C-coded extensions, chances are that [ironclad](http://code.google.com/p/ironclad/) can bail you out; you get 2.6 support, just about every CPython standard library or third-party extension module (maybe not trivial fo... |
Keyword Matching in Pyparsing: non-greedy slurping of tokens | 1,905,278 | 5 | 2009-12-15T05:05:23Z | 1,905,809 | 7 | 2009-12-15T07:46:51Z | [
"python",
"parsing",
"grammar",
"pyparsing"
] | Pythonistas:
Suppose you want to parse the following string using Pyparsing:
```
'ABC_123_SPEED_X 123'
```
were `ABC_123` is an identifier; `SPEED_X` is a parameter, and `123` is a value. I thought of the following BNF using Pyparsing:
```
Identifier = Word( alphanums + '_' )
Parameter = Keyword('SPEED_X') or Keywo... | I based my answer off of [this one](http://pyparsing.wikispaces.com/message/view/HowToUsePyparsing/178079), since what you're trying to do is get a non-greedy match. It seems like this is difficult to make happen in pyparsing, but not impossible with some cleverness and compromise. The following seems to work:
```
fro... |
python time(milli seconds) calculation | 1,905,403 | 6 | 2009-12-15T05:46:32Z | 1,905,423 | 11 | 2009-12-15T05:52:30Z | [
"python",
"time"
] | How to calculate milliseconds,from the code below.
```
a = datetime.datetime.now()
b = datetime.datetime.now()
c = b - a
>>> c
>>> c.days
0
>>> c.seconds
4
>>> c.microseconds
``` | ```
milliseconds = (c.days * 24 * 60 * 60 + c.seconds) * 1000 + c.microseconds / 1000.0
``` |
Crop a PNG image to its minimum size | 1,905,421 | 5 | 2009-12-15T05:52:01Z | 1,905,468 | 10 | 2009-12-15T06:09:32Z | [
"python",
"image",
"png"
] | How to cut off the blank border area of a PNG image and shrink it to its minimum size using Python? | [PIL](http://www.pythonware.com/products/pil/)'s [getbbox](http://www.pythonware.com/library/pil/handbook/image.htm) is working for me
> im.getbbox() => 4-tuple or None
>
> Calculates the bounding box of the
> non-zero regions in the image. The
> bounding box is returned as a 4-tuple
> defining the left, upper, right,... |
dict keys with spaces in Django templates | 1,906,129 | 12 | 2009-12-15T09:06:30Z | 1,906,279 | 16 | 2009-12-15T09:43:27Z | [
"python",
"django",
"django-templates",
"whitespace"
] | I am trying to present a dictionary from my view.py at the HTML template such as:
```
test = { 'works': True, 'this fails':False }
```
and in the template:
This works without a problem:
```
{{ test.works }}
```
But a dictionary key that is having an empty space between words such as 'this fails' doesn't work:
```... | The filter you want is something like
```
@register.filter(name='getkey')
def getkey(value, arg):
return value[arg]
```
And used with
```
{{test|getkey:'this works'}}
```
source: <http://www.bhphp.com/blog4.php/2009/08/17/django-templates-and-dictionaries> |
multiple requests in a single connection? | 1,906,151 | 3 | 2009-12-15T09:09:37Z | 1,906,201 | 10 | 2009-12-15T09:23:37Z | [
"python",
"connection",
"httplib"
] | Is it possible to put multiple requests without breaking the connection using python httplib?.
Like, can I upload a big file to the server in parts but in a single socket connection.
I looked for answers. But nothing seemed so clear and definite.
Any examples/related links will be helpfull.
Thanks. | Yes, the connection stays open until you close it using the `close()` method.
The following example, taken from the [httplib documentation](http://docs.python.org/dev/library/httplib.html), shows how to perform multiple requests using a single connection:
```
>>> import httplib
>>> conn = httplib.HTTPConnection("www.... |
splitting integer in python? | 1,906,717 | 11 | 2009-12-15T11:09:00Z | 1,906,723 | 31 | 2009-12-15T11:10:17Z | [
"python"
] | my integer input is suppose 12345 , i want to split and put it into an array as 1,2,3,4,5 . How will i be able to do it? | return array as string
```
>>> list(str(12345))
['1', '2', '3', '4', '5']
```
return array as integer
```
>>> map(int,str(12345))
[1, 2, 3, 4, 5]
``` |
splitting integer in python? | 1,906,717 | 11 | 2009-12-15T11:09:00Z | 1,906,727 | 33 | 2009-12-15T11:12:22Z | [
"python"
] | my integer input is suppose 12345 , i want to split and put it into an array as 1,2,3,4,5 . How will i be able to do it? | ```
>>> [int(i) for i in str(12345)]
[1, 2, 3, 4, 5]
``` |
python unbound method again | 1,906,926 | 3 | 2009-12-15T11:51:28Z | 1,906,949 | 7 | 2009-12-15T11:57:16Z | [
"python",
"class"
] | This gets me into difficult time (sorry, i am still very new to python)
Thank you for any kind of help.
The error
> ```
> print Student.MostFrequent() TypeError: unbound method
> ```
>
> MostFrequent() must be called with
> Student instance as first argument
> (got nothing instead)
This Student.MostFrequent() is cal... | use `Student().MostFrequent()`
**edit**:
beware that you use class attributes and this is dangerous. here an example:
```
>>> class Person:
... name = None
... hobbies = []
... def __init__(self, name):
... self.name = name
...
>>> a = Person('marco')
>>> b = Person('francesco')
>>> a.hobbies.append('football'... |
python unbound method again | 1,906,926 | 3 | 2009-12-15T11:51:28Z | 1,906,958 | 7 | 2009-12-15T11:58:52Z | [
"python",
"class"
] | This gets me into difficult time (sorry, i am still very new to python)
Thank you for any kind of help.
The error
> ```
> print Student.MostFrequent() TypeError: unbound method
> ```
>
> MostFrequent() must be called with
> Student instance as first argument
> (got nothing instead)
This Student.MostFrequent() is cal... | **first** read [PEP-8](http://www.python.org/dev/peps/pep-0008/) on naming conventions:
> Method Names and Instance Variables
```
Use the function naming rules: lowercase with words separated by
underscores as necessary to improve readability.
```
**second** you are calling `mostFrequest` on the class `Student`,... |
Read https url from Python with basic access authentication | 1,906,977 | 4 | 2009-12-15T12:02:58Z | 1,910,005 | 9 | 2009-12-15T20:02:53Z | [
"python",
"authentication",
"https",
"passwords"
] | How do you open https url in Python?
```
import urllib2
url = "https://user:[email protected]/path/
f = urllib2.urlopen(url)
print f.read()
```
gives:
```
httplib.InvalidURL: nonnumeric port: '[email protected]'
``` | This has never failed me
```
import urllib2, base64
username = 'foo'
password = 'bar'
auth_encoded = base64.encodestring('%s:%s' % (username, password))[:-1]
req = urllib2.Request('https://somewebsite.com')
req.add_header('Authorization', 'Basic %s' % auth_encoded)
try:
response = urllib2.urlopen(req)
except urll... |
How do I check if it's Monday to Friday and the time is between 10 AM to 3 PM? | 1,907,196 | 9 | 2009-12-15T12:45:45Z | 1,907,247 | 14 | 2009-12-15T12:52:36Z | [
"python",
"datetime"
] | In python how do I check if its a weekday (Monday - Friday) and the time is between 10 AM to 3 PM? | ```
>>> import datetime
>>> d = datetime.datetime.now()
# => datetime.datetime(2009, 12, 15, 13, 50, 35, 833175)
# check if weekday is 1..5
>>> d.isoweekday() in range(1, 6)
True
# check if hour is 10..15
>>> d.hour in range(10, 15)
True
# check if minute is 30
>>> d.minute==30
False
``` |
C,Python - different behaviour of the modulo (%) operation | 1,907,565 | 40 | 2009-12-15T13:46:07Z | 1,907,585 | 46 | 2009-12-15T13:48:13Z | [
"python",
"c",
"math"
] | I have found that the same mod operation produces different results depending on what language is being used.
In Python:
```
-1 % 10
```
produces **9**
In C it produces **-1** !
1) Which one is the right modulo?
2) How to make mod operation in C to be the same like in Python? | 1. Both variants are correct, however in mathematics (number theory in particular), Python's [modulo](http://en.wikipedia.org/wiki/Modulo%5Foperation) is most commonly used.
2. In C, you do `((n % M) + M) % M` to get the same result as in Python. E. g. `((-1 % 10) + 10) % 10`. Note, how it still works for positive inte... |
C,Python - different behaviour of the modulo (%) operation | 1,907,565 | 40 | 2009-12-15T13:46:07Z | 1,907,723 | 23 | 2009-12-15T14:11:20Z | [
"python",
"c",
"math"
] | I have found that the same mod operation produces different results depending on what language is being used.
In Python:
```
-1 % 10
```
produces **9**
In C it produces **-1** !
1) Which one is the right modulo?
2) How to make mod operation in C to be the same like in Python? | Python has a "true" modulo operation, while C has a *remainder* operation.
It has a direct relation with how the negative integer division is handled, i.e. rounded towards 0 or minus infinite. Python rounds towards minus infinite and C(99) towards 0, but in both languages `(n/m)*m + n%m == n`, so the % operator must c... |
C,Python - different behaviour of the modulo (%) operation | 1,907,565 | 40 | 2009-12-15T13:46:07Z | 1,907,889 | 13 | 2009-12-15T14:38:36Z | [
"python",
"c",
"math"
] | I have found that the same mod operation produces different results depending on what language is being used.
In Python:
```
-1 % 10
```
produces **9**
In C it produces **-1** !
1) Which one is the right modulo?
2) How to make mod operation in C to be the same like in Python? | In C89/90 the behavior of division operator and remainder operator with negative operands is *implementation-defined*, meaning that depending on the implementation you can get either behavior. It is just required that the operators agree with each other: from `a / b = q` and `a % b = r` follows `a = b * q + r`. Use sta... |
In there something similar to Java's Thread.yield() in Python? Does that even make sense? | 1,908,206 | 7 | 2009-12-15T15:30:28Z | 1,908,252 | 10 | 2009-12-15T15:38:13Z | [
"python",
"multithreading",
"sleep",
"yield"
] | I want to tell my Python threads to yield, and so avoid hogging the CPU unnecessarily. In Java, you could do that using the `Thread.yield()` function. I don't think there is something similar in Python, so I have been using `time.sleep(t)` where `t = 0.00001`. For `t=0` there seems to be no effect.
I think that maybe ... | Dup of: [How does a threading.Thread yield the rest of its quantum in Python?](http://stackoverflow.com/questions/787803/how-does-a-threading-thread-yield-the-rest-of-its-quantum-in-python).
```
time.sleep(0)
``` |
Parsing XML to a hash table | 1,908,410 | 4 | 2009-12-15T15:57:26Z | 1,908,987 | 12 | 2009-12-15T17:18:26Z | [
"python",
"xml",
"dom"
] | I have an XML file in the following format:
```
<doc>
<id name="X">
<type name="A">
<min val="100" id="80"/>
<max val="200" id="90"/>
</type>
<type name="B">
<min val="100" id="20"/>
<max val="20" id="90"/>
</type>
</id>
<type...>
</type>
</doc>
```
I would like to parse this document and bu... | I disagree with the suggestion in other answers to use minidom -- that's a so-so Python adaptation of a standard originally conceived for other languages, usable but not a great fit. The recommended approach in modern Python is [ElementTree](http://docs.python.org/library/xml.etree.elementtree.html).
The same interfac... |
How to do this GROUP BY query in Django's ORM with annotate and aggregate | 1,908,741 | 5 | 2009-12-15T16:43:37Z | 1,909,277 | 14 | 2009-12-15T18:08:11Z | [
"python",
"django",
"orm",
"group-by"
] | I don't really have groked how to translate `GROUP BY` and `HAVING` to Django's `QuerySet.annotate` and `QuerySet.aggregate`. I'm trying to translate this SQL query into ORM speak
```
SELECT EXTRACT(year FROM pub_date) as year, EXTRACT(month from pub_date) as month, COUNT(*) as article_count FROM articles_article GROU... | I think to do it in one query you might have to have month and year as separate fields...
```
Article.objects.values('pub_date').annotate(article_count=Count('title'))
```
That would `group by` by pub\_date. But there is no way I can think of to do the equivalent of the `extract` function clause inline there.
If you... |
Netcat implementation in Python | 1,908,878 | 21 | 2009-12-15T17:01:41Z | 1,909,355 | 34 | 2009-12-15T18:18:02Z | [
"python",
"netcat"
] | I found [this](http://4thmouse.com/index.php/2008/02/22/netcat-clone-in-three-languages-part-ii-python/) and am using it as my base, but it wasn't working right out of the box. My goal is also to treat it as a package instead of a command line utility, so my code changes will reflect that.
```
class Netcat:
def __... | Does it work if you just use [`nc`](http://www.openbsd.org/cgi-bin/man.cgi?query=nc&sektion=1)?
I think you should try something a little simpler:
```
import socket
def netcat(hostname, port, content):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, port))
s.sendall(content)
... |
Import error with virtualenv | 1,909,025 | 5 | 2009-12-15T17:26:21Z | 1,910,294 | 7 | 2009-12-15T20:46:57Z | [
"python",
"virtualenv"
] | I have a problem with virtualenv. I use it regulary, I use it on my development machine and on several servers. But on this last server I tried to use i got a problem.
I created a virtualenv with the --no-site-packages argument, and then I installed some python modules inside the virtualenv. I can confirm that the mod... | Is there a bash alias active on this machine for "python", by any chance? That will take priority over the PATH-modifications made by activate, and could cause the wrong python binary to be used.
Try running virtualenv/bin/python directly (no need to activate) and see if you can import your module.
If this fixes it, ... |
How to clean up my Python Installation for a fresh start | 1,909,249 | 17 | 2009-12-15T18:03:17Z | 1,909,611 | 11 | 2009-12-15T19:03:05Z | [
"python",
"osx",
"osx-snow-leopard"
] | I'm developing on Snow Leopard and going through the various "how tos" to get the MySQLdb package installed and working (uphill battle). Things are a mess and I'd like to regain confidence with a fresh, clean, as close to factory install of Python 2.6.
What folders should I clean out?
What should I run?
What symboli... | One thing you should *not* do is try to remove or change any of the Apple-supplied python files or links: they are in `/usr/bin` and `/System/Library/Frameworks/Python.framework`. These are part of OS X and managed by Apple. It is fine to clean up any unnecessary packages you have installed for that Python. They are in... |
Is it possible to use functions before declaring their body in python? | 1,909,325 | 8 | 2009-12-15T18:14:27Z | 1,909,379 | 13 | 2009-12-15T18:21:47Z | [
"python"
] | Is there any way to make possible to use functions in your file before you actually declare their body?
The following code doesn't seem to work:
```
abc = myFunction
def myFunction():
print "123"
```
Thanks | You can *declare* functions that use forward declarations, but Python *executes* the code in your source from top to bottom. So, this would compile and run:
```
def foo():
print "in foo"
bar()
def bar():
print "in bar"
foo()
foo()
```
(except it would cause a stack overflow at runtime, of course). I... |
Is it possible to use functions before declaring their body in python? | 1,909,325 | 8 | 2009-12-15T18:14:27Z | 1,909,389 | 14 | 2009-12-15T18:23:27Z | [
"python"
] | Is there any way to make possible to use functions in your file before you actually declare their body?
The following code doesn't seem to work:
```
abc = myFunction
def myFunction():
print "123"
```
Thanks | You can't use the `myFunction` variable before it's assigned. Your example code is similar to:
```
def myFunction():
print abc
abc = 123
```
To do what you want, either re-arrange the order:
```
def myFunction():
print "123"
abc = myFunction
```
Or declare `abc` as just a proxy:
```
# Style 1
abc = la... |
C/Python Socket Performance? | 1,909,471 | 10 | 2009-12-15T18:39:23Z | 1,909,511 | 11 | 2009-12-15T18:46:34Z | [
"python",
"c",
"sockets",
"scapy"
] | my question simply relates to the difference in performance between a socket in C and in Python. Since my Python build is CPython, I assume it's similar, but I'm curious if someone actually has "real" benchmarks, or at least an opinion that's evidence based.
My logics is as such:
* C socket much faster? then write a ... | In general, sockets in Python perform just fine. For example, the reference implementation of the BitTorrent tracker server is written in Python.
When doing networking operations, the speed of the network is usually the limiting factor. That is, any possible tiny difference in speed between C and Python's socket code ... |
What is python used for? | 1,909,512 | 88 | 2009-12-15T18:46:46Z | 1,923,081 | 114 | 2009-12-17T16:50:33Z | [
"python"
] | Okay, so I am fairly new at programming (knowing only html, CSS, and JavaScript) and I just started diving into python. What I want to know is, what is it used for and what is it designed for? | Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.
1. Python is **dynamically** typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assig... |
lisp-style style `let` syntax in Python list-comprehensions | 1,910,003 | 6 | 2009-12-15T20:02:47Z | 1,910,132 | 7 | 2009-12-15T20:22:15Z | [
"refactoring",
"lisp",
"python"
] | Consider the following code:
```
>>> colprint([
(name, versions[name][0].summary or '')
for name in sorted(versions.keys())
])
```
What this code does is to print the elements of the dictionary `versions` in ascending order of its `keys`, but since the `value` is another sorted list, only the summ... | Why not exploit tuples?
```
colprint([(name, version[0].summary or '')
for (name, version) in sorted(versions.iteritems())])
```
or, even
```
colprint(sorted([(name, version[0].summary or '')
for (name, version) in versions.iteritems()]))
```
Also, you may consider (in my first example) removing ... |
How should I deal with a circular import in Google App Engine? | 1,910,886 | 9 | 2009-12-15T22:29:35Z | 1,912,396 | 7 | 2009-12-16T04:56:50Z | [
"python",
"google-app-engine"
] | If I have "a.py"
```
from google.appengine.ext import db
class A(db.Model):
db.ReferenceProperty(b.B)
...other stuff
```
and another file "b.py"
```
from google.appengine.ext import db
class B(db.Model):
db.ReferenceProperty(a.A)
...other stuff
```
It would appear that Python simply does not allow c... | The workaround is to have a ReferenceProperty in at least one of the models that doesn't restrict itself to a particular class, and then enforce only referencing that class in your own code.
e.g.,
```
class A(db.Model):
b = db.ReferenceProperty()
class B(db.Model):
a = db.ReferenceProperty(A)
```
You'll be able... |
concatenate items in dictionary in python using list comprehension | 1,911,014 | 4 | 2009-12-15T22:49:10Z | 1,911,025 | 7 | 2009-12-15T22:51:32Z | [
"python",
"list-comprehension"
] | EDIT: Clarified the question a bit
How can I get a string from a dictionary with the format
```
key1 = value1
key2 = value2
```
in a relatively fast way ? (relative to plain concatenation) | ```
print '\n'.join('%s = %s' % (key, value) for key, value in d.iteritems())
``` |
concatenate items in dictionary in python using list comprehension | 1,911,014 | 4 | 2009-12-15T22:49:10Z | 1,911,027 | 9 | 2009-12-15T22:51:40Z | [
"python",
"list-comprehension"
] | EDIT: Clarified the question a bit
How can I get a string from a dictionary with the format
```
key1 = value1
key2 = value2
```
in a relatively fast way ? (relative to plain concatenation) | There's no reason to use list comprehension here.
Python 3.x:
```
for k,v in mydict.items():
print(k, '=', v)
```
Python 2.x:
```
for k,v in mydict.iteritems():
print k, '=', v
```
**EDIT because of comment by OP in another answer:**
If you're passing it to a function and not printing it here, then you should... |
Is there a better way to compare dictionary values | 1,911,273 | 9 | 2009-12-15T23:39:12Z | 1,911,722 | 15 | 2009-12-16T01:36:09Z | [
"python",
"dictionary"
] | I am currently using the following function to compare dictionary values. Is there a faster or better way to do it?
```
match = True
for keys in dict1:
if dict1[keys] != dict2[keys]:
match = False
print keys
print dict1[keys],
print '->' ,
print dict2[keys]
```
Edit: Both ... | If the dicts have identical sets of keys and you need all those prints for any value difference, there isn't much you can do; maybe something like:
```
diffkeys = [k for k in dict1 if dict1[k] != dict2[k]]
for k in diffkeys:
print k, ':', dict1[k], '->', dict2[k]
```
pretty much equivalent to what you have, but you... |
Is there a better way to compare dictionary values | 1,911,273 | 9 | 2009-12-15T23:39:12Z | 5,635,309 | 36 | 2011-04-12T12:39:48Z | [
"python",
"dictionary"
] | I am currently using the following function to compare dictionary values. Is there a faster or better way to do it?
```
match = True
for keys in dict1:
if dict1[keys] != dict2[keys]:
match = False
print keys
print dict1[keys],
print '->' ,
print dict2[keys]
```
Edit: Both ... | If the true intent of the question is the comparison between dicts (rather than printing differences), the answer is
```
dict1 == dict2
```
This has been mentioned before, but I felt it was slightly drowning in other bits of information. It might appear superficial, but the value comparison of dicts has actually powe... |
How do I get list of methods in a Python class? | 1,911,281 | 161 | 2009-12-15T23:40:41Z | 1,911,287 | 165 | 2009-12-15T23:41:56Z | [
"python"
] | I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods?
Also see:
* [How can I list the methods in a
Python 2.5 module?](http://stackoverflow.com/questions/1280787/how-can-i-list-the-methods-in-a-python-2-5... | An example (listing the methods of the `optparse.OptionParser` class):
```
>>> from optparse import OptionParser
>>> import inspect
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
('add_option', <unbound method OptionParser.add_option>),
(... |
How do I get list of methods in a Python class? | 1,911,281 | 161 | 2009-12-15T23:40:41Z | 1,911,291 | 19 | 2009-12-15T23:42:38Z | [
"python"
] | I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods?
Also see:
* [How can I list the methods in a
Python 2.5 module?](http://stackoverflow.com/questions/1280787/how-can-i-list-the-methods-in-a-python-2-5... | Try the property `__dict__`. |
How do I get list of methods in a Python class? | 1,911,281 | 161 | 2009-12-15T23:40:41Z | 1,911,313 | 80 | 2009-12-15T23:49:18Z | [
"python"
] | I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods?
Also see:
* [How can I list the methods in a
Python 2.5 module?](http://stackoverflow.com/questions/1280787/how-can-i-list-the-methods-in-a-python-2-5... | There is the `dir(theobject)` method to list all the fields and methods of your object (as a tuple) and the inspect module (as codeape write) to list the fields and methods with their doc (in """).
Because everything (even fields) might be called in Python, I'm not sure there is a built-in function to list only method... |
Nested SSH session with Paramiko | 1,911,690 | 25 | 2009-12-16T01:28:06Z | 1,916,877 | 22 | 2009-12-16T18:59:53Z | [
"python",
"ssh",
"paramiko"
] | I'm rewriting a Bash script I wrote into Python. The crux of that script was
```
ssh -t first.com "ssh second.com very_remote_command"
```
I'm having a problem with the nested authentication with paramiko. I wasn't able to find any examples dealing with my precise situation, but I was able to find examples with *sudo... | I managed to find a solution, but it requires a little manual work. If anyone have a better solution, please tell me.
```
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('first.com', username='luser', password='secret')
chan = ssh.invoke_shell()
# Ssh and wait for the... |
Nested SSH session with Paramiko | 1,911,690 | 25 | 2009-12-16T01:28:06Z | 10,432,669 | 12 | 2012-05-03T13:42:53Z | [
"python",
"ssh",
"paramiko"
] | I'm rewriting a Bash script I wrote into Python. The crux of that script was
```
ssh -t first.com "ssh second.com very_remote_command"
```
I'm having a problem with the nested authentication with paramiko. I wasn't able to find any examples dealing with my precise situation, but I was able to find examples with *sudo... | Here is a small example using paramiko only (and port forwarding):
```
import paramiko as ssh
class SSHTool():
def __init__(self, host, user, auth,
via=None, via_user=None, via_auth=None):
if via:
t0 = ssh.Transport(via)
t0.start_client()
t0.auth_passwo... |
How does this max() expression in Python work? | 1,911,981 | 2 | 2009-12-16T03:01:12Z | 1,912,002 | 9 | 2009-12-16T03:07:03Z | [
"python",
"lambda",
"max"
] | Here's the code:
```
a = [1,2,3,4]
b = {}
b[1] = 10
b[2] = 8
b[3] = 7
b[4] = 5
print max(a,key=lambda w: b[w])
```
This prints out `1`.
I don't understand how `max(a,key=lambda w: b[w])` is being evaluated here though; I'm guessing for each value i in a, it finds the corresponding value b[i] by
1. saving the curren... | `max(a,...)` is always going to return an element of `a`. So the result will be either 1,2,3, or 4.
For each value `w` in `a`, the key value is `b[w]`. The largest key value is 10, and that corresponds with `w` equalling 1. So `max(a,key=lambda w: b[w])` returns 1. |
deleter decorator using Property in Python | 1,912,229 | 7 | 2009-12-16T04:11:41Z | 1,912,252 | 7 | 2009-12-16T04:16:30Z | [
"python",
"properties",
"decorator"
] | I'm playing around with property in Python and I was wondering how this @propertyName.deleter decorator works. I'm probably missing something, I could not find clear answers by Google.
What I would like to achieve is when this **deleter** behavior is called, I can trigger other actions (e.g: using my 3d application SD... | Make M a new-style class:
```
class M(object):
```
See <http://www.python.org/download/releases/2.2.3/descrintro/#property>:
> **Properties do not work for classic
> classes**, but you don't get a clear
> error when you try this. Your get
> method will be called, so it appears
> to work, but upon attribute
> assignm... |
Django: Where to put helper functions? | 1,912,351 | 31 | 2009-12-16T04:44:50Z | 1,912,370 | 32 | 2009-12-16T04:50:03Z | [
"python",
"django"
] | I have a couple of functions that i wrote that I need to use in my django app. Where would I put the file with them and how would i make them callable whithin my views? | I usually put such app specific helper function in file utils.py and use someting like this
```
from myapp.utils import my_cool_func
def view_coolness(request):
data = my_cool_func(request)
return render_to_response("xxx.html")
```
but it depends what you helper does, may be they modify request , the could b... |
Django: Where to put helper functions? | 1,912,351 | 31 | 2009-12-16T04:44:50Z | 1,912,371 | 7 | 2009-12-16T04:50:06Z | [
"python",
"django"
] | I have a couple of functions that i wrote that I need to use in my django app. Where would I put the file with them and how would i make them callable whithin my views? | If they are related to a specific app, I usually just put them in the related app folder and name the file, 'functions.py'.
If they're not specific to an app, you could just make a 'functions' app folder and place them in there. |
How do I parse XML in Python? | 1,912,434 | 522 | 2009-12-16T05:09:24Z | 1,912,445 | 145 | 2009-12-16T05:12:43Z | [
"python",
"xml"
] | I have many rows in a database that contains xml and I'm trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like:
```
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
```
How ... | You can use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/)
```
from bs4 import BeautifulSoup
x="""<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>"""
y=BeautifulSoup(x)
>>> y.foo.bar.type["foobar"]
u'1'
>>> y.foo.bar.findAll("type")
[<type foobar="1"></type>, <type f... |
How do I parse XML in Python? | 1,912,434 | 522 | 2009-12-16T05:09:24Z | 1,912,483 | 384 | 2009-12-16T05:21:55Z | [
"python",
"xml"
] | I have many rows in a database that contains xml and I'm trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like:
```
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
```
How ... | I suggest [`ElementTree`](http://docs.python.org/library/xml.etree.elementtree.html). There are other compatible implementations of the same API, such as [`lxml`](http://lxml.de/), and `cElementTree` in the Python standard library itself; but, in this context, what they chiefly add is even more speed -- the ease of pro... |
How do I parse XML in Python? | 1,912,434 | 522 | 2009-12-16T05:09:24Z | 1,912,486 | 11 | 2009-12-16T05:23:31Z | [
"python",
"xml"
] | I have many rows in a database that contains xml and I'm trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like:
```
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
```
How ... | I'm still a Python newbie myself, but my impression is that [ElementTree](http://docs.python.org/library/xml.etree.elementtree.html) is the state-of-the-art in Python XML parsing and handling.
Mark Pilgrim has [a good section](http://getpython3.com/diveintopython3/xml.html#xml-parse) on Parsing XML with ElementTree in... |
How do I parse XML in Python? | 1,912,434 | 522 | 2009-12-16T05:09:24Z | 1,912,504 | 16 | 2009-12-16T05:28:00Z | [
"python",
"xml"
] | I have many rows in a database that contains xml and I'm trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like:
```
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
```
How ... | Python has an interface to the expat xml parser.
```
xml.parsers.expat
```
It's a non-validating parser, so bad xml will not be caught. But if you know your file is correct, then this is pretty good, and you'll probably **get the exact info you want and you can discard the rest on the fly.**
```
stringofxml = """<fo... |
How do I parse XML in Python? | 1,912,434 | 522 | 2009-12-16T05:09:24Z | 1,912,516 | 277 | 2009-12-16T05:30:15Z | [
"python",
"xml"
] | I have many rows in a database that contains xml and I'm trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like:
```
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
```
How ... | [`minidom`](https://docs.python.org/3/library/xml.dom.minidom.html) is the quickest and pretty straight forward:
XML:
```
<data>
<items>
<item name="item1"></item>
<item name="item2"></item>
<item name="item3"></item>
<item name="item4"></item>
</items>
</data>
```
PYTHON:
``... |
How do I parse XML in Python? | 1,912,434 | 522 | 2009-12-16T05:09:24Z | 1,913,809 | 31 | 2009-12-16T10:42:24Z | [
"python",
"xml"
] | I have many rows in a database that contains xml and I'm trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like:
```
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
```
How ... | [lxml.objectify](http://lxml.de/objectify.html) is really simple.
Taking your sample text:
```
from lxml import objectify
from collections import defaultdict
count = defaultdict(int)
root = objectify.fromstring(text)
for item in root.bar.type:
count[item.attrib.get("foobar")] += 1
print dict(count)
```
Outpu... |
How do I parse XML in Python? | 1,912,434 | 522 | 2009-12-16T05:09:24Z | 17,535,533 | 8 | 2013-07-08T20:35:26Z | [
"python",
"xml"
] | I have many rows in a database that contains xml and I'm trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like:
```
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
```
How ... | Here a very simple but effective code using `cElementTree`.
```
try:
import cElementTree as ET
except ImportError:
try:
# Python 2.5 need to import a different module
import xml.etree.cElementTree as ET
except ImportError:
exit_err("Failed to import cElementTree from any known place")
def fi... |
How do I parse XML in Python? | 1,912,434 | 522 | 2009-12-16T05:09:24Z | 19,302,655 | 53 | 2013-10-10T17:44:17Z | [
"python",
"xml"
] | I have many rows in a database that contains xml and I'm trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like:
```
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
```
How ... | There are many options out there. [cElementTree](http://effbot.org/zone/celementtree.htm) looks excellent if speed and memory usage are an issue. It has very little overhead compared to simply reading in the file using `readlines`.
The relevant metrics can be found in the table below, copied from the [cElementTree](ht... |
How do I parse XML in Python? | 1,912,434 | 522 | 2009-12-16T05:09:24Z | 24,183,790 | 20 | 2014-06-12T11:57:29Z | [
"python",
"xml"
] | I have many rows in a database that contains xml and I'm trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like:
```
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
```
How ... | I suggest [xmltodict](https://pypi.python.org/pypi/xmltodict) for simplicity.
It parses your xml to an OrderedDict;
```
>>> e = '<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo> '
>>> import xmltodict
>>> result = xmltodict.parse(e)
>... |
A question on python GIL | 1,912,557 | 2 | 2009-12-16T05:43:19Z | 1,912,607 | 10 | 2009-12-16T05:58:56Z | [
"python",
"multithreading",
"gil"
] | Does the presence of python GIL imply that in python multi threading the **same** operation is not so different from repeating it in a single thread?.
For example, If I need to upload two files, what is the advantage of doing them in two threads instead of uploading them one after another?.
I tried a big math operati... | Python's threads get a slightly worse rap than they deserve. There are three (well, 2.5) cases where they actually get you benefits:
* If non-Python code (e.g. a C library, the kernel, etc.) is running, other Python threads can continue executing. It's only pure Python code that can't run in two threads at once. So if... |
Python library to detect if a file has changed between different runs? | 1,912,567 | 4 | 2009-12-16T05:45:36Z | 1,912,614 | 7 | 2009-12-16T06:01:45Z | [
"python",
"file"
] | Suppose I have a program A. I run it, and performs some operation starting from a file foo.txt. Now A terminates.
New run of A. It checks if the file foo.txt has changed. If the file has changed, A runs its operation again, otherwise, it quits.
Does a library function/external library for this exists ?
Of course it ... | It's unlikely that someone made a library for something so simple. Solution in 13 lines:
```
import pickle
import md5
try:
l = pickle.load(open("db"))
except IOError:
l = []
db = dict(l)
path = "/etc/hosts"
checksum = md5.md5(open(path).read())
if db.get(path, None) != checksum:
print "file changed"
db... |
IronPython: What kind of jobs you ever done with IronPython instead of standard .NET languages (e.g., C#) | 1,912,971 | 8 | 2009-12-16T07:36:11Z | 1,913,008 | 9 | 2009-12-16T07:49:01Z | [
"python",
"ironpython"
] | I am learning IronPython along wiht Python. I'm curious **what kinds of tasks** you tend to use IronPython to tackle more often than standard .NET languages.
Thanks for any example. | One example that is a perfect match for IronPython is when you want to include scriptability in your application. I have been working on systems where the user can interact with the whole application class model directly through the in-app python scripting layer and it allows for a great deal of flexibility for advance... |
Speedup writing C programs using a subset of the Python syntax | 1,913,837 | 5 | 2009-12-16T10:48:52Z | 1,913,945 | 7 | 2009-12-16T11:06:30Z | [
"python",
"c",
"vim",
"syntax",
"scripting"
] | I am constantly trying to optimize my time. Writing a C code takes a lot of time and requires much more keyboard touches than say writing a Python program.
However, in order to speed up the time required to create a C program, one can automatize many things. I'd like to write my programs using smth. like Python but wi... | Cython is designed to write python extensions, not full-fledged programs. The same is true for Pyrex.
Even though it's quite different from your example, [PyPy](http://codespeak.net/pypy/) might be what you're looking for. It uses a Python subset (called RPython, a kind of more statical python) to generate code to dif... |
Python performance characteristics | 1,913,906 | 13 | 2009-12-16T10:58:41Z | 1,915,951 | 20 | 2009-12-16T16:40:18Z | [
"python",
"performance"
] | I'm in the process of tuning a pet project of mine to improve its performance. I've already busted out the profiler to identify hotspots but I'm thinking understanding Pythons performance characteristics a little better would be quite useful going forward.
There are a few things I'd like to know:
# How smart is its o... | Python's compiler is deliberately dirt-simple -- this makes it fast and highly predictable. Apart from some constant folding, it basically generates bytecode that faithfully mimics your sources. Somebody else already suggested [dis](http://docs.python.org/library/dis.html?highlight=dis#module-dis), and it's indeed a go... |
Why there are not any real lightweight threads for python? | 1,914,341 | 9 | 2009-12-16T12:20:42Z | 1,914,362 | 22 | 2009-12-16T12:25:57Z | [
"python",
"multithreading",
"pthreads"
] | I'm new to Python and seems that the multiprocessing and threads module are not very interesting and suffer from the same problems such as threads in Perl. Is there a technical reason why the interpreter can't use lightweight threads such as posix threads to make an efficient thread implementation that really runs on s... | It *is* using POSIX threads. The problem is the [GIL](http://www.dabeaz.com/python/GIL.pdf).
Note that the GIL is not part of the Python spec --- it's part of the CPython reference implementation. Jython, for example, does not suffer from this problem.
That said, looked into [Stackless](https://bitbucket.org/stackles... |
What does Python's GIL have to do with the garbage collector? | 1,914,605 | 10 | 2009-12-16T13:16:57Z | 1,914,762 | 15 | 2009-12-16T13:51:19Z | [
"python",
"garbage-collection",
"gil",
"unladen-swallow"
] | I just saw [this section of Unladen Swallow's documentation](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan#Global%5FInterpreter%5FLock) come up on Hacker News. Basically, it's the Google engineers saying that they're not optimistic about removing the GIL. However, it seems as though there is discussion abou... | The really short version is that currently python manages memory with a reference counting+a mark&sweep cycle collector scheme, optimized for latency (instead of throughput).
This is all fine when there is only a single mutating thread, but in a multi-threaded system, you need to synchronize all the times you modify r... |
Alphabetizing functions in a Python class | 1,914,761 | 4 | 2009-12-16T13:51:00Z | 1,914,795 | 10 | 2009-12-16T13:57:11Z | [
"python",
"class",
"visualization",
"publishing",
"alphabetized"
] | Warning, this is a sheer-laziness query! As my project develops, so also do the number of functions within a class. I also have a number of classes per .py file. So what I would like to do is re-sort them to that the function names are organised [sorry, UK here, I've already compromised hugely with the 'z' in Alphabeti... | I don't have a solution to your question, but I have a very strong opinion: if the number of methods in your classes becomes so large you have trouble finding them, you should consider reducing the number, perhaps by splitting the class into smaller ones.
The same principles of cohesion that apply to functions and met... |
split a generator/iterable every n items in python (splitEvery) | 1,915,170 | 16 | 2009-12-16T14:58:28Z | 1,915,307 | 25 | 2009-12-16T15:21:05Z | [
"python",
"iterator",
"split"
] | I'm trying to write the Haskel function 'splitEvery' in Python. Here is it's definition:
```
splitEvery :: Int -> [e] -> [[e]]
@'splitEvery' n@ splits a list into length-n pieces. The last
piece will be shorter if @n@ does not evenly divide the length of
the list.
```
The basic version of this works fine... | ```
from itertools import islice
def split_every(n, iterable):
i = iter(iterable)
piece = list(islice(i, n))
while piece:
yield piece
piece = list(islice(i, n))
```
Some tests:
```
>>> list(split_every(5, range(9)))
[[0, 1, 2, 3, 4], [5, 6, 7, 8]]
>>> list(split_every(3, (x**2 for x in r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.