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
Common coding style for Python?
2,815,272
11
2010-05-12T00:02:14Z
2,815,311
18
2010-05-12T00:11:46Z
[ "python", "coding-style", "naming-conventions", "indentation", "column-width" ]
I'm pretty new to Python, and I want to develop my first serious open source project. I want to ask what is the common coding style for python projects. I'll put also what I'm doing right now. 1.- What is the most widely used column width? (the eternal question) I'm currently sticking to 80 columns (and it's a pain!...
[PEP 8](http://www.python.org/dev/peps/pep-0008/) is pretty much "the root" of all common style guides. Google's [Python style guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html) has some parts that are quite well thought of, but others are idiosyncratic (the two-space indents instead of the popular...
How to get the parent dir location
2,817,264
70
2010-05-12T08:57:45Z
2,817,302
87
2010-05-12T09:03:16Z
[ "python", "path" ]
this code is get the templates/blog1/page.html in b.py: ``` path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog1/page.html')) ``` but i want to get the parent dir location: ``` aParent |--a | |---b.py | |---templates | |--------blog1 | ...
You can apply dirname repeatedly to climb higher: `dirname(dirname(file))`. This can only go as far as the root package, however. If this is a problem, use `os.path.abspath`: `dirname(dirname(abspath(file)))`.
How to get the parent dir location
2,817,264
70
2010-05-12T08:57:45Z
2,817,541
8
2010-05-12T09:36:21Z
[ "python", "path" ]
this code is get the templates/blog1/page.html in b.py: ``` path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog1/page.html')) ``` but i want to get the parent dir location: ``` aParent |--a | |---b.py | |---templates | |--------blog1 | ...
``` os.path.dirname(os.path.abspath(__file__)) ``` Should give you the path to `a`. But if `b.py` is the file that is currently executed, then you can achieve the same by just doing ``` os.path.abspath(os.path.join('templates', 'blog1', 'page.html')) ```
How to get the parent dir location
2,817,264
70
2010-05-12T08:57:45Z
14,150,750
24
2013-01-04T03:38:30Z
[ "python", "path" ]
this code is get the templates/blog1/page.html in b.py: ``` path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog1/page.html')) ``` but i want to get the parent dir location: ``` aParent |--a | |---b.py | |---templates | |--------blog1 | ...
`os.path.abspath` doesn't validate anything, so if we're already appending strings to `__file__` there's no need to bother with `dirname` or joining or any of that. Just treat `__file__` as a directory and start climbing: ``` # climb to __file__'s parent's parent: os.path.abspath(__file__ + "/../../") ``` That's far ...
How do I request and process JSON with python?
2,817,481
54
2010-05-12T09:28:59Z
2,817,530
59
2010-05-12T09:35:03Z
[ "python", "json", "httprequest" ]
I am trying to send a GET request to a URL that I know returns data in the form of JSON using python. I would like to know how to send this request to `http://someurl/path/to/json`, and how to parse it - preferably to a python dict.
Python's standard library has [`json`](http://docs.python.org/library/json.html) and [`urllib2`](http://docs.python.org/library/urllib2.html) modules. ``` import json import urllib2 data = json.load(urllib2.urlopen('http://someurl/path/to/json')) ```
How do I request and process JSON with python?
2,817,481
54
2010-05-12T09:28:59Z
12,402,180
64
2012-09-13T08:22:07Z
[ "python", "json", "httprequest" ]
I am trying to send a GET request to a URL that I know returns data in the form of JSON using python. I would like to know how to send this request to `http://someurl/path/to/json`, and how to parse it - preferably to a python dict.
For anything with requests to URLs you might want to check out [requests](http://docs.python-requests.org/en/latest/user/quickstart/). For JSON in particular: ``` >>> import requests >>> r = requests.get('https://github.com/timeline.json') >>> r.json() [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/....
error: Unable to find vcvarsall.bat
2,817,869
692
2010-05-12T10:24:35Z
2,818,009
21
2010-05-12T10:44:21Z
[ "python", "windows", "pip", "setup.py" ]
I tried to install the Python package [dulwich](https://pypi.python.org/pypi/dulwich): ``` pip install dulwich ``` But I get a cryptic error message: ``` error: Unable to find vcvarsall.bat ``` The same happens if I try installing the package manually: ``` > python setup.py install running build_ext building 'dulw...
Looks like its looking for VC compilers, so you could try to mention compiler type with `-c mingw32`, since you have msys ``` python setup.py install -c mingw32 ```
error: Unable to find vcvarsall.bat
2,817,869
692
2010-05-12T10:24:35Z
2,838,827
215
2010-05-15T03:37:31Z
[ "python", "windows", "pip", "setup.py" ]
I tried to install the Python package [dulwich](https://pypi.python.org/pypi/dulwich): ``` pip install dulwich ``` But I get a cryptic error message: ``` error: Unable to find vcvarsall.bat ``` The same happens if I try installing the package manually: ``` > python setup.py install running build_ext building 'dulw...
I found the solution. I had the exact same problem, and error, installing 'amara'. I had mingw32 installed, but distutils needed to be configured. 1. I have Python 2.6 that was already installed. 2. I installed mingw32 to `C:\programs\mingw\` 3. Add mingw32's bin directory to your environment variable: append `c:\prog...
error: Unable to find vcvarsall.bat
2,817,869
692
2010-05-12T10:24:35Z
5,983,696
214
2011-05-12T19:55:38Z
[ "python", "windows", "pip", "setup.py" ]
I tried to install the Python package [dulwich](https://pypi.python.org/pypi/dulwich): ``` pip install dulwich ``` But I get a cryptic error message: ``` error: Unable to find vcvarsall.bat ``` The same happens if I try installing the package manually: ``` > python setup.py install running build_ext building 'dulw...
You can install compiled version from <http://www.lfd.uci.edu/~gohlke/pythonlibs/>
error: Unable to find vcvarsall.bat
2,817,869
692
2010-05-12T10:24:35Z
10,501,736
53
2012-05-08T15:31:47Z
[ "python", "windows", "pip", "setup.py" ]
I tried to install the Python package [dulwich](https://pypi.python.org/pypi/dulwich): ``` pip install dulwich ``` But I get a cryptic error message: ``` error: Unable to find vcvarsall.bat ``` The same happens if I try installing the package manually: ``` > python setup.py install running build_ext building 'dulw...
I just had this same problem, so I'll tell my story here hoping it helps someone else with the same issues and save them the couple of hours I just spent: I have mingw (g++ (GCC) 4.6.1) and python 2.7.3 in a windows 7 box and I'm trying to install PyCrypto. It all started with this error when running setup.py install...
error: Unable to find vcvarsall.bat
2,817,869
692
2010-05-12T10:24:35Z
10,558,328
629
2012-05-11T20:39:57Z
[ "python", "windows", "pip", "setup.py" ]
I tried to install the Python package [dulwich](https://pypi.python.org/pypi/dulwich): ``` pip install dulwich ``` But I get a cryptic error message: ``` error: Unable to find vcvarsall.bat ``` The same happens if I try installing the package manually: ``` > python setup.py install running build_ext building 'dulw...
***Update***: Comments point out that the instructions here may be dangerous. Consider using the Visual C++ 2008 Express edition or the purpose-built [Microsoft Visual C++ Compiler for Python](https://aka.ms/vcpython27) ([details](/a/26127562/2778484)) and **NOT** using the original answer below. Original error message...
error: Unable to find vcvarsall.bat
2,817,869
692
2010-05-12T10:24:35Z
15,718,810
19
2013-03-30T13:00:56Z
[ "python", "windows", "pip", "setup.py" ]
I tried to install the Python package [dulwich](https://pypi.python.org/pypi/dulwich): ``` pip install dulwich ``` But I get a cryptic error message: ``` error: Unable to find vcvarsall.bat ``` The same happens if I try installing the package manually: ``` > python setup.py install running build_ext building 'dulw...
I have python 2.73 and windows 7 .The solution that worked for me was: 1. Added mingw32's bin directory to environment variable: append **PATH** with `C:\programs\mingw\bin;` 2. Created **distutils.cfg** located at `C:\Python27\Lib\distutils\distutils.cfg` containing: ``` [build] compiler=mingw32 ``` To ...
error: Unable to find vcvarsall.bat
2,817,869
692
2010-05-12T10:24:35Z
15,832,595
9
2013-04-05T11:20:39Z
[ "python", "windows", "pip", "setup.py" ]
I tried to install the Python package [dulwich](https://pypi.python.org/pypi/dulwich): ``` pip install dulwich ``` But I get a cryptic error message: ``` error: Unable to find vcvarsall.bat ``` The same happens if I try installing the package manually: ``` > python setup.py install running build_ext building 'dulw...
Maybe somebody can be interested, the following worked for me for the py2exe package. (I have windows 7 64 bit and portable python 2.7, Visual Studio 2005 Express with Windows SDK for Windows 7 and .NET Framework 4) ``` set VS90COMNTOOLS=%VS80COMNTOOLS% ``` then: ``` python.exe setup.py install ```
error: Unable to find vcvarsall.bat
2,817,869
692
2010-05-12T10:24:35Z
17,065,122
7
2013-06-12T12:09:08Z
[ "python", "windows", "pip", "setup.py" ]
I tried to install the Python package [dulwich](https://pypi.python.org/pypi/dulwich): ``` pip install dulwich ``` But I get a cryptic error message: ``` error: Unable to find vcvarsall.bat ``` The same happens if I try installing the package manually: ``` > python setup.py install running build_ext building 'dulw...
I tried all the above answers, and found all of them not to work, this was perhaps I was using Windows 8 and had installed Visual Studio 2012. In this case, this is what you do. The `vcvarsall.bat` file is located here: `C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC` Simply select the file, and copy it. The...
error: Unable to find vcvarsall.bat
2,817,869
692
2010-05-12T10:24:35Z
18,018,539
63
2013-08-02T13:48:46Z
[ "python", "windows", "pip", "setup.py" ]
I tried to install the Python package [dulwich](https://pypi.python.org/pypi/dulwich): ``` pip install dulwich ``` But I get a cryptic error message: ``` error: Unable to find vcvarsall.bat ``` The same happens if I try installing the package manually: ``` > python setup.py install running build_ext building 'dulw...
What's going on? Python modules can be [part written in C or C++](https://docs.python.org/3/extending/extending.html) (typically for speed). If you try to install such a package with Pip (or `setup.py`), it has to compile that C/C++ from source. Out the box, Pip will brazenly assume you the compiler Microsoft Visual C+...
error: Unable to find vcvarsall.bat
2,817,869
692
2010-05-12T10:24:35Z
18,045,219
113
2013-08-04T16:48:35Z
[ "python", "windows", "pip", "setup.py" ]
I tried to install the Python package [dulwich](https://pypi.python.org/pypi/dulwich): ``` pip install dulwich ``` But I get a cryptic error message: ``` error: Unable to find vcvarsall.bat ``` The same happens if I try installing the package manually: ``` > python setup.py install running build_ext building 'dulw...
At least I found my solution from drawing feedback from other answers using the Visual Studio C++ compilers rather than installing through the mingw32 path. ## Important Note: If you are using a Python version *more recent* than Python 2.7 (especially any Python 3.x), you most likely need a version of Visual Studio C...
error: Unable to find vcvarsall.bat
2,817,869
692
2010-05-12T10:24:35Z
26,127,562
50
2014-09-30T18:23:08Z
[ "python", "windows", "pip", "setup.py" ]
I tried to install the Python package [dulwich](https://pypi.python.org/pypi/dulwich): ``` pip install dulwich ``` But I get a cryptic error message: ``` error: Unable to find vcvarsall.bat ``` The same happens if I try installing the package manually: ``` > python setup.py install running build_ext building 'dulw...
You'll need to install a Microsoft compiler, compatible with the compiler used to build Python. This means you need Visual C++ 2008 (or newer, with [some tweaking](/a/10558328)). Microsoft now supplies a bundled compiler and headers *just* to be able to compile Python extensions, at the memorable URL: > ### Microsoft...
error: Unable to find vcvarsall.bat
2,817,869
692
2010-05-12T10:24:35Z
28,617,830
11
2015-02-19T22:00:53Z
[ "python", "windows", "pip", "setup.py" ]
I tried to install the Python package [dulwich](https://pypi.python.org/pypi/dulwich): ``` pip install dulwich ``` But I get a cryptic error message: ``` error: Unable to find vcvarsall.bat ``` The same happens if I try installing the package manually: ``` > python setup.py install running build_ext building 'dulw...
Look in the `setup.py` file of the package you are trying to install. If it is an older package it may be importing `distutils.core.setup()` rather than `setuptools.setup()`. I ran in to this (in 2015) with a combination of these factors: 1. The Microsoft Visual C++ Compiler for Python 2.7 from <http://aka.ms/vcpytho...
Dynamically calling functions - Python
2,818,490
3
2010-05-12T11:53:08Z
2,818,524
9
2010-05-12T11:57:37Z
[ "python" ]
I have a list of functions... e.g. ``` def filter_bunnies(pets): ... def filter_turtles(pets): ... def filter_narwhals(pets): ... ``` **Is there a way to call these functions by using a string representing their name?** e.g. ``` 'filter_bunnies', 'filter_turtles', 'filter_narwhals' ```
Are your function a part of an object? If so you could use [`getattr`](http://docs.python.org/library/functions.html#getattr) function: ``` >> class A: def filter_bunnies(self, pets): print('bunnies') >>> getattr(A(), 'filter_bunnies')(1) bunnies ```
parsing .properties file in Python
2,819,696
34
2010-05-12T14:25:01Z
2,819,788
61
2010-05-12T14:36:38Z
[ "python", "key-value", "ini" ]
The [`ConfigParser`](http://docs.python.org/2/library/configparser) module raises an exception if one parses a simple Java-style **`.properties`** file, whose content is key-value pairs (i..e without INI-style section headers). Is there some workaround?
Say you have, e.g.: ``` $ cat my.props first: primo second: secondo third: terzo ``` i.e. would be a `.config` format except that it's missing a leading section name. Then, it easy to fake the section header: ``` import ConfigParser class FakeSecHead(object): def __init__(self, fp): self.fp = fp ...
parsing .properties file in Python
2,819,696
34
2010-05-12T14:25:01Z
8,555,776
14
2011-12-18T23:46:01Z
[ "python", "key-value", "ini" ]
The [`ConfigParser`](http://docs.python.org/2/library/configparser) module raises an exception if one parses a simple Java-style **`.properties`** file, whose content is key-value pairs (i..e without INI-style section headers). Is there some workaround?
Alex Martelli's answer above does not work for Python 3.2+: `readfp()` has been replaced by `read_file()`, and it now takes an iterator instead of using the `readline()` method. Here's a snippet that uses the same approach, but works in Python 3.2+. ``` >>> import configparser >>> def add_section_header(properties_fi...
parsing .properties file in Python
2,819,696
34
2010-05-12T14:25:01Z
8,657,601
26
2011-12-28T15:13:32Z
[ "python", "key-value", "ini" ]
The [`ConfigParser`](http://docs.python.org/2/library/configparser) module raises an exception if one parses a simple Java-style **`.properties`** file, whose content is key-value pairs (i..e without INI-style section headers). Is there some workaround?
My solution is to use `StringIO` and prepend a simple dummy header: ``` import StringIO import os config = StringIO.StringIO() config.write('[dummysection]\n') config.write(open('myrealconfig.ini').read()) config.seek(0, os.SEEK_SET) import ConfigParser cp = ConfigParser.ConfigParser() cp.readfp(config) somevalue = c...
parsing .properties file in Python
2,819,696
34
2010-05-12T14:25:01Z
25,493,615
7
2014-08-25T20:11:06Z
[ "python", "key-value", "ini" ]
The [`ConfigParser`](http://docs.python.org/2/library/configparser) module raises an exception if one parses a simple Java-style **`.properties`** file, whose content is key-value pairs (i..e without INI-style section headers). Is there some workaround?
I thought [MestreLion's "read\_string" comment](http://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/25493615#comment26110228_8555776) was nice and simple and deserved an example. For Python 3.2+, you can implement the "dummy section" idea like this: ``` with open(CONFIG_PATH, 'r') as f: c...
How can I redirect the logger to a wxPython textCtrl using a custom logging handler?
2,819,791
8
2010-05-12T14:37:12Z
2,820,928
11
2010-05-12T16:47:01Z
[ "python", "logging", "wxpython" ]
I'm using a module in my python app that writes a lot a of messages using the logging module. Initially I was using this in a console application and it was pretty easy to get the logging output to display on the console using a console handler. Now I've developed a GUI version of my app using wxPython and I'd like to ...
Create Handler ``` import wx import wx.lib.newevent import logging # create event type wxLogEvent, EVT_WX_LOG_EVENT = wx.lib.newevent.NewEvent() class wxLogHandler(logging.Handler): """ A handler class which sends log strings to a wx object """ def __init__(self, wxDest=None): """ I...
Is there a better way of making numpy.argmin() ignore NaN values
2,821,072
10
2010-05-12T17:07:15Z
2,821,092
21
2010-05-12T17:10:15Z
[ "arrays", "numpy", "python", null ]
I want to get the index of the min value of a numpy array that contains NaNs and I want them ignored ``` >>> a = array([ nan, 2.5, 3., nan, 4., 5.]) >>> a array([ NaN, 2.5, 3. , NaN, 4. , 5. ]) ``` if I run argmin, it returns the index of the first NaN ``` >>> a.argmin() 0 ``` I substitute NaNs ...
Sure! Use `nanargmin`: ``` import numpy as np a = np.array([ np.nan, 2.5, 3., np.nan, 4., 5.]) print(np.nanargmin(a)) # 1 ``` There is also `nansum`, `nanmax`, `nanargmax`, and `nanmin`, In `scipy.stats`, there is `nanmean` and `nanmedian`. [For more ways](http://docs.scipy.org/doc/numpy/reference/routines...
Python print statement prints nothing with a carriage return
2,821,503
7
2010-05-12T18:05:08Z
2,821,622
9
2010-05-12T18:21:47Z
[ "python", "command-line", "carriage-return" ]
I'm trying to write a simple tool that reads files from disc, does some image processing, and returns the result of the algorithm. Since the program can sometimes take awhile, I like to have a progress bar so I know where it is in the program. And since I don't like to clutter up my command line and I'm on a Unix platf...
Try adding `sys.stdout.flush()` after the print statement. It's possible that `print` isn't flushing the output until it writes a newline, which doesn't happen here.
How do you extend the Site model in django?
2,821,702
6
2010-05-12T18:33:03Z
2,824,112
7
2010-05-13T02:26:17Z
[ "python", "django", "django-models" ]
What is the best approach to extending the Site model in django? Creating a new model and ForeignKey the Site or there another approach that allows me to subclass the Site model? I prefer subclassing, because relationally I'm more comfortable, but I'm concerned for the impact it will have with the built-in Admin.
I just used my own subclass of Site and created a custom admin for it. Basically, when you subclass a model in django it creates FK pointing to parent model and allows to access parent model's fields transparently- the same way you'd access parent class attributes in pyhon. Built in admin won't suffer in any way, but ...
python copytree with negated ignore pattern
2,821,787
5
2010-05-12T18:44:51Z
2,821,871
7
2010-05-12T18:55:29Z
[ "python", "regex" ]
I'm trying to use python to copy a tree of files/directories. is it possible to use copytree to copy everything that ends in foo? There is an ignore\_patterns patterns function, can I give it a negated regular expression? Are they supported in python? eg. copytree(src, dest, False, ignore\_pattern('!\*.foo')) Where...
`shutil.copytree` has an [`ignore` keyword](http://docs.python.org/library/shutil.html#shutil.copytree). `ignore` can be set to any callable. Given the directory being visited and a list of its contents, the callable should return a sequence of directory and filenames to be ignored. For example: ``` import shutil def...
Django 1.2 object level permissions - third party solutions?
2,821,997
11
2010-05-12T19:14:05Z
2,856,794
7
2010-05-18T11:34:23Z
[ "python", "django", "permissions" ]
Since Django 1.2 final is almost out, I am curious if there are already projects that use the new object level permissions / row level permissions system. [Django-authority](http://packages.python.org/django-authority/), which is a possible solution for Django up to 1.1, has not been updated for a while, and does not (...
Finally, I found really good stuff: Florian Apolloner wrote a howto on djangoadvent: <http://djangoadvent.com/1.2/object-permissions/> Now **that's** what I'm gonna use :) Something useful might be as well: <http://github.com/washingtontimes/django-objectpermissions> (link dead as of 2011-07-18)
Django 1.2 object level permissions - third party solutions?
2,821,997
11
2010-05-12T19:14:05Z
5,561,885
9
2011-04-06T05:31:10Z
[ "python", "django", "permissions" ]
Since Django 1.2 final is almost out, I am curious if there are already projects that use the new object level permissions / row level permissions system. [Django-authority](http://packages.python.org/django-authority/), which is a possible solution for Django up to 1.1, has not been updated for a while, and does not (...
I used <https://github.com/lukaszb/django-guardian> when it was still in version 0.2 on a project and it was rather complete and bug free. Yes I did have to write my own 'check\_permission' view decorator as at the time it didn't have it included yet - but at least from version 1.0 it is there. The author was also ve...
Python Terminated Thread Cannot Restart
2,822,677
5
2010-05-12T20:51:59Z
2,822,737
10
2010-05-12T21:01:10Z
[ "python", "multithreading", "runtime-error" ]
I have a thread that gets executed when some action occurs. Given the logic of the program, the thread cannot possibly be started while another instance of it is still running. Yet when I call it a second time, I get a "RuntimeError: thread already started" error. I added a check to see if it is actually alive using th...
Threads cannot be restarted. You must re-create the Thread in order to start it again.
Communication between threads in PySide
2,823,112
15
2010-05-12T22:06:22Z
4,232,911
14
2010-11-20T13:18:59Z
[ "python", "multithreading", "pyqt", "pyqt4", "pyside" ]
I have a thread which produces some data (a python list) and which shall be available for a widget that will read and display the data in the main thread. Actually, I'm using QMutex to provide access to the data, in this way: ``` class Thread(QThread): def get_data(self): QMutexLock(self.mutex) return deepco...
I think this should work with PySide. if not work please report a bug on PySide bugzilla(http://bugs.openbossa.org/) with a small test case: ``` class Thread(QThread): dataReady = Signal(object) def run(self): while True: self.data = slowly_produce_data() # this will add a ref to self.data and avo...
Making a string out of a string and an integer in Python
2,823,211
16
2010-05-12T22:27:57Z
2,823,221
22
2010-05-12T22:30:09Z
[ "python", "string", "random", "integer", "python-3.x" ]
I get this error when trying to take an integer and prepend "b" to it, converting it into a string: ``` File "program.py", line 19, in getname name = "b" + num TypeError: Can't convert 'int' object to str implicitly ``` That's related to this function: ``` num = random.randint(1,25) name = "b" + num ```
``` name = 'b' + str(num) ``` or ``` name = 'b%s' % num ``` as S.Lott notes, the mingle operator '%' is deprecated for Python 3 and up. And I stole the name "mingle" from [INTERCAL](http://catb.org/~esr/intercal/stross.html) but that's how I talk about it and wanted to see it in print at least once before - like the...
Making a string out of a string and an integer in Python
2,823,211
16
2010-05-12T22:27:57Z
2,823,223
7
2010-05-12T22:30:53Z
[ "python", "string", "random", "integer", "python-3.x" ]
I get this error when trying to take an integer and prepend "b" to it, converting it into a string: ``` File "program.py", line 19, in getname name = "b" + num TypeError: Can't convert 'int' object to str implicitly ``` That's related to this function: ``` num = random.randint(1,25) name = "b" + num ```
Python won't automatically convert types in the way that languages such as JavaScript or PHP do. You have to convert it to a string, or use a formatting method. ``` name="b"+str(num) ``` or printf style formatting... ``` name="b%s" % (num,) ``` or the new .format string method ``` name="b{0}".format(num) ```
Parsing a string representing a float *with an exponent* in Python
2,823,269
5
2010-05-12T22:40:54Z
2,823,294
11
2010-05-12T22:45:41Z
[ "python" ]
I have a large file with numbers in the form of `6,52353753563E-7`. So there's an exponent in that string. `float()` dies on this. While I could write custom code to pre-process the string into something `float()` can eat, I'm looking for the pythonic way of converting these into a float (something like a format strin...
Nothing to do with exponent. Problem is comma instead of decimal point. ``` >>> float("6,52353753563E-7") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for float(): 6,52353753563E-7 >>> float("6.52353753563E-7") 6.5235375356299998e-07 ``` For a general approach, ...
Generate a random letter in Python
2,823,316
60
2010-05-12T22:48:44Z
2,823,331
98
2010-05-12T22:51:54Z
[ "python", "random", "python-3.x" ]
Is there a way to generate random letters in Python (like random.randint but for letters)? The range functionality of random.randint would be nice but having a generator that just outputs a random letter would be better than nothing.
Simple: ``` >>> import string >>> string.letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> import random >>> random.choice(string.letters) 'j' ``` [`string.letters`](http://docs.python.org/library/string.html#string.letters) returns a string containing the lower case and upper case letters according ...
Generate a random letter in Python
2,823,316
60
2010-05-12T22:48:44Z
2,823,334
35
2010-05-12T22:52:59Z
[ "python", "random", "python-3.x" ]
Is there a way to generate random letters in Python (like random.randint but for letters)? The range functionality of random.randint would be nice but having a generator that just outputs a random letter would be better than nothing.
``` >>> import random >>> import string >>> random.choice(string.ascii_letters) 'g' ```
Generate a random letter in Python
2,823,316
60
2010-05-12T22:48:44Z
2,823,358
16
2010-05-12T22:55:09Z
[ "python", "random", "python-3.x" ]
Is there a way to generate random letters in Python (like random.randint but for letters)? The range functionality of random.randint would be nice but having a generator that just outputs a random letter would be better than nothing.
``` >>> import random >>> import string >>> random.choice(string.ascii_lowercase) 'b' ```
Generate a random letter in Python
2,823,316
60
2010-05-12T22:48:44Z
11,749,761
16
2012-07-31T22:11:01Z
[ "python", "random", "python-3.x" ]
Is there a way to generate random letters in Python (like random.randint but for letters)? The range functionality of random.randint would be nice but having a generator that just outputs a random letter would be better than nothing.
``` >>>def random_char(y): return ''.join(random.choice(string.ascii_letters) for x in range(y)) >>>print (random_char(5)) >>>fxkea ``` to generate y number of random characters
Is there a method that tells my program to quit?
2,823,472
14
2010-05-12T23:22:40Z
2,823,480
44
2010-05-12T23:24:44Z
[ "python", "exit", "quit" ]
For the "q" (quit) option in my program menu, I have the following code: ``` elif choice == "q": print() ``` That worked all right until I put it in an infinite loop, which kept printing blank lines. Is there a method that can quit the program? Else, can you think of another solution?
One way is to do: ``` sys.exit(0) ``` You will have to `import sys` of course. Another way is to `break` out of your infinite loop. For example, you could do this: ``` while True: choice = get_input() if choice == "a": # do something elif choice == "q": break ``` Yet another way is to p...
Is there a method that tells my program to quit?
2,823,472
14
2010-05-12T23:22:40Z
3,013,190
9
2010-06-10T09:31:27Z
[ "python", "exit", "quit" ]
For the "q" (quit) option in my program menu, I have the following code: ``` elif choice == "q": print() ``` That worked all right until I put it in an infinite loop, which kept printing blank lines. Is there a method that can quit the program? Else, can you think of another solution?
The actual way to end a program, is to call ``` raise SystemExit ``` It's what `sys.exit` [does, anyway](http://docs.python.org/library/exceptions.html#exceptions.SystemExit). A plain `SystemExit`, or with `None` as a single argument, sets the process' exit code to zero. Any non-integer exception value (`raise Syste...
what if i keep my class members are public?
2,824,579
2
2010-05-13T05:26:20Z
2,824,654
13
2010-05-13T05:50:03Z
[ "c++", "python" ]
In c++ instance variables are private by default,in Python variables are public by default i have two questions regarding the same:- 1: why Python have all the members are public by default? 2: People say you should your member data should be private what if i make my data to be public? what are the disadvantages of...
You can use a leading underscore in the name to tell readers of the code that the name in question is an internal detail and they must not rely on it remaining in future versions. Such a convention is really all you need -- why weigh the language down with an enforcement mechanism? Data, just like methods, should be p...
Final classes in Python 3.x- something Guido isn't telling me?
2,825,364
25
2010-05-13T08:35:43Z
2,825,423
11
2010-05-13T08:49:26Z
[ "python", "inheritance" ]
This question is built on top of many assumptions. If one assumption is wrong, then the whole thing falls over. I'm still relatively new to Python and have just entered the curious/exploratory phase. It is my understanding that Python does not support the creating of classes that cannot be subclassed (*final* classes)...
You could do this only via the C API. Clear the [`Py_TPFLAGS_BASETYPE`](http://docs.python.org/py3k/c-api/typeobj.html#Py_TPFLAGS_BASETYPE) bit of the `tp_flags` of the type object. Like this: <http://svn.python.org/projects/python/trunk/Objects/boolobject.c> (vs [intobject.c](http://svn.python.org/projects/python/tru...
Final classes in Python 3.x- something Guido isn't telling me?
2,825,364
25
2010-05-13T08:35:43Z
2,826,746
35
2010-05-13T12:34:27Z
[ "python", "inheritance" ]
This question is built on top of many assumptions. If one assumption is wrong, then the whole thing falls over. I'm still relatively new to Python and have just entered the curious/exploratory phase. It is my understanding that Python does not support the creating of classes that cannot be subclassed (*final* classes)...
You can simulate the same effect from Python 3.x quite easily: ``` class Final(type): def __new__(cls, name, bases, classdict): for b in bases: if isinstance(b, Final): raise TypeError("type '{0}' is not an acceptable base type".format(b.__name__)) return type.__new__(cl...
Correct approach to validate attributes of an instance of class
2,825,452
32
2010-05-13T08:53:16Z
2,825,580
39
2010-05-13T09:16:25Z
[ "python", "design" ]
Having a simple Python class like this: ``` class Spam(object): __init__(self, description, value): self.description = description self.value = value ``` I would like to check the following constraints: * "description cannot be empty" * "value must be greater than zero" Should I: 1. validate d...
You can use Python [properties](http://docs.python.org/library/functions.html#property) to cleanly apply rules to each field separately, and enforce them even when client code tries to change the field: ``` class Spam(object): def __init__(self, description, value): self.description = description s...
Does Google appengine cache external requests?
2,826,238
3
2010-05-13T11:05:29Z
2,826,696
8
2010-05-13T12:26:36Z
[ "python", "google-app-engine", "caching", "urllib2" ]
I have a very simple application running on appengine that requests a web page every five minutes and parses for a specific piece of data. Everything works fine except that the response I get back from the external request (using urllib2) doesn't reflect the latest changes to the page. Sometimes it takes a few minutes...
It appears that this is an issue the App Engine [team is aware of](http://code.google.com/p/googleappengine/issues/detail?id=739). The suggested workaround is to set Cache-Control header with max-age in seconds: ``` result = urlfetch.fetch(url, headers = {'Cache-Control' : 'max-age=240'}) ``` should hopefully work fo...
Angles between two n-dimensional vectors in Python
2,827,393
27
2010-05-13T14:06:21Z
2,827,466
19
2010-05-13T14:13:28Z
[ "python", "vector", "angle" ]
I need to determine the angle(s) between two n-dimensional vectors in Python. For example, the input can be two lists like the following: `[1,2,3,4]` and `[6,7,8,9]`.
Using [numpy](http://numpy.scipy.org/) (highly recommended), you would do: ``` from numpy import (array, dot, arccos, clip) from numpy.linalg import norm u = array([1.,2,3,4]) v = ... c = dot(u,v)/norm(u)/norm(v) # -> cosine of the angle angle = arccos(clip(c, -1, 1)) # if you really want the angle ```
Angles between two n-dimensional vectors in Python
2,827,393
27
2010-05-13T14:06:21Z
2,827,475
32
2010-05-13T14:14:28Z
[ "python", "vector", "angle" ]
I need to determine the angle(s) between two n-dimensional vectors in Python. For example, the input can be two lists like the following: `[1,2,3,4]` and `[6,7,8,9]`.
``` import math def dotproduct(v1, v2): return sum((a*b) for a, b in zip(v1, v2)) def length(v): return math.sqrt(dotproduct(v, v)) def angle(v1, v2): return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2))) ``` **Note**: this will fail when the vectors have either the same or the opposite direction. ...
Angles between two n-dimensional vectors in Python
2,827,393
27
2010-05-13T14:06:21Z
13,849,249
34
2012-12-12T21:47:38Z
[ "python", "vector", "angle" ]
I need to determine the angle(s) between two n-dimensional vectors in Python. For example, the input can be two lists like the following: `[1,2,3,4]` and `[6,7,8,9]`.
**Note**: all of the other answers here will fail if the two vectors have either the same direction (ex, `(1, 0, 0)`, `(1, 0, 0)`) or opposite directions (ex, `(-1, 0, 0)`, `(1, 0, 0)`). Here is a function which will correctly handle these cases: ``` import numpy as np def unit_vector(vector): """ Returns the un...
Python: create object and add attributes to it
2,827,623
145
2010-05-13T14:34:03Z
2,827,664
182
2010-05-13T14:41:55Z
[ "python", "class", "object", "attributes" ]
I want to create a dynamic object (inside another object) in Python and then add attributes to it. I tried: ``` obj = someobject obj.a = object() setattr(obj.a, 'somefield', 'somevalue') ``` but this didn't work. Any ideas? *edit:* I am setting the attributes from a `for` loop which loops through a list of values...
The built-in `object` can be instantiated but can't have any attributes set on it. (I wish it could, for this exact purpose.) It doesn't have a `__dict__` to hold the attributes. I generally just do this: ``` class Object(object): pass a = Object() a.somefield = somevalue ``` When I can, I give the `Object` cla...
Python: create object and add attributes to it
2,827,623
145
2010-05-13T14:34:03Z
2,827,726
23
2010-05-13T14:48:36Z
[ "python", "class", "object", "attributes" ]
I want to create a dynamic object (inside another object) in Python and then add attributes to it. I tried: ``` obj = someobject obj.a = object() setattr(obj.a, 'somefield', 'somevalue') ``` but this didn't work. Any ideas? *edit:* I am setting the attributes from a `for` loop which loops through a list of values...
There are a few ways to reach this goal. Basically you need an object which is extendable. ``` obj.a = type('Test', (object,), {}) obj.a.b = 'fun' obj.b = lambda:None class Test: pass obj.c = Test() ```
Python: create object and add attributes to it
2,827,623
145
2010-05-13T14:34:03Z
2,827,734
103
2010-05-13T14:49:46Z
[ "python", "class", "object", "attributes" ]
I want to create a dynamic object (inside another object) in Python and then add attributes to it. I tried: ``` obj = someobject obj.a = object() setattr(obj.a, 'somefield', 'somevalue') ``` but this didn't work. Any ideas? *edit:* I am setting the attributes from a `for` loop which loops through a list of values...
You could use my ancient [Bunch](http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/?in=user-97991) recipe, but if you don't want to make a "bunch class", a very simple one already exists in Python -- all functions can have arbitrary attributes (including lambda functions). So,...
Python: create object and add attributes to it
2,827,623
145
2010-05-13T14:34:03Z
18,776,386
11
2013-09-13T00:32:55Z
[ "python", "class", "object", "attributes" ]
I want to create a dynamic object (inside another object) in Python and then add attributes to it. I tried: ``` obj = someobject obj.a = object() setattr(obj.a, 'somefield', 'somevalue') ``` but this didn't work. Any ideas? *edit:* I am setting the attributes from a `for` loop which loops through a list of values...
Now you can do (not sure if it's the same answer as evilpie): ``` MyObject = type('MyObject', (object,), {}) obj = MyObject() obj.value = 42 ```
Python: create object and add attributes to it
2,827,623
145
2010-05-13T14:34:03Z
32,036,628
20
2015-08-16T15:13:33Z
[ "python", "class", "object", "attributes" ]
I want to create a dynamic object (inside another object) in Python and then add attributes to it. I tried: ``` obj = someobject obj.a = object() setattr(obj.a, 'somefield', 'somevalue') ``` but this didn't work. Any ideas? *edit:* I am setting the attributes from a `for` loop which loops through a list of values...
There is [`types.SimpleNamespace` class in Python 3.3+](https://docs.python.org/3/library/types.html#types.SimpleNamespace): ``` obj = someobject obj.a = SimpleNamespace() for p in params: setattr(obj.a, p, value) # obj.a.attr1 ```
sorting arrays in numpy by column
2,828,059
97
2010-05-13T15:32:57Z
2,828,121
233
2010-05-13T15:39:39Z
[ "python", "sorting", "numpy", "scipy" ]
How can I sort an array in numpy by the nth column? e.g. ``` a = array([[1,2,3],[4,5,6],[0,0,1]]) ``` I'd like to sort by the second column, such that I get back: ``` array([[0,0,1],[1,2,3],[4,5,6]]) ``` thanks.
I suppose this works: `a[a[:,1].argsort()]`
sorting arrays in numpy by column
2,828,059
97
2010-05-13T15:32:57Z
2,828,371
45
2010-05-13T16:10:17Z
[ "python", "sorting", "numpy", "scipy" ]
How can I sort an array in numpy by the nth column? e.g. ``` a = array([[1,2,3],[4,5,6],[0,0,1]]) ``` I'd like to sort by the second column, such that I get back: ``` array([[0,0,1],[1,2,3],[4,5,6]]) ``` thanks.
@steve's is actually the most elegant way of doing it. For the "correct" way see the order keyword argument of [numpy.ndarray.sort](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sort.html#numpy.ndarray.sort) However, you'll need to view your array as an array with fields (a structured array). The...
sorting arrays in numpy by column
2,828,059
97
2010-05-13T15:32:57Z
7,588,949
12
2011-09-28T20:05:37Z
[ "python", "sorting", "numpy", "scipy" ]
How can I sort an array in numpy by the nth column? e.g. ``` a = array([[1,2,3],[4,5,6],[0,0,1]]) ``` I'd like to sort by the second column, such that I get back: ``` array([[0,0,1],[1,2,3],[4,5,6]]) ``` thanks.
From the python docs wiki [link](http://wiki.python.org/moin/HowTo/Sorting), I think you can do : ``` a = ([[1,2,3],[4,5,6],[0,0,1]]); a = sorted(a, key=lambda a_entry: a_entry[1]) print a ``` Output is: ``` [[[0, 0, 1], [1, 2, 3], [4, 5, 6]]] ```
How do I find difference between times in different timezones in Python?
2,828,158
5
2010-05-13T15:43:57Z
2,828,249
7
2010-05-13T15:55:01Z
[ "python", "datetime", "timezone" ]
I am trying to calculate difference(in seconds) between two date/times formatted as following: 2010-05-11 17:07:33 UTC 2010-05-11 17:07:33 EDT ``` time1 = '2010-05-11 17:07:33 UTC' time2 = '2010-05-11 17:07:33 EDT' delta = time.mktime(time.strptime(time1,"%Y-%m-%d %H:%M:%S %Z"))-\ time.mktime(time.strptime(t...
Check out the [**pytz**](http://pytz.sourceforge.net/) world timezone definitions library. > This library allows accurate and cross platform timezone calculations using Python 2.3 or higher. It also solves the issue of ambiguous times at the end of daylight savings, which you can read more about in the Python Library ...
How do I find difference between times in different timezones in Python?
2,828,158
5
2010-05-13T15:43:57Z
2,828,294
9
2010-05-13T16:01:16Z
[ "python", "datetime", "timezone" ]
I am trying to calculate difference(in seconds) between two date/times formatted as following: 2010-05-11 17:07:33 UTC 2010-05-11 17:07:33 EDT ``` time1 = '2010-05-11 17:07:33 UTC' time2 = '2010-05-11 17:07:33 EDT' delta = time.mktime(time.strptime(time1,"%Y-%m-%d %H:%M:%S %Z"))-\ time.mktime(time.strptime(t...
In addition to `pytz`, check out [`python-dateutil`](http://labix.org/python-dateutil). The [`relativedelta`](http://labix.org/python-dateutil#head-ba5ffd4df8111d1b83fc194b97ebecf837add454) functionality is outstanding. Here's a sample of using them together: ``` from datetime import datetime from dateutil.relatived...
SQLAlchemy returns tuple not dictionary
2,828,248
5
2010-05-13T15:54:54Z
2,828,734
7
2010-05-13T17:04:38Z
[ "python", "sqlalchemy" ]
I've updated SQLAlchemy to 0.6 but it broke everything. I've noticed it returns tuple not a dictionary anymore. Here's a sample query: ``` query = session.query(User.id, User.username, User.email).filter(and_(User.id == id, User.username == username)).limit(1) result = session.execute(query).fetchone() ``` This piece...
Are you sure it isn't a [ResultProxy](http://www.sqlalchemy.org/docs/reference/sqlalchemy/connections.html#sqlalchemy.engine.base.ResultProxy) which pretends to be a tuple when you print it? Many objects in the ORM are not what their `__str__` function returns.
SQLAlchemy returns tuple not dictionary
2,828,248
5
2010-05-13T15:54:54Z
2,848,519
28
2010-05-17T11:17:06Z
[ "python", "sqlalchemy" ]
I've updated SQLAlchemy to 0.6 but it broke everything. I've noticed it returns tuple not a dictionary anymore. Here's a sample query: ``` query = session.query(User.id, User.username, User.email).filter(and_(User.id == id, User.username == username)).limit(1) result = session.execute(query).fetchone() ``` This piece...
session.execute has never returned a dict, it returns a RowProxy object, that can be indexed *like* a dict using either integer keys for positional lookup, string keys for label based lookup up or Column objects to lookup the value of that column. The problem here is that `session.execute(query)` doesn't do what you se...
Conversion of strings like \\uXXXX in python
2,828,284
14
2010-05-13T16:00:43Z
2,828,310
20
2010-05-13T16:03:00Z
[ "python", "unicode" ]
I have a string like \uXXXX (representation) and I need to convert it into unicode. I receive it from 3rd party service so python interpreter doesn't convert it and I need conversion in my code. How do I do it in Python? ``` >>> s u'\\u0e4f\\u032f\\u0361\\u0e4f' ```
``` >>> u'\\u0e4f\\u032f\\u0361\\u0e4f'.decode('unicode-escape') u'\u0e4f\u032f\u0361\u0e4f' >>> print u'\\u0e4f\\u032f\\u0361\\u0e4f'.decode('unicode-escape') ๏̯͡๏ ```
Build problems when adding `__str__` method to Boost Python C++ class
2,828,903
12
2010-05-13T17:31:01Z
3,084,341
21
2010-06-21T11:48:47Z
[ "python", "boost-python" ]
I have started to play around with boost python a bit and ran into a problem. I tried to expose a C++ class to python which posed no problems. But I can't seem to manage to implement the `__str__` functionality for the class without getting build errors I don't understand. I'm using boost 1\_42 prebuild by boostpro. I...
I recently encountered this problem; The solution that worked was to explicitly resolve the `str` and `self` on this line: ``` .def(str(self)) ``` So that it becomes: ``` .def(self_ns::str(self_ns::self)) ``` I don't know why this is necessary, (knowing something of the overload-resolution complication that goes on...
Build problems when adding `__str__` method to Boost Python C++ class
2,828,903
12
2010-05-13T17:31:01Z
11,217,214
9
2012-06-26T23:09:47Z
[ "python", "boost-python" ]
I have started to play around with boost python a bit and ran into a problem. I tried to expose a C++ class to python which posed no problems. But I can't seem to manage to implement the `__str__` functionality for the class without getting build errors I don't understand. I'm using boost 1\_42 prebuild by boostpro. I...
I ran into the same thing. Adding this line (instead of qualifying str and self) also works: ``` using self_ns::str; ```
Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call
2,828,953
19
2010-05-13T17:37:52Z
2,829,036
48
2010-05-13T17:46:55Z
[ "python", "stdout" ]
Is there a way in Python to silence stdout without wrapping a function call like following? Original Broken Code: ``` from sys import stdout from copy import copy save_stdout = copy(stdout) stdout = open('trash','w') foo() stdout = save_stdout ``` Edit: Corrected code from Alex Martelli ``` import sys save_stdout =...
Assigning the `stdout` variable as you're doing has no effect whatsoever, assuming `foo` contains `print` statements -- yet another example of why you should never import stuff from *inside* a module (as you're doing here), but always a module as a whole (then use qualified names). The `copy` is irrelevant, by the way....
Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call
2,828,953
19
2010-05-13T17:37:52Z
2,829,095
8
2010-05-13T17:54:59Z
[ "python", "stdout" ]
Is there a way in Python to silence stdout without wrapping a function call like following? Original Broken Code: ``` from sys import stdout from copy import copy save_stdout = copy(stdout) stdout = open('trash','w') foo() stdout = save_stdout ``` Edit: Corrected code from Alex Martelli ``` import sys save_stdout =...
Why do you think this is inefficient? Did you *test* it? By the way, it does not work at all because you are using the `from ... import` statement. Replacing `sys.stdout` is fine, but don't make a copy and don't use a temporary file. Open the null device instead: ``` import sys import os def foo(): print "abc" o...
Catch a thread's exception in the caller thread in Python
2,829,329
94
2010-05-13T18:35:01Z
2,830,127
60
2010-05-13T20:36:46Z
[ "python", "multithreading", "exception-handling", "exception" ]
I'm very new to Python and multithreaded programming in general. Basically, I have a script that will copy files to another location. I would like this to be placed in another thread so I can output `....` to indicate that the script is still running. The problem that I am having is that if the files cannot be copied ...
The problem is that `thread_obj.start()` returns immediately. The child thread that you spawned executes in its own context, with its own stack. Any exception that occurs there is in the context of the child thread, and it is in its own stack. One way I can think of right now to communicate this information to the pare...
Catch a thread's exception in the caller thread in Python
2,829,329
94
2010-05-13T18:35:01Z
2,830,277
192
2010-05-13T20:59:42Z
[ "python", "multithreading", "exception-handling", "exception" ]
I'm very new to Python and multithreaded programming in general. Basically, I have a script that will copy files to another location. I would like this to be placed in another thread so I can output `....` to indicate that the script is still running. The problem that I am having is that if the files cannot be copied ...
You have to think of threads in terms of phone calls. Consider this. > You call up the local city council and ask a question. While they find the answer for you, you hold. When they have the answer, they'll tell it to you, and then you hang up. If for some reason they can't find the answer (exception), they will tell...
Catch a thread's exception in the caller thread in Python
2,829,329
94
2010-05-13T18:35:01Z
6,874,161
18
2011-07-29T13:48:30Z
[ "python", "multithreading", "exception-handling", "exception" ]
I'm very new to Python and multithreaded programming in general. Basically, I have a script that will copy files to another location. I would like this to be placed in another thread so I can output `....` to indicate that the script is still running. The problem that I am having is that if the files cannot be copied ...
Although it is not possible to directly catch an exception thrown in a different thread, here's a code to quite transparently obtain something very close to this functionality. Your child thread must subclass the `ExThread` class instead of `threading.Thread` and the parent thread must call the `child_thread.join_with_...
Catch a thread's exception in the caller thread in Python
2,829,329
94
2010-05-13T18:35:01Z
12,808,634
14
2012-10-09T21:24:37Z
[ "python", "multithreading", "exception-handling", "exception" ]
I'm very new to Python and multithreaded programming in general. Basically, I have a script that will copy files to another location. I would like this to be placed in another thread so I can output `....` to indicate that the script is still running. The problem that I am having is that if the files cannot be copied ...
The [`concurrent.futures`](http://docs.python.org/py3k/library/concurrent.futures.html) module makes it simple to do work in separate threads (or processes) and handle any resulting exceptions: ``` import concurrent.futures import shutil def copytree_with_dots(src_path, dst_path): with concurrent.futures.ThreadPo...
What's the scope of a Python variable declared in an if statement?
2,829,528
101
2010-05-13T19:07:45Z
2,829,549
19
2010-05-13T19:10:02Z
[ "python", "variables", "if-statement", "scope", "local-variables" ]
I'm new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly: ``` if __name__ == '__main__': x = 1 print x ``` In other languages I've worked in, this code would throw an exception, as the `x` variable is local to the `if` statement and s...
Yes, they're in the same "local scope", and actually code like this is common in Python: ``` if condition: x = 'something' else: x = 'something else' use(x) ``` Note that `x` isn't declared or initialized before the condition, like it would be in C or Java, for example.
What's the scope of a Python variable declared in an if statement?
2,829,528
101
2010-05-13T19:07:45Z
2,829,580
24
2010-05-13T19:13:14Z
[ "python", "variables", "if-statement", "scope", "local-variables" ]
I'm new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly: ``` if __name__ == '__main__': x = 1 print x ``` In other languages I've worked in, this code would throw an exception, as the `x` variable is local to the `if` statement and s...
Scope in python follows this order: * Search the local scope * Search the scope of any enclosing functions * Search the global scope * Search the built-ins ([source](http://docs.python.org/tutorial/classes.html#python-scopes-and-namespaces)) Notice that `if` and other looping/branching constructs are not listed - on...
What's the scope of a Python variable declared in an if statement?
2,829,528
101
2010-05-13T19:07:45Z
2,829,642
90
2010-05-13T19:21:40Z
[ "python", "variables", "if-statement", "scope", "local-variables" ]
I'm new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly: ``` if __name__ == '__main__': x = 1 print x ``` In other languages I've worked in, this code would throw an exception, as the `x` variable is local to the `if` statement and s...
Python variables are scoped to the innermost function or module; control blocks like `if` and `while` blocks don't count. (IIUC, this is also how JavaScript's `var`-declared variables work.)
How should I grab pairs from a list in python?
2,829,887
3
2010-05-13T19:59:55Z
2,829,931
11
2010-05-13T20:07:06Z
[ "python", "list" ]
Say I have a list that looks like this: ``` ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10'] ``` Using Python, how would I grab pairs from it, where each item is included in a pair with both the item before and after it? ``` ['item1', 'item2'] ['item2', 'item3'] ['item3', '...
A quick and simple way of doing it would be something like: ``` a = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10'] print zip(a, a[1:]) ``` Which will produce the following: ``` [('item1', 'item2'), ('item2', 'item3'), ('item3', 'item4'), ('item4', 'item5'), ('item5', 'it...
What are the implications of running python with the optimize flag?
2,830,358
21
2010-05-13T21:14:38Z
2,830,411
13
2010-05-13T21:23:27Z
[ "python", "optimization" ]
I cannot seem to find a good simple explanation of what python does differently when running with the -O or optimize flag.
`assert` statements are completely eliminated, as are statement blocks of the form `if __debug__: ...` (so you can put your debug code in such statements blocks and just run with `-O` to avoid that debug code). With `-OO`, in addition, docstrings are also eliminated.
What are the implications of running python with the optimize flag?
2,830,358
21
2010-05-13T21:14:38Z
2,830,413
18
2010-05-13T21:23:36Z
[ "python", "optimization" ]
I cannot seem to find a good simple explanation of what python does differently when running with the -O or optimize flag.
From [the docs](http://docs.python.org/tutorial/modules.html): > When the Python interpreter is invoked > with the -O flag, optimized code is > generated and stored in .pyo files. > The optimizer currently doesn’t help > much; it only removes assert > statements. When -O is used, all > bytecode is optimized; .pyc fi...
Matching id's in BeautifulSoup
2,830,530
14
2010-05-13T21:42:23Z
2,830,550
34
2010-05-13T21:46:28Z
[ "python", "beautifulsoup" ]
I'm using BeautifulSoup - python module. I have to find any reference to the div's with id like: 'post-#'. For example: ``` <div id="post-45">...</div> <div id="post-334">...</div> ``` How can I filter this? ``` html = '<div id="post-45">...</div> <div id="post-334">...</div>' soupHandler = BeautifulSoup(html) print...
You can pass a function to [findAll](http://www.crummy.com/software/BeautifulSoup/documentation.html#The%20basic%20find%20method%3a%20findAll%28name,%20attrs,%20recursive,%20text,%20limit,%20%2a%2akwargs%29): ``` >>> print soupHandler.findAll('div', id=lambda x: x and x.startswith('post-')) [<div id="post-45">...</div...
Does a multithreaded crawler in Python really speed things up?
2,830,880
9
2010-05-13T23:02:42Z
2,830,905
8
2010-05-13T23:08:53Z
[ "python", "multithreading", "gil" ]
Was looking to write a little web crawler in python. I was starting to investigate writing it as a multithreaded script, one pool of threads downloading and one pool processing results. Due to the GIL would it actually do simultaneous downloading? How does the GIL affect a web crawler? Would each thread pick some data ...
The GIL is not held by the Python interpreter when doing network operations. If you are doing work that is network-bound (like a crawler), you can safely ignore the effects of the GIL. On the other hand, you may want to measure your performance if you create lots of threads doing processing (after downloading). Limiti...
Python Instance Variable as Default Parameter
2,831,112
11
2010-05-14T00:19:32Z
2,831,119
13
2010-05-14T00:21:27Z
[ "python" ]
I have am writing a Python function that takes a timeout value as a parameter. Normally, the user will always use the same timeout value, but on occasion he may want to wait slightly longer. The timeout value is stored as a class instance variable. I want to use the class' timeout instance variable as the default param...
A common way is to use `None` as the default value ``` def _writeAndWait (self, string, timeout=None): if timeout is None: timeout = self._timeout ```
Python Instance Variable as Default Parameter
2,831,112
11
2010-05-14T00:19:32Z
2,831,215
11
2010-05-14T00:56:48Z
[ "python" ]
I have am writing a Python function that takes a timeout value as a parameter. Normally, the user will always use the same timeout value, but on occasion he may want to wait slightly longer. The timeout value is stored as a class instance variable. I want to use the class' timeout instance variable as the default param...
The short answer to your question is no, you cannot eliminate the if statement, because Python examines the signature only once, and so the default is shared across all calls. Consider, for example: ``` def addit(x, L=[]): L.append(x) return L ``` Versus: ``` def addit(x,L=None): if L is None: ...
Python Sets vs Lists
2,831,212
68
2010-05-14T00:55:55Z
2,831,242
87
2010-05-14T01:04:04Z
[ "python", "performance", "list", "set" ]
In Python, which data structure is more efficient/speedy? Assuming that order is not important to me and I would be checking for duplicates anyway, is a Python set slower than a Python list?
It depends on what you are intending to do with it. Sets are significantly faster when it comes to determining if an object is present in the set (as in `x in s`), but are slower than lists when it comes to iterating over their contents. You can use the [timeit module](https://docs.python.org/library/timeit.html) to ...
Python Sets vs Lists
2,831,212
68
2010-05-14T00:55:55Z
17,945,009
75
2013-07-30T10:51:12Z
[ "python", "performance", "list", "set" ]
In Python, which data structure is more efficient/speedy? Assuming that order is not important to me and I would be checking for duplicates anyway, is a Python set slower than a Python list?
When you want to store some values which you'll be iterating over, Python's list constructs are slightly faster. However, if you'll be storing (unique) values in order to check for their existence, then sets are significantly faster. It turns out tuples perform in almost exactly the same way as lists, but they do use ...
"isnotnan" functionality in numpy, can this be more pythonic?
2,831,516
21
2010-05-14T02:30:59Z
2,831,551
47
2010-05-14T02:41:47Z
[ "arrays", "numpy", "python", null ]
I need a function that returns non-NaN values from an array. Currently I am doing it this way: ``` >>> a = np.array([np.nan, 1, 2]) >>> a array([ NaN, 1., 2.]) >>> np.invert(np.isnan(a)) array([False, True, True], dtype=bool) >>> a[np.invert(np.isnan(a))] array([ 1., 2.]) ``` Python: 2.6.4 numpy: 1.3.0 Plea...
``` a = a[~np.isnan(a)] ```
"isnotnan" functionality in numpy, can this be more pythonic?
2,831,516
21
2010-05-14T02:30:59Z
20,053,366
12
2013-11-18T16:57:15Z
[ "arrays", "numpy", "python", null ]
I need a function that returns non-NaN values from an array. Currently I am doing it this way: ``` >>> a = np.array([np.nan, 1, 2]) >>> a array([ NaN, 1., 2.]) >>> np.invert(np.isnan(a)) array([False, True, True], dtype=bool) >>> a[np.invert(np.isnan(a))] array([ 1., 2.]) ``` Python: 2.6.4 numpy: 1.3.0 Plea...
You are currently testing for anything that is not NaN and mtrw has the right way to do this. If you are interested in testing for finite numbers (is not NaN and is not INF) then you don't need an inversion and can use: ``` np.isfinite(a) ``` More pythonic and native, an easy read, and often when you want to avoid Na...
pythonic way to associate list elements with their indices
2,831,672
8
2010-05-14T03:28:02Z
2,831,677
13
2010-05-14T03:30:42Z
[ "list", "dictionary", "python", "enumerate" ]
I have a list of values and I want to put them in a dictionary that would map each value to it's index. I can do it this way: ``` >>> t = (5,6,7) >>> d = dict(zip(t, range(len(t)))) >>> d {5: 0, 6: 1, 7: 2} ``` this is not bad, but I'm looking for something more elegant. I've come across the following, but it does ...
You can use a list comprehension (or a generator, depending on your python version) to perform a simple in-place swap for your second example. --- Using a list comprehension: ``` d = dict([(y,x) for x,y in enumerate(t)]) ``` --- Using a generator expression (Python 2.4 and up): ``` d = dict((y,x) for x,y in enume...
pythonic way to associate list elements with their indices
2,831,672
8
2010-05-14T03:28:02Z
2,831,725
12
2010-05-14T03:48:13Z
[ "list", "dictionary", "python", "enumerate" ]
I have a list of values and I want to put them in a dictionary that would map each value to it's index. I can do it this way: ``` >>> t = (5,6,7) >>> d = dict(zip(t, range(len(t)))) >>> d {5: 0, 6: 1, 7: 2} ``` this is not bad, but I'm looking for something more elegant. I've come across the following, but it does ...
In Python2.7+ you can write it like this ``` >>> t = (5,6,7) >>> d = {x:i for i,x in enumerate(t)} >>> print d {5: 0, 6: 1, 7: 2} ```
Running a python script for a user-specified amount of time?
2,831,775
10
2010-05-14T04:08:55Z
2,831,811
11
2010-05-14T04:19:35Z
[ "python" ]
Sorry, this is probably a terrible question. I've **JUST** started learning python today. I've been reading a Byte of Python. Right now I have a project for Python that involves time. I can't find anything relating to time in Byte of Python, so I'll ask you: How can I run a block for a user specified amount of time an...
Try `time.time()`, which returns the current time as the number of seconds since a set time called the *epoch* (midnight on Jan. 1, 1970 for many computers). Here's one way to use it: ``` import time max_time = int(raw_input('Enter the amount of seconds you want to run this: ')) start_time = time.time() # remember w...
Running a python script for a user-specified amount of time?
2,831,775
10
2010-05-14T04:08:55Z
2,831,837
12
2010-05-14T04:28:33Z
[ "python" ]
Sorry, this is probably a terrible question. I've **JUST** started learning python today. I've been reading a Byte of Python. Right now I have a project for Python that involves time. I can't find anything relating to time in Byte of Python, so I'll ask you: How can I run a block for a user specified amount of time an...
I recommend spawning another [thread](http://docs.python.org/library/threading.html#thread-objects), making it a [daemon thread](http://docs.python.org/library/threading.html#threading.Thread.daemon), then [sleeping](http://docs.python.org/library/time.html#time.sleep) until you want the task to die. For example: ``` ...
Can't overload python socket.send
2,833,022
5
2010-05-14T09:21:21Z
2,834,134
8
2010-05-14T12:38:34Z
[ "python", "inheritance", "overloading" ]
As we can see, send method is not overloaded. ``` from socket import socket class PolySocket(socket): def __init__(self,*p): print "PolySocket init" socket.__init__(self,*p) def sendall(self,*p): print "PolySocket sendall" return socket.sendall(self,*p) def send(self,*p)...
I am sure you don't actually need it and there are other ways to solve your task (not subclassing but the real task). If you really need to mock object, go with proxy object: ``` from socket import socket class PolySocket(object): def __init__(self, *p): print "PolySocket init" self._sock = sock...
Write xml file using lxml library in Python
2,833,185
22
2010-05-14T09:48:58Z
2,833,273
34
2010-05-14T10:04:03Z
[ "python", "xml", "lxml" ]
I'm using [lxml](http://codespeak.net/lxml/tutorial.html) to create an XML file from scratch; having a code like this: ``` from lxml import etree root = etree.Element("root") root.set("interesting", "somewhat") child1 = etree.SubElement(root, "test") ``` How do I write root `Element` object to an xml file using `wri...
You can get a string from the element and then write that from [lxml tutorial](http://lxml.de/tutorial.html) ``` str = etree.tostring(root, pretty_print=True) ``` or convert to an element tree ``` et = etree.ElementTree(root) et.write(sys.stdout, pretty_print=True) ```
Parsing values from a JSON file in Python
2,835,559
517
2010-05-14T15:54:20Z
2,835,672
859
2010-05-14T16:10:15Z
[ "python", "json", "parsing" ]
I have this JSON in a file: ``` { "maps": [ { "id": "blabla", "iscategorical": "0" }, { "id": "blabla", "iscategorical": "0" } ], "masks": [ "id": "valore" ], "om_points": "value", "parameters": [ "i...
I think what Ignacio is saying is that your JSON file is incorrect. You have `[]` when you should have `{}`. `[]` are for lists, `{}` are for dictionaries. Here's how your JSON file should look, your JSON file wouldn't even load for me: ``` { "maps": [ { "id": "blabla", "iscategori...
Parsing values from a JSON file in Python
2,835,559
517
2010-05-14T15:54:20Z
13,633,860
131
2012-11-29T20:10:03Z
[ "python", "json", "parsing" ]
I have this JSON in a file: ``` { "maps": [ { "id": "blabla", "iscategorical": "0" }, { "id": "blabla", "iscategorical": "0" } ], "masks": [ "id": "valore" ], "om_points": "value", "parameters": [ "i...
Your `data.json` should look like this: ``` { "maps":[ {"id":"blabla","iscategorical":"0"}, {"id":"blabla","iscategorical":"0"} ], "masks": {"id":"valore"}, "om_points":"value", "parameters": {"id":"valore"} } ``` Your code should be: ``` import json from pprint import pp...
Parsing values from a JSON file in Python
2,835,559
517
2010-05-14T15:54:20Z
16,511,897
21
2013-05-12T20:47:46Z
[ "python", "json", "parsing" ]
I have this JSON in a file: ``` { "maps": [ { "id": "blabla", "iscategorical": "0" }, { "id": "blabla", "iscategorical": "0" } ], "masks": [ "id": "valore" ], "om_points": "value", "parameters": [ "i...
``` data = [] with codecs.open('d:\output.txt','rU','utf-8') as f: for line in f: data.append(json.loads(line)) ```
Parsing values from a JSON file in Python
2,835,559
517
2010-05-14T15:54:20Z
30,388,020
12
2015-05-22T03:44:04Z
[ "python", "json", "parsing" ]
I have this JSON in a file: ``` { "maps": [ { "id": "blabla", "iscategorical": "0" }, { "id": "blabla", "iscategorical": "0" } ], "masks": [ "id": "valore" ], "om_points": "value", "parameters": [ "i...
@Justin Peel's answer is really helpful, but if you are using Python 3 reading JSON should be done like this: ``` with open('data.json', encoding='utf-8') as data_file: data = json.loads(data_file.read()) ``` Note: use `json.loads` instead of `json.load`. In Python 3, `json.loads` takes a string parameter. `json....
How does polymorphism work in Python?
2,835,793
49
2010-05-14T16:23:42Z
2,835,815
66
2010-05-14T16:25:28Z
[ "python", "polymorphism" ]
I'm new to Python... and coming from a mostly Java background, if that accounts for anything. I'm trying to understand polymorphism in Python. Maybe the problem is that I'm expecting the concepts I already know to project into Python. But I put together the following test code: ``` class animal(object): "empty an...
The `is` operator in Python checks that the two arguments refer to the same object in memory; it is not like the `is` operator in C#. [From the docs](http://docs.python.org/reference/expressions.html#notin): > The operators is and is not test for object identity: x is y is true if and only if x and y are the same obj...
How does polymorphism work in Python?
2,835,793
49
2010-05-14T16:23:42Z
2,835,839
10
2010-05-14T16:28:31Z
[ "python", "polymorphism" ]
I'm new to Python... and coming from a mostly Java background, if that accounts for anything. I'm trying to understand polymorphism in Python. Maybe the problem is that I'm expecting the concepts I already know to project into Python. But I put together the following test code: ``` class animal(object): "empty an...
Try `isinstance(myDog, dog)` resp. `isinstance(myDog, animal)`.
How does polymorphism work in Python?
2,835,793
49
2010-05-14T16:23:42Z
2,835,879
35
2010-05-14T16:34:21Z
[ "python", "polymorphism" ]
I'm new to Python... and coming from a mostly Java background, if that accounts for anything. I'm trying to understand polymorphism in Python. Maybe the problem is that I'm expecting the concepts I already know to project into Python. But I put together the following test code: ``` class animal(object): "empty an...
phimuemue and Mark have answered your question. But this is ALSO an example of polymorphism in Python, but it's not as explicit as your inheritance based example. ``` class wolf(object): def bark(self): print "hooooowll" class dog(object): def bark(self): print "woof" def barkforme(dogtype...
tail -f in a webbrowser
2,836,838
6
2010-05-14T19:01:24Z
2,837,314
8
2010-05-14T20:14:59Z
[ "javascript", "jquery", "python", "django", "console" ]
I've created a Python script that monitors a logfile for changes (like tail -f) and displays it on a console. I would like to access the output of the Python script in a webbrowser. What would I need to create this? I was thinking about using Django and jQuery. Any tips or examples are greatly appreciated.
First create a python script that monitors the log file for changes. If you only need this for debugging - testing purposes, then it is an overkill to use Django or another web framework. It is very easy to implement Http Web server functionality using sockets. Whenever an Http GET request is coming, serve only the dif...
Python popen command. Wait until the command is finished
2,837,214
33
2010-05-14T20:00:29Z
2,837,319
49
2010-05-14T20:15:36Z
[ "python", "wait", "popen" ]
I have a script where I launch with popen a shell command. The problem is that the script doesn't wait until that popen command is finished and go continues right away. ``` om_points = os.popen(command, "w") ..... ``` How can I tell to my Python script to wait until the shell command has finished?
Depending on how you want to work your script you have two options. If you want the commands to block and not do anything while it is executing, you can just use `subprocess.call`. ``` #start and block until done subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"]) ``` If you want to do things while it i...
How do I save data from a ModelForm to database in django?
2,837,229
9
2010-05-14T20:03:03Z
2,837,396
11
2010-05-14T20:27:48Z
[ "python", "django" ]
I have a model: ``` class Cost(models.Model): project = models.ForeignKey(Project) cost = models.FloatField() date = models.DateField() ``` For the model I created a `ModelForm` class: ``` class CostForm(ModelForm): class Meta: model = Cost fields = ['date', 'cost'] ``` view.py: ```...
A couple things dont look right. 1) Project.objects.filter() will return a queryset. use Project.ojects.get() instead... it will return just a single Project object 2) You wont need to explicitly set the cost and date, that will be handled by your `instance=form.save(commit=False)` 3) you aren't using the form in yo...