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
'for' loop through form fields and excluding one of the fields with 'if'
710,100
3
2009-04-02T15:05:31Z
710,146
7
2009-04-02T15:14:10Z
[ "python", "django-templates" ]
The problem I'm struggling with is as follows: I have: ``` {% for field in form %} {{ field }} {% end for %} ``` What I want is to put an 'if' statement to exclude a field which .label or whatever is provided. Like: ``` {% for field in form%} {% if field == title %} {% else %} {{ field }} {...
Yes, this should be possible: ``` {% for field in form %} {% ifnotequal field.label title %} {{ field }} {% endifnotequal %} {% endfor %} ``` Django's [template tags](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ref-templates-builtins) offer `ifequal` and `ifnotequal` variants, and you...
'import module' or 'from module import'
710,551
138
2009-04-02T16:40:49Z
710,598
27
2009-04-02T16:50:35Z
[ "python", "python-import" ]
I've tried to find a comprehensive guide on whether it is best to use `import module` or `from module import`. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind. Basically, I was hoping if anyone could share their exper...
Both ways are supported for a reason: there are times when one is more appropriate than the other. import module: nice when you are using many bits from the module. drawback is that you'll need to qualify each reference with the module name. from module import ...: nice that imported items are usable directly without...
'import module' or 'from module import'
710,551
138
2009-04-02T16:40:49Z
710,603
181
2009-04-02T16:52:11Z
[ "python", "python-import" ]
I've tried to find a comprehensive guide on whether it is best to use `import module` or `from module import`. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind. Basically, I was hoping if anyone could share their exper...
The difference between `import module` and `from module import foo` is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide. `import module` * **Pros:** + Less maintenance of your `import` statements. Don't need to add any additional imports to s...
'import module' or 'from module import'
710,551
138
2009-04-02T16:40:49Z
710,606
9
2009-04-02T16:52:49Z
[ "python", "python-import" ]
I've tried to find a comprehensive guide on whether it is best to use `import module` or `from module import`. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind. Basically, I was hoping if anyone could share their exper...
``` import module ``` Is best when you will use many functions from the module. ``` from module import function ``` Is best when you want to avoid polluting the global namespace with all the functions and types from a module when you only need `function`.
'import module' or 'from module import'
710,551
138
2009-04-02T16:40:49Z
710,656
24
2009-04-02T17:03:54Z
[ "python", "python-import" ]
I've tried to find a comprehensive guide on whether it is best to use `import module` or `from module import`. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind. Basically, I was hoping if anyone could share their exper...
I personally always use ``` from package.subpackage.subsubpackage import module ``` and then access everything as ``` module.function module.modulevar ``` etc. The reason is that at the same time you have short invocation, and you clearly define the module namespace of each routine, something that is very useful if...
'import module' or 'from module import'
710,551
138
2009-04-02T16:40:49Z
19,185,936
11
2013-10-04T16:10:12Z
[ "python", "python-import" ]
I've tried to find a comprehensive guide on whether it is best to use `import module` or `from module import`. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind. Basically, I was hoping if anyone could share their exper...
There's another detail here, not mentioned, related to writing to a module. Granted this may not be very common, but I've needed it from time to time. Due to the way references and name binding works in Python, if you want to update some symbol in a module, say foo.bar, from outside that module, and have other importi...
'import module' or 'from module import'
710,551
138
2009-04-02T16:40:49Z
21,547,583
11
2014-02-04T08:40:54Z
[ "python", "python-import" ]
I've tried to find a comprehensive guide on whether it is best to use `import module` or `from module import`. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind. Basically, I was hoping if anyone could share their exper...
Already many people explained about `import` vs `from`, even I want to try to explain a bit more under the hood, where are all the places it got changes: **First of all let me explain:** **import X :** ``` imports the module X, and creates a reference to that module in the current namespace. Then you need to define ...
Checking a Python module version at runtime
710,609
94
2009-04-02T16:53:08Z
4,939,465
203
2011-02-08T22:54:17Z
[ "python", "module", "version" ]
Many third-party Python modules have an attribute which holds the version information for the module (usually something like `module.VERSION` or `module.__version__`), however some do not. Particular examples of such modules are libxslt and libxml2. I need to check that the correct version of these modules are being ...
Use [pkg\_resources](https://pythonhosted.org/setuptools/pkg_resources.html). Anything installed from PyPI at least should have a version number. ``` >>> import pkg_resources >>> pkg_resources.get_distribution("blogofile").version '0.7.1' ```
Changing element value with BeautifulSoup returns empty element
711,376
2
2009-04-02T20:04:38Z
711,405
8
2009-04-02T20:09:42Z
[ "python", "xml", "parsing", "beautifulsoup" ]
``` from BeautifulSoup import BeautifulStoneSoup xml_data = """ <doc> <test>test</test> <foo:bar>Hello world!</foo:bar> </doc> """ soup = BeautifulStoneSoup(xml_data) print soup.prettify() make = soup.find('foo:bar') print make # prints <foo:bar>Hello world!</foo:bar> make.contents = ['Top of the world Ma!'] pri...
Check out the [documentation on `replaceWith`](http://www.crummy.com/software/BeautifulSoup/documentation.html#Replacing%20one%20Element%20with%20Another). This works: ``` make.contents[0].replaceWith('Top of the world Ma!') ```
Python naming conventions for modules
711,884
62
2009-04-02T22:31:35Z
711,892
80
2009-04-02T22:34:41Z
[ "python", "naming-conventions" ]
I have a module whose purpose is to define a class called "nib". (and a few related classes too.) How should I call the module itself? "nib"? "nibmodule"? Anything else?
Just nib. Name the class Nib, with a capital N. For more on naming conventions and other style advice, see [PEP 8](https://www.python.org/dev/peps/pep-0008/#package-and-module-names), the Python style guide.
Python naming conventions for modules
711,884
62
2009-04-02T22:31:35Z
711,908
25
2009-04-02T22:40:32Z
[ "python", "naming-conventions" ]
I have a module whose purpose is to define a class called "nib". (and a few related classes too.) How should I call the module itself? "nib"? "nibmodule"? Anything else?
I would call it nib.py. And I would also name the class Nib. In a larger python project I'm working on, we have lots of modules defining basically one important class. Classes are named beginning with a capital letter. The modules are named like the class in lowercase. This leads to imports like the following: ``` fr...
Python naming conventions for modules
711,884
62
2009-04-02T22:31:35Z
711,910
19
2009-04-02T22:41:13Z
[ "python", "naming-conventions" ]
I have a module whose purpose is to define a class called "nib". (and a few related classes too.) How should I call the module itself? "nib"? "nibmodule"? Anything else?
nib is fine. If in doubt, refer to the Python style guide. From [PEP 8](http://www.python.org/dev/peps/pep-0008/): > Package and Module Names > Modules should have short, all-lowercase names. Underscores can be used > in the module name if it improves readability. Python packages should > also have short, all-lowerca...
Python naming conventions for modules
711,884
62
2009-04-02T22:31:35Z
712,035
24
2009-04-02T23:33:04Z
[ "python", "naming-conventions" ]
I have a module whose purpose is to define a class called "nib". (and a few related classes too.) How should I call the module itself? "nib"? "nibmodule"? Anything else?
I know my solution is not very popular from the pythonic point of view, but I prefer to use the Java approach of one module->one class, with the module named as the class. I do understand the reason behind the python style, but I am not too fond of having a very large file containing a lot of classes. I find it difficu...
List all Tests Found by Nosetest
712,020
28
2009-04-02T23:27:37Z
1,151,294
34
2009-07-20T00:32:07Z
[ "python", "unit-testing", "nose", "nosetests" ]
I use `nosetests` to run my unittests and it works well. I want to get a list of all the tests `nostests` finds without actually running them. Is there a way to do that?
Version 0.11.1 is currently available. You can get a list of tests without running them as follows: ``` nosetests -v --collect-only ```
List all Tests Found by Nosetest
712,020
28
2009-04-02T23:27:37Z
3,448,487
15
2010-08-10T11:37:31Z
[ "python", "unit-testing", "nose", "nosetests" ]
I use `nosetests` to run my unittests and it works well. I want to get a list of all the tests `nostests` finds without actually running them. Is there a way to do that?
I recommend using: ``` nosetests -vv --collect-only ``` While the `-vv` option is not described in `man nosetests`, ["An Extended Introduction to the nose Unit Testing Framework"](http://ivory.idyll.org/articles/nose-intro.html) states that: > Using the -vv flag gives you verbose output from nose's test discovery al...
Interpreting Number Ranges in Python
712,460
4
2009-04-03T03:33:41Z
712,483
11
2009-04-03T03:42:56Z
[ "python", "numeric-ranges" ]
In a Pylons webapp, I need to take a string such as "<3, 45, 46, 48-51, 77" and create a list of ints (which are actually IDs of objects) to search on. Any suggestions on ways to do this? I'm new to Python, and I haven't found anything out there that helps with this kind of thing. The list would be: [1, 2, 3, 45, 46,...
Use parseIntSet from [here](http://thoughtsbyclayg.blogspot.com/2008/10/parsing-list-of-numbers-in-python.html) I also like the pyparsing implementation in the comments at the end. The parseIntSet has been modified here to handle "<3"-type entries and to only spit out the invalid strings if there are any. ``` #! /us...
Using CSV as a mutable database?
712,510
4
2009-04-03T04:02:50Z
712,521
15
2009-04-03T04:11:14Z
[ "python", "csv" ]
Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLi...
**Don't walk, run to get a new host immediately**. If your host won't even get you the most basic of free databases, it's time for a change. There are many fish in the sea. At the very least I'd recommend an xml data store rather than a csv. [My blog](http://chrisballance.com) uses an xml data provider and I haven't h...
What are the differences between json and simplejson Python modules?
712,791
289
2009-04-03T06:56:13Z
712,799
305
2009-04-03T06:59:11Z
[ "python", "json", "simplejson" ]
I have seen many projects using **`simplejson`** module instead of **`json`** module from the Standard Library. Also, there are many different `simplejson` modules. Why would use these alternatives, instead of the one in the Standard Library?
`json` [is](http://docs.python.org/whatsnew/2.6.html#the-json-module-javascript-object-notation) `simplejson`, added to the stdlib. But since `json` was added in 2.6, `simplejson` has the advantage of working on more Python versions (2.4+). `simplejson` is also updated more frequently than Python, so if you need (or w...
What are the differences between json and simplejson Python modules?
712,791
289
2009-04-03T06:56:13Z
4,833,752
18
2011-01-28T22:39:38Z
[ "python", "json", "simplejson" ]
I have seen many projects using **`simplejson`** module instead of **`json`** module from the Standard Library. Also, there are many different `simplejson` modules. Why would use these alternatives, instead of the one in the Standard Library?
I've been benchmarking json, simplejson and cjson. * cjson is fastest * simplejson is almost on par with cjson * json is about 10x slower than simplejson <http://pastie.org/1507411>: ``` $ python test_serialization_speed.py -------------------- Encoding Tests -------------------- Encoding: 100000 x {'m': 'asdsas...
What are the differences between json and simplejson Python modules?
712,791
289
2009-04-03T06:56:13Z
16,131,316
67
2013-04-21T12:53:31Z
[ "python", "json", "simplejson" ]
I have seen many projects using **`simplejson`** module instead of **`json`** module from the Standard Library. Also, there are many different `simplejson` modules. Why would use these alternatives, instead of the one in the Standard Library?
I have to disagree with the other answers: the built in **`json`** library (in Python 2.7) is not necessarily slower than **`simplejson`**. It also doesn't have [this annoying unicode bug](https://code.google.com/p/simplejson/issues/detail?id=40). Here is a simple benchmark: ``` import json import simplejson from tim...
What are the differences between json and simplejson Python modules?
712,791
289
2009-04-03T06:56:13Z
17,823,905
17
2013-07-24T01:48:06Z
[ "python", "json", "simplejson" ]
I have seen many projects using **`simplejson`** module instead of **`json`** module from the Standard Library. Also, there are many different `simplejson` modules. Why would use these alternatives, instead of the one in the Standard Library?
All of these answers aren't very helpful because they are **time sensitive**. After doing some research of my own I found that `simplejson` is indeed faster than the builtin, **if** you keep it updated to the latest version. `pip/easy_install` wanted to install 2.3.2 on ubuntu 12.04, but after finding out the latest ...
Getting the docstring from a function
713,138
75
2009-04-03T09:04:09Z
713,143
108
2009-04-03T09:05:57Z
[ "python" ]
I have the following function: ``` def my_func(): """My docstring is both funny and informative""" pass ``` How do I get access to the docstring?
Interactively, you can display it with ``` help(my_func) ``` Or from code you can retrieve it with ``` my_func.__doc__ ```
Getting the docstring from a function
713,138
75
2009-04-03T09:04:09Z
5,915,733
40
2011-05-06T18:47:14Z
[ "python" ]
I have the following function: ``` def my_func(): """My docstring is both funny and informative""" pass ``` How do I get access to the docstring?
You can also use [inspect.getdoc](http://docs.python.org/library/inspect.html#inspect.getdoc). It cleans up the \_\_doc\_\_ by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.
Catching an exception while using a Python 'with' statement
713,794
129
2009-04-03T13:00:25Z
713,814
126
2009-04-03T13:04:32Z
[ "python", "exception-handling" ]
To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code: ``` with open("a.txt") as f: print f.readlines() ``` I really want to handle 'file not found exception' in order to do somehing. But I can't write ``` with open("a.txt") as f: print f.readlines() except: ...
``` from __future__ import with_statement try: with open( "a.txt" ) as f : print f.readlines() except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available print 'oops' ``` If you want different handling for errors from the open call vs the working code you could do: ``` t...
Catching an exception while using a Python 'with' statement
713,794
129
2009-04-03T13:00:25Z
6,090,497
38
2011-05-22T20:13:04Z
[ "python", "exception-handling" ]
To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code: ``` with open("a.txt") as f: print f.readlines() ``` I really want to handle 'file not found exception' in order to do somehing. But I can't write ``` with open("a.txt") as f: print f.readlines() except: ...
The best "Pythonic" way to do this, exploiting the `with` statement, is listed as Example #6 in [PEP 343](http://www.python.org/dev/peps/pep-0343/), which gives the background of the statement. ``` @contextmanager def opened_w_error(filename, mode="r"): try: f = open(filename, mode) except IOError, err...
How can I generate a screenshot of a webpage using a server-side script?
713,938
18
2009-04-03T13:35:52Z
713,952
7
2009-04-03T13:39:42Z
[ "php", "python", "screenshot", "server-side-scripting" ]
I need a server-side script (PHP, Python) to capture a webpage to a PNG, JPG, Tiff, GIF image and resize them to a thumbnail. What is the best way to accomplish this? ### See also: > * [Web Page Screenshots with PHP?](http://stackoverflow.com/questions/686858/web-page-screenshots-with-php) > * [How can I take a scre...
What needs to happen is for a program to render the page and then take an image of the page. This is a very slow and heavy process but it [can be done in PHP on Windows.](http://is.php.net/manual/en/function.imagegrabscreen.php) Also check the comments in the documentation article. For python [I'd recommend reading t...
How can I generate a screenshot of a webpage using a server-side script?
713,938
18
2009-04-03T13:35:52Z
713,975
13
2009-04-03T13:46:41Z
[ "php", "python", "screenshot", "server-side-scripting" ]
I need a server-side script (PHP, Python) to capture a webpage to a PNG, JPG, Tiff, GIF image and resize them to a thumbnail. What is the best way to accomplish this? ### See also: > * [Web Page Screenshots with PHP?](http://stackoverflow.com/questions/686858/web-page-screenshots-with-php) > * [How can I take a scre...
You can probably write something similar to [webkit2png](http://www.paulhammond.org/webkit2png/), unless your server already runs Mac OS X. **UPDATE:** I just saw the link to its Linux equivalent: [khtml2png](http://khtml2png.sourceforge.net/) See also: * [Create screenshots of a web page using Python and QtWebKit](...
Importing modules from parent folder
714,063
197
2009-04-03T14:08:02Z
714,070
40
2009-04-03T14:09:23Z
[ "python", "module", "folders", "python-import" ]
I am running Python 2.5. This is my folder tree: ``` ptdraft/ nib.py simulations/ life/ life.py ``` (I also have `__init__.py` in each folder, omitted here for readability) How do I import the `nib` module from inside the `life` module? I am hoping it is possible to do without tinkering with sys.path....
What's wrong with just `import ptdraft.nib` ### Update: It seems that the problem is not related to the module being in a parent directory or anything like that. You need to add the directory that contains `ptdraft` to PYTHONPATH You said that `import nib` worked with you, that probably means that you added `ptdraf...
Importing modules from parent folder
714,063
197
2009-04-03T14:08:02Z
714,647
359
2009-04-03T16:17:27Z
[ "python", "module", "folders", "python-import" ]
I am running Python 2.5. This is my folder tree: ``` ptdraft/ nib.py simulations/ life/ life.py ``` (I also have `__init__.py` in each folder, omitted here for readability) How do I import the `nib` module from inside the `life` module? I am hoping it is possible to do without tinkering with sys.path....
You could use relative imports (python >= 2.5): ``` from ... import nib ``` [(What’s New in Python 2.5) PEP 328: Absolute and Relative Imports](http://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports) **EDIT**: added another dot '.' to go up two packages
Importing modules from parent folder
714,063
197
2009-04-03T14:08:02Z
9,331,002
18
2012-02-17T15:30:55Z
[ "python", "module", "folders", "python-import" ]
I am running Python 2.5. This is my folder tree: ``` ptdraft/ nib.py simulations/ life/ life.py ``` (I also have `__init__.py` in each folder, omitted here for readability) How do I import the `nib` module from inside the `life` module? I am hoping it is possible to do without tinkering with sys.path....
If adding your module folder to the PYTHONPATH didn't work, You can modify the **sys.path** list in your program where the Python interpreter searches for the modules to import, the [python documentation](http://docs.python.org/tutorial/modules.html#the-module-search-path) says: > When a module named **spam** is impor...
Importing modules from parent folder
714,063
197
2009-04-03T14:08:02Z
11,158,224
90
2012-06-22T14:30:07Z
[ "python", "module", "folders", "python-import" ]
I am running Python 2.5. This is my folder tree: ``` ptdraft/ nib.py simulations/ life/ life.py ``` (I also have `__init__.py` in each folder, omitted here for readability) How do I import the `nib` module from inside the `life` module? I am hoping it is possible to do without tinkering with sys.path....
Relative imports (as in `from .. import mymodule`) only work in a package. To import 'mymodule' that is in the parent directory of your current module: ``` import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.inser...
Importing modules from parent folder
714,063
197
2009-04-03T14:08:02Z
21,784,070
15
2014-02-14T16:09:22Z
[ "python", "module", "folders", "python-import" ]
I am running Python 2.5. This is my folder tree: ``` ptdraft/ nib.py simulations/ life/ life.py ``` (I also have `__init__.py` in each folder, omitted here for readability) How do I import the `nib` module from inside the `life` module? I am hoping it is possible to do without tinkering with sys.path....
Here is more generic solution that includes the parent directory into sys.path (works for me): ``` import os.path, sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) ```
Importing modules from parent folder
714,063
197
2009-04-03T14:08:02Z
28,712,742
14
2015-02-25T06:37:47Z
[ "python", "module", "folders", "python-import" ]
I am running Python 2.5. This is my folder tree: ``` ptdraft/ nib.py simulations/ life/ life.py ``` (I also have `__init__.py` in each folder, omitted here for readability) How do I import the `nib` module from inside the `life` module? I am hoping it is possible to do without tinkering with sys.path....
You can use OS depending path in "module search path" which is listed in **sys.path** . So you can easily add parent directory like following ``` import sys sys.path.insert(0,'..') ``` If you want to add parent-parent directory, ``` sys.path.insert(0,'../..') ```
Importing modules from parent folder
714,063
197
2009-04-03T14:08:02Z
33,532,002
7
2015-11-04T21:06:30Z
[ "python", "module", "folders", "python-import" ]
I am running Python 2.5. This is my folder tree: ``` ptdraft/ nib.py simulations/ life/ life.py ``` (I also have `__init__.py` in each folder, omitted here for readability) How do I import the `nib` module from inside the `life` module? I am hoping it is possible to do without tinkering with sys.path....
Using information from this Stack Overflow answer, "[How do I get the path of the current executed file in python?](http://stackoverflow.com/questions/2632199/how-do-i-get-the-path-of-the-current-executed-file-in-python/18489147#18489147)", here is a short, simple, hopefully easy to understand answer. It is also quite ...
What is a maximum number of arguments in a Python function?
714,475
21
2009-04-03T15:32:14Z
714,518
17
2009-04-03T15:44:51Z
[ "python", "function", "arguments", "language-features", "limit" ]
It's somewhat common knowledge that Python functions can have a maximum of 256 arguments. What I'm curious to know is if this limit applies to `*args` and `**kwargs` when they're unrolled in the following manner: ``` items = [1,2,3,4,5,6] def do_something(*items): pass ``` I ask because, hypothetically, there mi...
WFM ``` >>> fstr = 'def f(%s): pass'%(', '.join(['arg%d'%i for i in range(5000)])) >>> exec(fstr) >>> f <function f at 0x829bae4> ``` **Update:** as Brian noticed, the limit is on the calling side: ``` >>> exec 'f(' + ','.join(str(i) for i in range(5000)) + ')' Traceback (most recent call last): File "<pyshell#63...
What is a maximum number of arguments in a Python function?
714,475
21
2009-04-03T15:32:14Z
8,932,175
18
2012-01-19T19:36:03Z
[ "python", "function", "arguments", "language-features", "limit" ]
It's somewhat common knowledge that Python functions can have a maximum of 256 arguments. What I'm curious to know is if this limit applies to `*args` and `**kwargs` when they're unrolled in the following manner: ``` items = [1,2,3,4,5,6] def do_something(*items): pass ``` I ask because, hypothetically, there mi...
The limit is due to how the compiled bytecode treats calling a function with position arguments and/or keyword arguments. The bytecode op of concern is CALL\_FUNCTION which carries an op\_arg that is 4 bytes in length, but on the two least significant bytes are used. Of those, the most significant byte represent the n...
How to include external Python code to use in other files?
714,881
86
2009-04-03T17:21:58Z
714,889
30
2009-04-03T17:24:10Z
[ "python" ]
If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)? So if I have: ``` [Math.py] def Calculate ( num ) ``` How do I call it like this: ``` [Tool.py] using Math.py for i in range ( 5 ) : Calculate ( i ) ```
If you use: ``` import Math ``` then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want. If you want to import a module's functions without having to prefix them, you must explicitly name them, like: ``` from Math import Calculate, Add, Subtract ```...
How to include external Python code to use in other files?
714,881
86
2009-04-03T17:21:58Z
714,890
129
2009-04-03T17:24:28Z
[ "python" ]
If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)? So if I have: ``` [Math.py] def Calculate ( num ) ``` How do I call it like this: ``` [Tool.py] using Math.py for i in range ( 5 ) : Calculate ( i ) ```
You will need to import the other file as a module like this: ``` import Math ``` If you don't want to prefix your `Calculate` function with the module name then do this: ``` from Math import Calculate ``` If you want to import all members of a module then do this: ``` from Math import * ``` **Edit:** [Here is a ...
How to include external Python code to use in other files?
714,881
86
2009-04-03T17:21:58Z
16,604,453
32
2013-05-17T08:15:42Z
[ "python" ]
If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)? So if I have: ``` [Math.py] def Calculate ( num ) ``` How do I call it like this: ``` [Tool.py] using Math.py for i in range ( 5 ) : Calculate ( i ) ```
Just write the "include" command : ``` import os def include(filename): if os.path.exists(filename): execfile(filename) include('myfile.py') ``` @Deleet : @bfieck remark is correct, for python 2 and 3 compatibility, you need either : Python 2 and 3: alternative 1 ``` from past.builtins import execf...
python dict update diff
715,234
5
2009-04-03T19:04:34Z
715,314
10
2009-04-03T19:23:17Z
[ "python", "diff", "dictionary" ]
Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this: ``` >>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'} >>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'} >>> a.diff(b) {'c':'pepsi', 'd':'ice ...
No, but you can subclass dict to provide notification on change. ``` class ObservableDict( dict ): def __init__( self, *args, **kw ): self.observers= [] super( ObservableDict, self ).__init__( *args, **kw ) def observe( self, observer ): self.observers.append( observer ) def __setit...
python dict update diff
715,234
5
2009-04-03T19:04:34Z
2,904,335
7
2010-05-25T12:02:03Z
[ "python", "diff", "dictionary" ]
Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this: ``` >>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'} >>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'} >>> a.diff(b) {'c':'pepsi', 'd':'ice ...
## one year later I like the following solution: ``` >>> def dictdiff(d1, d2): return dict(set(d2.iteritems()) - set(d1.iteritems())) ... >>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'} >>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'} >>> dictdiff(a, b) {'c...
How do I iterate over all lines of files passed on the command line?
715,277
16
2009-04-03T19:15:37Z
715,282
35
2009-04-03T19:17:06Z
[ "python", "stdin" ]
I usually do this in Perl: whatever.pl ``` while(<>) { #do whatever; } ``` then `cat foo.txt | whatever.pl` Now, I want to do this in Python. I tried `sys.stdin` but I have no idea how to do as I have done in Perl. How can I read the input?
Try this: ``` import fileinput for line in fileinput.input(): process(line) ```
How do I iterate over all lines of files passed on the command line?
715,277
16
2009-04-03T19:15:37Z
715,300
10
2009-04-03T19:19:50Z
[ "python", "stdin" ]
I usually do this in Perl: whatever.pl ``` while(<>) { #do whatever; } ``` then `cat foo.txt | whatever.pl` Now, I want to do this in Python. I tried `sys.stdin` but I have no idea how to do as I have done in Perl. How can I read the input?
``` import sys def main(): for line in sys.stdin: print line if __name__=='__main__': sys.exit(main()) ```
Converting from a string to boolean in Python?
715,417
258
2009-04-03T19:44:20Z
715,455
361
2009-04-03T19:52:56Z
[ "python", "string" ]
Does anyone know how to do convert from a string to a boolean in Python? I found [this link](http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/). But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc. EDIT: The reason I asked this is becaus...
Really, you just compare the string to whatever you expect to accept as representing true, so you can do this: ``` s == 'True' ``` Or to checks against a whole bunch of values: ``` s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh'] ``` Be cautious when using the following: ``` >>> bool("foo"...
Converting from a string to boolean in Python?
715,417
258
2009-04-03T19:44:20Z
715,468
152
2009-04-03T19:56:44Z
[ "python", "string" ]
Does anyone know how to do convert from a string to a boolean in Python? I found [this link](http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/). But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc. EDIT: The reason I asked this is becaus...
``` def str2bool(v): return v.lower() in ("yes", "true", "t", "1") ``` Then call it like so: ``` str2bool("yes") ``` `> True` ``` str2bool("no") ``` `> False` ``` str2bool("stuff") ``` `> False` ``` str2bool("1") ``` `> True` ``` str2bool("0") ``` `> False` --- **Handling true and false explicitly:** Yo...
Converting from a string to boolean in Python?
715,417
258
2009-04-03T19:44:20Z
922,374
77
2009-05-28T18:06:39Z
[ "python", "string" ]
Does anyone know how to do convert from a string to a boolean in Python? I found [this link](http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/). But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc. EDIT: The reason I asked this is becaus...
Starting with Python 2.6, there is now `ast.literal_eval`: ``` >>> import ast >>> help(ast.literal_eval) Help on function literal_eval in module ast: literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the...
Converting from a string to boolean in Python?
715,417
258
2009-04-03T19:44:20Z
9,333,816
11
2012-02-17T18:57:43Z
[ "python", "string" ]
Does anyone know how to do convert from a string to a boolean in Python? I found [this link](http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/). But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc. EDIT: The reason I asked this is becaus...
Here's is my version. It checks against both positive and negative values lists, raising an exception for unknown values. And it does not receive a string, but any type should do. ``` def to_bool(value): """ Converts 'something' to boolean. Raises exception for invalid formats Possible True valu...
Converting from a string to boolean in Python?
715,417
258
2009-04-03T19:44:20Z
13,706,457
35
2012-12-04T15:38:14Z
[ "python", "string" ]
Does anyone know how to do convert from a string to a boolean in Python? I found [this link](http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/). But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc. EDIT: The reason I asked this is becaus...
The JSON parser is also useful for in general converting strings to reasonable python types. ``` >>> import json >>> json.loads("false") False >>> json.loads("true") True ```
Converting from a string to boolean in Python?
715,417
258
2009-04-03T19:44:20Z
18,472,142
81
2013-08-27T17:42:22Z
[ "python", "string" ]
Does anyone know how to do convert from a string to a boolean in Python? I found [this link](http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/). But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc. EDIT: The reason I asked this is becaus...
Just use: ``` distutils.util.strtobool(some_string) ``` <http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool> > True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.
Converting from a string to boolean in Python?
715,417
258
2009-04-03T19:44:20Z
19,015,368
9
2013-09-25T21:16:55Z
[ "python", "string" ]
Does anyone know how to do convert from a string to a boolean in Python? I found [this link](http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/). But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc. EDIT: The reason I asked this is becaus...
This version keeps the semantics of constructors like int(value) and provides an easy way to define acceptable string values. ``` def to_bool(value): valid = {'true': True, 't': True, '1': True, 'false': False, 'f': False, '0': False, } if isinstance(value, bool): return v...
Converting from a string to boolean in Python?
715,417
258
2009-04-03T19:44:20Z
25,242,187
8
2014-08-11T11:27:49Z
[ "python", "string" ]
Does anyone know how to do convert from a string to a boolean in Python? I found [this link](http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/). But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc. EDIT: The reason I asked this is becaus...
You can simply use the built-in function [eval()](https://docs.python.org/2/library/functions.html#eval): ``` a='True' if a is True: print 'a is True, a type is', type(a) else: print "a isn't True, a type is", type(a) b = eval(a) if b is True: print 'b is True, b type is', type(b) else: print "b isn't ...
Best way to encode tuples with json
715,550
21
2009-04-03T20:14:25Z
715,601
16
2009-04-03T20:25:57Z
[ "python", "json" ]
In python I have a dictionary that maps tuples to a list of tuples. e.g. `{(1,2): [(2,3),(1,7)]}` I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key. Is the best way to handle this is encode it as "1,2" and then p...
You might consider saying ``` {"[1,2]": [(2,3),(1,7)]} ``` and then when you need to get the value out, you can just parse the keys themselves as JSON objects, which all modern browsers can do with the built-in `JSON.parse` method (I'm using `jQuery.each` to iterate here but you could use anything): ``` var myjson =...
OptionParser - supporting any option at the end of the command line
716,006
5
2009-04-03T22:52:46Z
716,090
13
2009-04-03T23:33:45Z
[ "python", "optparse" ]
I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around `ssh [hostname] [command]`). I want to execute it as such: ``` ./floep [command] ``` However, I need to pass certain command lines from time to time: ``` ./floep -v [command] ``` so I dec...
Try using [`disable_interspersed_args()`](http://docs.python.org/library/optparse.html#other-methods) ``` #!/usr/bin/env python from optparse import OptionParser parser = OptionParser() parser.disable_interspersed_args() parser.add_option("-v", action="store_true", dest="verbose") (options, args) = parser.parse_args(...
Why can't environmental variables set in python persist?
716,011
25
2009-04-03T22:55:29Z
716,046
26
2009-04-03T23:08:47Z
[ "python", "persistence", "environment-variables" ]
I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things: Is this true? and It seems like ...
You can't do it from python, but some clever bash tricks can do something similar. The basic reasoning is this: environment variables exist in a per-process memory space. When a new process is created with fork() it inherits its parent's environment variables. When you set an environment variable in your shell (e.g. ba...
Why can't environmental variables set in python persist?
716,011
25
2009-04-03T22:55:29Z
716,188
16
2009-04-04T00:38:24Z
[ "python", "persistence", "environment-variables" ]
I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things: Is this true? and It seems like ...
One workaround is to output `export` commands, and have the parent shell evaluate this.. `thescript.py`: ``` import pipes import random r = random.randint(1,100) print("export BLAHBLAH=%s" % (pipes.quote(str(r)))) ``` ..and the bash alias (the same can be done in most shells.. even tcsh!): ``` alias setblahblahenv=...
Matrices in Python
716,259
4
2009-04-04T01:21:36Z
716,292
10
2009-04-04T01:38:21Z
[ "python", "matrix" ]
Yesterday I had the need for a matrix type in Python. Apparently, a trivial answer to this need would be to use `numpy.matrix()`, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. `numpy.matrix` does not perform this. An example is ``` >>> n...
You can have inhomogeneous types if your `dtype` is `object`: ``` In [1]: m = numpy.matrix([[1, 2, 3], [4, '5', 6]], dtype=numpy.object) In [2]: m Out[2]: matrix([[1, 2, 3], [4, 5, 6]], dtype=object) In [3]: m[1, 1] Out[3]: '5' In [4]: m[1, 2] Out[4]: 6 ``` I have no idea what good this does you other than f...
My first python program: can you tell me what I'm doing wrong?
716,278
6
2009-04-04T01:27:46Z
716,309
10
2009-04-04T01:46:23Z
[ "python" ]
I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away. I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel. This is just for personal educational purposes. The program works! I...
Usually is preferred that what follows after the end of sentence `:` is in a separate line (also don't add a space before it) ``` if options.verbose: print "" ``` instead of ``` if options.verbose : print "" ``` You don't need to check the len of a list if you are going to iterate over it ``` if len(threadlist) ...
My first python program: can you tell me what I'm doing wrong?
716,278
6
2009-04-04T01:27:46Z
716,388
7
2009-04-04T02:37:51Z
[ "python" ]
I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away. I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel. This is just for personal educational purposes. The program works! I...
Before unloading any criticism, first let me say congratulations on getting your first Python program working. Moving from one language to another can be a chore, constantly fumbling around with syntax issues and hunting through unfamiliar libraries. The most quoted style guideline is [PEP-8](http://www.python.org/dev...
Queue.Queue vs. collections.deque
717,148
85
2009-04-04T14:03:09Z
717,261
142
2009-04-04T15:26:29Z
[ "python", "thread-safety", "queue" ]
I need a queue which multiple threads can put stuff into, and multiple threads may read from. Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation. However, the Queue docs also state: > colle...
`Queue.Queue` and `collections.deque` serve different purposes. Queue.Queue is intended for allowing different threads to communicate using queued messages/data, whereas `collections.deque` is simply intended as a datastructure. That's why `Queue.Queue` has methods like `put_nowait()`, `get_nowait()`, and `join()`, whe...
Queue.Queue vs. collections.deque
717,148
85
2009-04-04T14:03:09Z
20,330,499
18
2013-12-02T14:20:14Z
[ "python", "thread-safety", "queue" ]
I need a queue which multiple threads can put stuff into, and multiple threads may read from. Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation. However, the Queue docs also state: > colle...
If all you're looking for is **a thread-safe way to transfer objects between threads**, then both would work (both for FIFO and LIFO). For FIFO: * [`Queue.put()` and `Queue.get()` are thread-safe](http://docs.python.org/2/library/queue.html#) * [`deque.append()` and `deque.popleft()` are thread-safe](http://docs.pytho...
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
717,506
12
2009-04-04T17:54:50Z
717,527
13
2009-04-04T18:03:18Z
[ "python", "ruby", "language-features", "monkeypatching" ]
In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. Why th...
The languages might permit it, but neither community condones the practice. Monkeypatching isn't condoned in either language, but you hear about it more often in Ruby because the form of open class it uses makes it very, very easy to monkeypatch a class and because of this, [it's more acceptable in the Ruby community, ...
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
717,506
12
2009-04-04T17:54:50Z
717,553
13
2009-04-04T18:17:20Z
[ "python", "ruby", "language-features", "monkeypatching" ]
In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. Why th...
"Does Python include different types of safeguards to minimize the risks of this feature?" Yes. The community refuses to do it. The safeguard is entirely social.
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
717,506
12
2009-04-04T17:54:50Z
717,563
20
2009-04-04T18:22:54Z
[ "python", "ruby", "language-features", "monkeypatching" ]
In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. Why th...
It's a technique less practised in Python, in part because "core" classes in Python (those implemented in C) are not really modifiable. In Ruby, on the other hand, because of the way it's implemented internally (not better, just different) just about anything can be modified dynamically. Philosophically, it's somethin...
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
717,506
12
2009-04-04T17:54:50Z
718,062
16
2009-04-04T23:48:08Z
[ "python", "ruby", "language-features", "monkeypatching" ]
In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. Why th...
As a Python programmer who has had a taste of Ruby (and likes it), I think there is somewhat of an ironic parallel to when Python was beginning to become popular. C and Java programmers would ‘bash’ Python, stating that it wasn't a real language, and that the dynamic nature of its types would be dangerous, and all...
Self-repairing Python threads
717,831
4
2009-04-04T21:14:32Z
717,847
8
2009-04-04T21:25:52Z
[ "python", "multithreading" ]
I've created a web spider that accesses both a US and EU server. The US and EU servers are the same data structure, but have different data inside them, and I want to collate it all. In order to be nice to the server, there's a wait time between each request. As the program is exactly the same, in order to speed up pro...
Just use a `try: ... except: ...` block in the `run` method. If something weird happens that causes the thread to fail, it's highly likely that an error will be thrown somewhere in your code (as opposed to in the threading subsystem itself); this way you can catch it, log it, and restart the thread. It's your call whet...
How to install SimpleJson Package for Python
718,040
32
2009-04-04T23:31:10Z
718,073
43
2009-04-04T23:54:42Z
[ "python", "simplejson" ]
<http://pypi.python.org/pypi/simplejson> I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working.. I am on a Windows System
I would recommend [EasyInstall](http://pypi.python.org/pypi/setuptools#windows), a package management application for Python. Once you've installed EasyInstall, you should be able to go to a command window and type: ``` easy_install simplejson ``` This may require putting easy\_install.exe on your PATH first, I don'...
How to install SimpleJson Package for Python
718,040
32
2009-04-04T23:31:10Z
718,097
15
2009-04-05T00:12:08Z
[ "python", "simplejson" ]
<http://pypi.python.org/pypi/simplejson> I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working.. I am on a Windows System
If you have Python 2.6 installed then you already have simplejson - just import `json`; it's the same thing.
How to install SimpleJson Package for Python
718,040
32
2009-04-04T23:31:10Z
16,538,587
17
2013-05-14T08:39:32Z
[ "python", "simplejson" ]
<http://pypi.python.org/pypi/simplejson> I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working.. I am on a Windows System
Really simple way is: ``` pip install simplejson ```
Django Template - New Variable Declaration
719,127
13
2009-04-05T15:37:15Z
719,132
20
2009-04-05T15:38:44Z
[ "python", "django", "django-templates" ]
Let me preface by I am just starting Python so if this is really a simple question ^\_^ I have a html file with the following content: ``` {%for d in results%} <div class="twt"> <img src="{{ d.profile_image_url }}" width="48px" height="48px" /> <span> {{ d.text }} </span> <span class="date">{{ d.created_...
Check out the [documentation](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for) on the `for` loop. It automatically creates a variable called `forloop.counter` that holds the current iteration index. As far as the greater question on how to declare variables, there is no out-of-the-box way of doing th...
Django Template - New Variable Declaration
719,127
13
2009-04-05T15:37:15Z
5,040,262
7
2011-02-18T10:38:13Z
[ "python", "django", "django-templates" ]
Let me preface by I am just starting Python so if this is really a simple question ^\_^ I have a html file with the following content: ``` {%for d in results%} <div class="twt"> <img src="{{ d.profile_image_url }}" width="48px" height="48px" /> <span> {{ d.text }} </span> <span class="date">{{ d.created_...
If you want to set any variable inside a Django template, you can use [this small template tag I've written](http://www.soyoucode.com/2011/set-variable-django-template).
How can you make a vote-up-down button like in Stackoverflow?
719,194
30
2009-04-05T16:07:30Z
719,475
57
2009-04-05T18:55:08Z
[ "javascript", "python", "html", "ajax" ]
**Problems** 1. how to make an Ajax buttons (upward and downward arrows) such that the number can increase or decrease 2. how to save the action af an user to an variable NumberOfVotesOfQuestionID I am not sure whether I should use database or not for the variable. However, I know that there is an easier way too to s...
This is a dirty/untested theoretical implementation using jQuery/Django. We're going to assume the voting up and down is for questions/answers like on this site, but that can obviously be adjusted to your real life use case. ### The template ``` <div id="answer_595" class="answer"> <img src="vote_up.png" class="vo...
How can you make a vote-up-down button like in Stackoverflow?
719,194
30
2009-04-05T16:07:30Z
719,606
7
2009-04-05T20:16:48Z
[ "javascript", "python", "html", "ajax" ]
**Problems** 1. how to make an Ajax buttons (upward and downward arrows) such that the number can increase or decrease 2. how to save the action af an user to an variable NumberOfVotesOfQuestionID I am not sure whether I should use database or not for the variable. However, I know that there is an easier way too to s...
A couple of points no one has mentioned: * You don't want to use GET when changing the state of your database. Otherwise I could put an image on my site with `src="http://stackoverflow.com/question_555/vote/up/answer_3/"`. * You also need [csrf (Cross Site Request Forgery) protection](http://docs.djangoproject.com/en/...
What is the purpose of python's inner classes?
719,705
58
2009-04-05T21:13:28Z
719,718
56
2009-04-05T21:24:34Z
[ "python", "class", "oop", "language-features" ]
Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?
Quoted from <http://www.geekinterview.com/question_details/64739>: > ### Advantages of inner class: > > * **Logical grouping of classes**: If a class is useful to only one other class then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamli...
What is the purpose of python's inner classes?
719,705
58
2009-04-05T21:13:28Z
722,036
9
2009-04-06T15:43:54Z
[ "python", "class", "oop", "language-features" ]
Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?
Nesting classes within classes: * Nested classes bloat the class definition making it harder to see whats going on. * Nested classes can create coupling that would make testing more difficult. * In Python you can put more than one class in a file/module, unlike Java, so the class still remains close to top level class...
What is the purpose of python's inner classes?
719,705
58
2009-04-05T21:13:28Z
722,175
40
2009-04-06T16:23:21Z
[ "python", "class", "oop", "language-features" ]
Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?
> Is there something that can't be accomplished without them? No. They are absolutely equivalent to defining the class normally at top level, and then copying a reference to it into the outer class. I don't think there's any special reason nested classes are ‘allowed’, other than it makes no particular sense to e...
What is the purpose of python's inner classes?
719,705
58
2009-04-05T21:13:28Z
722,237
18
2009-04-06T16:38:01Z
[ "python", "class", "oop", "language-features" ]
Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?
There's something you need to wrap your head around to be able to understand this. In most languages, class definitions are directives to the compiler. That is, the class is created before the program is ever run. In python, all statements are executable. That means that this statement: ``` class foo(object): pass...
What is the best ordered dict implementation in python?
719,744
6
2009-04-05T21:40:44Z
719,772
8
2009-04-05T21:56:17Z
[ "python", "dictionary", "ordereddictionary" ]
I've seen (and written) a number of implementations of this. Is there one that is considered the best or is emerging as a standard? What I mean by ordered dict is that the object has some concept of the order of the keys in it, similar to an array in PHP. odict from [PEP 372](http://www.python.org/dev/peps/pep-0372/)...
I haven't seen a standard; everyone seems to roll their own (see answers to [this question](http://stackoverflow.com/questions/60848/how-do-you-retrieve-items-from-a-dictionary-in-the-order-that-theyre-inserted)). If you can use the `OrderedDict` [patch](http://bugs.python.org/issue5397) from PEP 372, that's your best ...
What is the best ordered dict implementation in python?
719,744
6
2009-04-05T21:40:44Z
2,030,935
12
2010-01-08T21:37:05Z
[ "python", "dictionary", "ordereddictionary" ]
I've seen (and written) a number of implementations of this. Is there one that is considered the best or is emerging as a standard? What I mean by ordered dict is that the object has some concept of the order of the keys in it, similar to an array in PHP. odict from [PEP 372](http://www.python.org/dev/peps/pep-0372/)...
This one by Raymond Hettinger is a drop-in substitute for the collections.OrderedDict that will appear in Python 2.7: <http://pypi.python.org/pypi/ordereddict> The dev version of the collections docs say it's equivalent to what will be in Python 2.7, so it's probably pretty likely to be a smooth transition to the one ...
How do I apply Django model Meta options to models that I did not write?
720,083
5
2009-04-06T02:21:26Z
720,090
9
2009-04-06T02:26:08Z
[ "python", "django" ]
I want to apply the ["ordering"](http://docs.djangoproject.com/en/dev/ref/models/options/#ordering) Meta option to the Django model User from django.contrib.auth.models. Normally I would just put the Meta class in the model's definition, but in this case I did not define the model. So where do I put the Meta class to m...
[This is how the Django manual recommends you do it](http://docs.djangoproject.com/en/dev/topics/db/models/#specifying-the-parent-link-field): > You could also use a proxy model to define a different default ordering on a model. The standard User model has no ordering defined on it (intentionally; sorting is expensive...
Find Hyperlinks in Text using Python (twitter related)
720,113
12
2009-04-06T02:37:48Z
720,137
20
2009-04-06T02:53:17Z
[ "python", "regex" ]
How can I parse text and find all instances of hyperlinks with a string? The hyperlink will not be in the html format of `<a href="http://test.com">test</a>` but just `http://test.com` Secondly, I would like to then convert the original string and replace all instances of hyperlinks into clickable html hyperlinks. I ...
Here's a Python port of <http://stackoverflow.com/questions/32637/easiest-way-to-convert-a-url-to-a-hyperlink-in-a-c-string/32648#32648>: ``` import re myString = "This is my tweet check it out http://tinyurl.com/blah" r = re.compile(r"(http://[^ ]+)") print r.sub(r'<a href="\1">\1</a>', myString) ``` Output: ``` ...
Find Hyperlinks in Text using Python (twitter related)
720,113
12
2009-04-06T02:37:48Z
2,102,648
8
2010-01-20T15:45:58Z
[ "python", "regex" ]
How can I parse text and find all instances of hyperlinks with a string? The hyperlink will not be in the html format of `<a href="http://test.com">test</a>` but just `http://test.com` Secondly, I would like to then convert the original string and replace all instances of hyperlinks into clickable html hyperlinks. I ...
[Here](http://mail.python.org/pipermail/tutor/2002-September/017228.html) is a much more sophisticated regexp from 2002.
Function definition in Python
720,621
2
2009-04-06T08:36:23Z
720,632
19
2009-04-06T08:40:47Z
[ "python" ]
I am new to Python. I was trying to define and run a simple function in a class. Can anybody please tell me what's wrong in my code: ``` class A : def m1(name,age,address) : print('Name -->',name) print('Age -->',age) print('Address -->',address) >>> a = A() >>> a.m1('X',12,'XXXX') Traceback (mos...
Instance methods take instance as first argument: ``` class A : def m1(self, name,age,address) : print('Name -->',name) print('Age -->',age) print('Address -->',address) ``` You can also use [@staticmethod decorator](http://docs.python.org/library/functions.html#staticmethod) to create sta...
HTTP Authentication in Python
720,867
15
2009-04-06T10:03:12Z
720,880
20
2009-04-06T10:09:33Z
[ "authentication", "curl", "http-headers", "python" ]
Whats is the python urllib equivallent of ``` curl -u username:password status="abcd" http://example.com/update.json ``` I did this: ``` handle = urllib2.Request(url) authheader = "Basic %s" % base64.encodestring('%s:%s' % (username, password)) handle.add_header("Authorization", authheader) ``` Is there a better /...
The trick is to create a password manager, and then tell urllib about it. Usually, you won't care about the realm of the authentication, just the host/url part. For example, the following: ``` password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() top_level_url = "http://example.com/" password_mgr.add_password(None,...
Django templates stripping spaces?
721,035
13
2009-04-06T11:22:15Z
721,082
10
2009-04-06T11:45:05Z
[ "python", "django", "django-templates" ]
I'm having trouble with Django templates and CharField models. So I have a model with a CharField that creates a slug that replaces spaces with underscores. If I create an object, Somename Somesurname, this creates slug *Somename\_Somesurname* and gets displayed as expected on the template. However, if I create an ob...
Django sees the object internally as having two spaces (judging by the two underscores and two spaces in the `repr` output). The fact that it only shows up with one space in the template is just how HTML works. Notice how, in the question you just asked, most of the places where you entered two spaces, only one is show...
Django templates stripping spaces?
721,035
13
2009-04-06T11:22:15Z
722,266
29
2009-04-06T16:46:38Z
[ "python", "django", "django-templates" ]
I'm having trouble with Django templates and CharField models. So I have a model with a CharField that creates a slug that replaces spaces with underscores. If I create an object, Somename Somesurname, this creates slug *Somename\_Somesurname* and gets displayed as expected on the template. However, if I create an ob...
Let me preface this by saying [@DNS's answer](#721082) is correct as to why the spaces are not showing. With that in mind, this template filter will replace any spaces in the string with `&nbsp;` Usage: ``` {{ "hey there world"|spacify }} ``` Output would be `hey&nbsp;there&nbsp;&nbsp;world` Here is the code: ``...
What's a good two-way encryption library implemented in Python?
721,436
4
2009-04-06T13:27:18Z
721,444
7
2009-04-06T13:30:05Z
[ "python", "encryption" ]
The authentication system for an application we're using right now uses a two-way hash that's basically little more than a glorified caesar cypher. Without going into too much detail about what's going on with it, I'd like to replace it with a more secure encryption algorithm (and it needs to be done server-side). Unfo...
If it's two-way, it's not really a "hash". It's encryption (and from the sounds of things this is really more of a 'salt' or 'cypher', *not* real encryption.) A hash is one-way *by definition*. So rather than something like MD5 or SHA1 you need to look for something more like PGP. Secondly, can you explain the reasoni...
What's a good two-way encryption library implemented in Python?
721,436
4
2009-04-06T13:27:18Z
721,457
19
2009-04-06T13:32:06Z
[ "python", "encryption" ]
The authentication system for an application we're using right now uses a two-way hash that's basically little more than a glorified caesar cypher. Without going into too much detail about what's going on with it, I'd like to replace it with a more secure encryption algorithm (and it needs to be done server-side). Unfo...
I assume you want an encryption algorithm, not a hash. The [PyCrypto](https://pypi.python.org/pypi/pycrypto) library offers a pretty wide range of options. It's in the middle of moving over to a [new maintainer](http://www.dlitz.net/software/pycrypto/), so the docs are a little disorganized, but [this](http://www.dlitz...
Django GROUP BY strftime date format
722,325
14
2009-04-06T17:04:07Z
722,880
14
2009-04-06T19:45:11Z
[ "python", "django", "orm", "django-models", "django-aggregation" ]
I would like to do a SUM on rows in a database and group by date. I am trying to run this SQL query using Django aggregates and annotations: ``` select strftime('%m/%d/%Y', time_stamp) as the_date, sum(numbers_data) from my_model group by the_date; ``` I tried the following: ``` data = My_Model.objects.valu...
This works for me: ``` select_data = {"d": """strftime('%%m/%%d/%%Y', time_stamp)"""} data = My_Model.objects.extra(select=select_data).values('d').annotate(Sum("numbers_data")).order_by() ``` Took a bit to figure out I had to escape the % signs.
Best way to turn word list into frequency dict
722,697
4
2009-04-06T18:55:11Z
722,702
11
2009-04-06T18:56:16Z
[ "python" ]
What's the best way to convert a list/tuple into a dict where the keys are the distinct values of the list and the values are the the frequencies of those distinct values? In other words: ``` ['a', 'b', 'b', 'a', 'b', 'c'] --> {'a': 2, 'b': 3, 'c': 1} ``` (I've had to do something like the above so many times, is t...
Kind of ``` from collections import defaultdict fq= defaultdict( int ) for w in words: fq[w] += 1 ``` That usually works nicely.
Best way to turn word list into frequency dict
722,697
4
2009-04-06T18:55:11Z
722,806
18
2009-04-06T19:28:51Z
[ "python" ]
What's the best way to convert a list/tuple into a dict where the keys are the distinct values of the list and the values are the the frequencies of those distinct values? In other words: ``` ['a', 'b', 'b', 'a', 'b', 'c'] --> {'a': 2, 'b': 3, 'c': 1} ``` (I've had to do something like the above so many times, is t...
I find that the easiest to understand (while might not be the most efficient) way is to do: ``` {i:words.count(i) for i in set(words)} ```
How do you send an Ethernet frame with a corrupt FCS?
723,635
6
2009-04-06T23:30:16Z
724,009
8
2009-04-07T02:50:09Z
[ "python", "networking", "automated-tests", "ethernet" ]
I'm not sure if this is even possible since this might be handled in hardware, but I need to send some Ethernet frames with errors in them. I'd like to be able to create runts, jabber, misalignment, and bad FCS errors. I'm working in Python.
It *can* be handled in hardware, but isn't always -- and even if it is, you can turn that off; see the [ethtool](http://linux.die.net/man/8/ethtool) offload parameters. With regard to getting full control over the frames you create -- look into [PF\_PACKET](http://swoolley.org/man.cgi/7/packet) (for one approach) or [...
Python distutils, how to get a compiler that is going to be used?
724,664
22
2009-04-07T08:36:07Z
5,192,738
17
2011-03-04T10:49:56Z
[ "python", "compiler-construction", "installation", "distutils" ]
For example, I may use `python setup.py build --compiler=msvc` or `python setup.py build --compiler=mingw32` or just `python setup.py build`, in which case the default compiler (say, `bcpp`) will be used. How can I get the compiler name inside my setup.py (e. g. `msvc`, `mingw32` and `bcpp`, respectively)? UPD.: I don...
This is an expanded version of Luper Rouch's answer that worked for me to get an openmp extension to compile using both mingw and msvc on windows. After subclassing build\_ext you need to pass it to setup.py in the cmdclass arg. By subclassing build\_extensions instead of finalize\_options you'll have the actual compil...
Picking out items from a python list which have specific indexes
724,856
9
2009-04-07T09:43:33Z
724,881
41
2009-04-07T09:50:52Z
[ "python", "list", "list-comprehension" ]
I'm sure there's a nice way to do this in Python, but I'm pretty new to the language, so forgive me if this is an easy one! I have a list, and I'd like to pick out certain values from that list. The values I want to pick out are the ones whose indexes in the list are specified in another list. For example: ``` index...
``` [main_list[x] for x in indexes] ``` This will return a list of the objects, using a list comprehension.
In Python, what is the difference between ".append()" and "+= []"?
725,782
88
2009-04-07T13:44:24Z
725,818
44
2009-04-07T13:51:17Z
[ "python", "list", "concatenation" ]
What is the difference between: ``` some_list1 = [] some_list1.append("something") ``` and ``` some_list2 = [] some_list2 += ["something"] ```
In the example you gave, there is no difference, in terms of output, between `append` and `+=`. But there is a difference between `append` and `+` (which the question originally asked about). ``` >>> a = [] >>> id(a) 11814312 >>> a.append("hello") >>> id(a) 11814312 >>> b = [] >>> id(b) 11828720 >>> c = b + ["hello"]...
In Python, what is the difference between ".append()" and "+= []"?
725,782
88
2009-04-07T13:44:24Z
725,853
19
2009-04-07T13:54:49Z
[ "python", "list", "concatenation" ]
What is the difference between: ``` some_list1 = [] some_list1.append("something") ``` and ``` some_list2 = [] some_list2 += ["something"] ```
``` some_list2 += ["something"] ``` is actually ``` some_list2.extend(["something"]) ``` for one value, there is no difference. Documentation states, that: > `s.append(x)` same as `s[len(s):len(s)] = [x]` > `s.extend(x)` same as `s[len(s):len(s)] = x` Thus obviously `s.append(x)` is same as `s.extend([x])`
In Python, what is the difference between ".append()" and "+= []"?
725,782
88
2009-04-07T13:44:24Z
725,863
36
2009-04-07T13:57:37Z
[ "python", "list", "concatenation" ]
What is the difference between: ``` some_list1 = [] some_list1.append("something") ``` and ``` some_list2 = [] some_list2 += ["something"] ```
``` >>> a=[] >>> a.append([1,2]) >>> a [[1, 2]] >>> a=[] >>> a+=[1,2] >>> a [1, 2] ``` See that append adds a single element to the list, which may be anything. `+=[]` joins the lists.
In Python, what is the difference between ".append()" and "+= []"?
725,782
88
2009-04-07T13:44:24Z
725,882
130
2009-04-07T14:00:24Z
[ "python", "list", "concatenation" ]
What is the difference between: ``` some_list1 = [] some_list1.append("something") ``` and ``` some_list2 = [] some_list2 += ["something"] ```
For your case the only difference is performance: append is twice as fast. ``` Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import timeit >>> timeit.Timer('s.append("something")', 's = []').timeit() 0.20177...
In Python, what is the difference between ".append()" and "+= []"?
725,782
88
2009-04-07T13:44:24Z
726,349
25
2009-04-07T15:29:12Z
[ "python", "list", "concatenation" ]
What is the difference between: ``` some_list1 = [] some_list1.append("something") ``` and ``` some_list2 = [] some_list2 += ["something"] ```
+= is an assignment. When you use it you're really saying ‘some\_list2= some\_list2+['something']’. Assignments involve rebinding, so: ``` l= [] def a1(x): l.append(x) # works def a2(x): l= l+[x] # assign to l, makes l local # so attempt to read l for addition gives UnboundLocalError def a3...
Installing ipython with readline on the mac
726,449
16
2009-04-07T15:55:16Z
1,840,304
34
2009-12-03T14:43:38Z
[ "python", "osx", "readline", "ipython" ]
I am using ipython on Mac OS 10.5 with python 2.5.1 (I would actually like to use ipython for 2.6.1, but it doesn't seem to be available?) I installed ipython via easy\_install. It works but is missing gnu readline (needed for nice searching of command line history with ctrl-R, etc.) I found a [blog post](http://www....
To install ipython on Snow Leopard or Lion without using MacPorts, you can simply do: ``` sudo easy_install readline ipython ``` (Note that if you use the "pip" to install readline, then ipython won't see the readline library, not sure why). *Edit:* If you had ipython installed remove it with ``` sudo pip uninstal...
Installing ipython with readline on the mac
726,449
16
2009-04-07T15:55:16Z
8,749,044
13
2012-01-05T20:09:03Z
[ "python", "osx", "readline", "ipython" ]
I am using ipython on Mac OS 10.5 with python 2.5.1 (I would actually like to use ipython for 2.6.1, but it doesn't seem to be available?) I installed ipython via easy\_install. It works but is missing gnu readline (needed for nice searching of command line history with ctrl-R, etc.) I found a [blog post](http://www....
this worked for me (I'm using python 2.7, for other versions you'll need to edit): ``` cd /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload sudo mv readline.so readline.so.bak ``` install readline however you want (pip, homebrew, macports, etc) ``` pip install -U readline ``` Succes...