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
How to merge two Python dictionaries in a single expression?
38,987
1,867
2008-09-02T07:44:30Z
19,279,501
10
2013-10-09T18:09:08Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place. ``` >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = x.update(y) >>> print z None >>>...
In python3, the `items` method [no longer returns a list](http://docs.python.org/dev/whatsnew/3.0.html#views-and-iterators-instead-of-lists), but rather a *view*, which acts like a set. In this case you'll need to take the set union since concatenating with `+` won't work: ``` dict(x.items() | y.items()) ``` For pyth...
How to merge two Python dictionaries in a single expression?
38,987
1,867
2008-09-02T07:44:30Z
26,853,961
1,255
2014-11-10T22:11:48Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place. ``` >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = x.update(y) >>> print z None >>>...
> # How can I merge two Python dictionaries in a single expression? Say you have two dicts and you want to merge them into a new dict without altering the original dicts: ``` x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} ``` The desired result is to get a new dictionary (`z`) with the values merged, and the second dict'...
How to merge two Python dictionaries in a single expression?
38,987
1,867
2008-09-02T07:44:30Z
28,753,078
22
2015-02-26T21:27:52Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place. ``` >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = x.update(y) >>> print z None >>>...
Python 3.5 (PEP 448) allows a nicer syntax option: ``` x = {'a': 1, 'b': 1} y = {'a': 2, 'c': 2} final = {**x, **y} final # {'a': 2, 'b': 1, 'c': 2} ``` Or even ``` final = {'a': 1, 'b': 1, **x, **y} ```
How to merge two Python dictionaries in a single expression?
38,987
1,867
2008-09-02T07:44:30Z
31,812,635
7
2015-08-04T14:54:58Z
[ "python", "dictionary", "mapping", "expression", "idioms" ]
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The `update()` method would be what I need, if it returned its result instead of modifying a dict in-place. ``` >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = x.update(y) >>> print z None >>>...
Simple solution using itertools that preserves order (latter dicts have precedence) ``` import itertools as it merge = lambda *args: dict(it.chain.from_iterable(it.imap(dict.iteritems, args))) ``` And it's usage: ``` >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> merge(x, y) {'a': 1, 'b': 10, 'c': 11} >>> z ...
Search and replace a line in a file in Python
39,086
170
2008-09-02T09:19:04Z
39,110
111
2008-09-02T09:42:21Z
[ "python", "file" ]
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? ``` f = open(...
I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file: ``` from tempfile import mkstemp from shutil import move from os import remove, close def replace(file_path, pattern, subst): #Create temp file fh, abs_path = mkstemp() with...
Search and replace a line in a file in Python
39,086
170
2008-09-02T09:19:04Z
39,113
8
2008-09-02T09:42:57Z
[ "python", "file" ]
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? ``` f = open(...
As lassevk suggests, write out the new file as you go, here is some example code: ``` fin = open("a.txt") fout = open("b.txt", "wt") for line in fin: fout.write( line.replace('foo', 'bar') ) fin.close() fout.close() ```
Search and replace a line in a file in Python
39,086
170
2008-09-02T09:19:04Z
290,494
182
2008-11-14T15:47:40Z
[ "python", "file" ]
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? ``` f = open(...
The shortest way would probably be to use the [fileinput module](http://docs.python.org/2/library/fileinput.html?highlight=fileinput#fileinput). For example, the following adds line numbers to a file, in-place: ``` import fileinput for line in fileinput.input("test.txt", inplace=True): print "%d: %s" % (fileinput...
Search and replace a line in a file in Python
39,086
170
2008-09-02T09:19:04Z
315,088
52
2008-11-24T19:02:28Z
[ "python", "file" ]
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? ``` f = open(...
Here's another example that was tested, and will match search & replace patterns: ``` import fileinput import sys def replaceAll(file,searchExp,replaceExp): for line in fileinput.input(file, inplace=1): if searchExp in line: line = line.replace(searchExp,replaceExp) sys.stdout.write(li...
Search and replace a line in a file in Python
39,086
170
2008-09-02T09:19:04Z
1,388,570
30
2009-09-07T10:07:25Z
[ "python", "file" ]
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? ``` f = open(...
This should work: (inplace editing) ``` import fileinput # Does a list of files, and # redirects STDOUT to the file in question for line in fileinput.input(files, inplace = 1): print line.replace("foo", "bar"), ```
Search and replace a line in a file in Python
39,086
170
2008-09-02T09:19:04Z
13,641,746
13
2012-11-30T08:51:17Z
[ "python", "file" ]
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? ``` f = open(...
Based on the answer by Thomas Watnedal. However, this does not answer the line-to-line part of the original question exactly. The function can still replace on a line-to-line basis This implementation replaces the file contents without using temporary files, as a consequence file permissions remain unchanged. Also re...
Search and replace a line in a file in Python
39,086
170
2008-09-02T09:19:04Z
21,857,132
7
2014-02-18T14:43:02Z
[ "python", "file" ]
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? ``` f = open(...
If you're wanting a generic function that replaces *any* text with some other text, this is likely the best way to go, particularly if you're a fan of regex's: ``` import re def replace( filePath, text, subs, flags=0 ): with open( filePath, "r+" ) as file: fileContents = file.read() textPattern = r...
Finding a file in a Python module distribution
39,104
12
2008-09-02T09:40:26Z
39,659
14
2008-09-02T14:26:07Z
[ "python", "distutils" ]
I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackag...
Try using pkg\_resources, which is part of setuptools (and available on all of the pythons I have access to right now): ``` >>> import pkg_resources >>> pkg_resources.resource_ filename(__name__, "foo.config") 'foo.config' >>> pkg_resources.resource_filename('tempfile', "foo.config") '/usr/lib/python2.4/foo.config' ``...
Finding a file in a Python module distribution
39,104
12
2008-09-02T09:40:26Z
9,918,496
9
2012-03-29T02:52:42Z
[ "python", "distutils" ]
I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackag...
Use `pkgutil.get_data`. It’s the cousin of `pkg_resources.resource_stream`, but in the standard library, and should work with flat filesystem installs as well as zipped packages and other importers.
What is the best way to do Bit Field manipulation in Python?
39,663
25
2008-09-02T14:28:40Z
39,760
7
2008-09-02T15:13:44Z
[ "python", "udp", "bits", "bit-fields" ]
I'm reading some MPEG Transport Stream protocol over UDP and it has some funky bitfields in it (length 13 for example). I'm using the "struct" library to do the broad unpacking, but is there a simple way to say "Grab the next 13 bits" rather than have to hand-tweak the bit manipulation? I'd like something like the way ...
It's an often-asked question. There's an [ASPN Cookbook](http://code.activestate.com/recipes/113799/) entry on it that has served me in the past. And there is an [extensive page of requirements one person would like to see from a module doing this.](http://wiki.python.org/moin/BitManipulation)
What is the best way to do Bit Field manipulation in Python?
39,663
25
2008-09-02T14:28:40Z
1,086,668
25
2009-07-06T12:20:13Z
[ "python", "udp", "bits", "bit-fields" ]
I'm reading some MPEG Transport Stream protocol over UDP and it has some funky bitfields in it (length 13 for example). I'm using the "struct" library to do the broad unpacking, but is there a simple way to say "Grab the next 13 bits" rather than have to hand-tweak the bit manipulation? I'd like something like the way ...
The [bitstring](http://python-bitstring.googlecode.com) module is designed to address just this problem. It will let you read, modify and construct data using bits as the basic building blocks. The latest versions are for Python 2.6 or later (including Python 3) but version 1.0 supported Python 2.4 and 2.5 as well. A ...
PGP signatures from Python?
39,929
5
2008-09-02T16:19:11Z
40,069
8
2008-09-02T17:15:23Z
[ "python", "security", "cross-platform", "gnupg" ]
What is the easiest way to create and verify PGP/GPG signatures from within a Python application? I can call pgp or gpg using subprocess and parse the output, but I was looking for a way that didn't require an external program to be installed (my application is cross-platform mac/windows/unix).
I think [GPGME](http://www.gnupg.org/related_software/gpgme/) and the [PyMe Python wrapper](http://pyme.sourceforge.net/) should do what you need.
javascript locals()?
39,960
17
2008-09-02T16:29:30Z
40,173
13
2008-09-02T18:01:29Z
[ "javascript", "python" ]
In python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in javascript? For instance, I would like to do something like the following: ``` var foo = function(){ alert('foo'); }; var bar = fun...
* locals() - No. * globals() - Yes. `window` is a reference to the global scope, like `globals()` in python. ``` globals()["foo"] ``` is the same as: ``` window["foo"] ```
Python deployment and /usr/bin/env portability
40,705
12
2008-09-02T21:21:14Z
40,715
8
2008-09-02T21:25:40Z
[ "python", "executable", "environment", "shebang" ]
At the beginning of all my executable Python scripts I put the [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) line: ``` #!/usr/bin/env python ``` I'm running these scripts on a system where `env python` yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Pyt...
"env" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script.
Always including the user in the django template context
41,547
25
2008-09-03T12:22:44Z
41,558
18
2008-09-03T12:31:58Z
[ "python", "django", "authentication", "session", "cookies" ]
I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests. In my template setup...
In a more general sense of not having to explicitly set variables in each view, it sounds like you want to look at writing your own [context processor](http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors). From the docs: > A context processor has a very simple interface: It's j...
Always including the user in the django template context
41,547
25
2008-09-03T12:22:44Z
269,249
31
2008-11-06T16:05:03Z
[ "python", "django", "authentication", "session", "cookies" ]
I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests. In my template setup...
@Ryan: Documentation about preprocessors is a bit small @Staale: Adding user to the Context every time one is calling the template in view, DRY Solution is very simple **A**: In your settings add ``` TEMPLATE_CONTEXT_PROCESSORS = ( 'myapp.processor_file_name.user', ) ``` **B**: In myapp/processor\_file\_name.p...
Always including the user in the django template context
41,547
25
2008-09-03T12:22:44Z
1,064,621
43
2009-06-30T16:14:29Z
[ "python", "django", "authentication", "session", "cookies" ]
I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests. In my template setup...
There is **no need** to write a context processor for the user object if you already have the [`"django.core.context_processors.auth"`](https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates) in [`TEMPLATE_CONTEXT_PROCESSORS`](https://docs.djangoproject.com/en/dev/ref/settings/#std%...
Splitting tuples in Python - best practice?
41,701
12
2008-09-03T13:48:30Z
41,707
13
2008-09-03T13:50:24Z
[ "python", "tuples" ]
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using cod...
I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tup...
Splitting tuples in Python - best practice?
41,701
12
2008-09-03T13:48:30Z
41,846
13
2008-09-03T14:51:48Z
[ "python", "tuples" ]
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using cod...
@Staale There is a better way: ``` job = dict(zip(keys, values)) ```
Standard way to open a folder window in linux?
41,969
6
2008-09-03T15:47:23Z
42,046
7
2008-09-03T16:18:25Z
[ "python", "linux", "cross-platform", "desktop" ]
I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application. On OSX, I can open a window in the finder with ``` os.system('open "%s"' % foldername) ``` and on Windows with ``` os.startfile(foldername) ``` What about unix/linux? Is there a sta...
``` os.system('xdg-open "%s"' % foldername) ``` `xdg-open` can be used for files/urls also
What is a tuple useful for?
42,034
25
2008-09-03T16:13:06Z
42,048
32
2008-09-03T16:18:53Z
[ "python", "tuples" ]
I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this differen...
* Tuples are used whenever you want to return multiple results from a function. * Since they're immutable, they can be used as keys for a dictionary (lists can't).
What is a tuple useful for?
42,034
25
2008-09-03T16:13:06Z
42,052
14
2008-09-03T16:20:59Z
[ "python", "tuples" ]
I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this differen...
Tuples make good dictionary keys when you need to combine more than one piece of data into your key and don't feel like making a class for it. ``` a = {} a[(1,2,"bob")] = "hello!" a[("Hello","en-US")] = "Hi There!" ``` I've used this feature primarily to create a dictionary with keys that are coordinates of the verti...
What is a tuple useful for?
42,034
25
2008-09-03T16:13:06Z
48,414
7
2008-09-07T13:12:28Z
[ "python", "tuples" ]
I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this differen...
I like [this explanation](http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/). Basically, you should use tuples when there's a constant structure (the 1st position always holds one type of value and the second another, and so forth), and lists should be used for lists of homogeneous values. ...
Best way to extract text from a Word doc without using COM/automation?
42,482
15
2008-09-03T20:18:47Z
43,364
8
2008-09-04T08:52:01Z
[ "python", "ms-word" ]
Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.) Antiword seems like it might be a reasonable option, but it seems like it might be abandoned. A Python so...
I use catdoc or antiword for this, whatever gives the result that is the easiest to parse. I have embedded this in python functions, so it is easy to use from the parsing system (which is written in python). ``` import os def doc_to_text_catdoc(filename): (fi, fo, fe) = os.popen3('catdoc -w "%s"' % filename) ...
Best way to extract text from a Word doc without using COM/automation?
42,482
15
2008-09-03T20:18:47Z
1,979,931
14
2009-12-30T12:23:05Z
[ "python", "ms-word" ]
Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.) Antiword seems like it might be a reasonable option, but it seems like it might be abandoned. A Python so...
(Same answer as [extracting text from MS word files in python](http://stackoverflow.com/questions/125222/extracting-text-from-ms-word-files-in-python)) Use the native Python docx module which I made this week. Here's how to extract all the text from a doc: ``` document = opendocx('Hello world.docx') # This location ...
Python re.sub MULTILINE caret match
42,581
31
2008-09-03T21:00:33Z
42,597
75
2008-09-03T21:08:02Z
[ "python", "regex", "python-2.x" ]
The Python docs say: > re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string... So what's going on when I get the following unexpected result? ...
Look at the definition of [`re.sub`](http://docs.python.org/library/re.html#re.sub): ``` sub(pattern, repl, string[, count]) ``` The 4th argument is the count, you are using `re.MULTILINE` (which is 8) as the count, not as a flag. You have to compile your regex if you wish to use flags. ``` re.sub(re.compile('^//',...
Get Last Day of the Month in Python
42,950
306
2008-09-04T00:54:44Z
42,997
43
2008-09-04T01:26:33Z
[ "python", "date" ]
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this?
EDIT: See @[Blair Conrad's answer](#43663) for a cleaner solution --- ``` >>> import datetime >>> datetime.date (2000, 2, 1) - datetime.timedelta (days = 1) datetime.date(2000, 1, 31) >>> ```
Get Last Day of the Month in Python
42,950
306
2008-09-04T00:54:44Z
43,088
32
2008-09-04T02:25:50Z
[ "python", "date" ]
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this?
EDIT: see my other answer. It has a better implementation than this one, which I leave here just in case someone's interested in seeing how one might "roll your own" calculator. @[John Millikin](#42997) gives a good answer, with the added complication of calculating the first day of the next month. The following isn'...
Get Last Day of the Month in Python
42,950
306
2008-09-04T00:54:44Z
43,663
552
2008-09-04T12:44:12Z
[ "python", "date" ]
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this?
I didn't notice this earlier when I was looking at the [documentation for the calendar module](https://docs.python.org/2/library/calendar.html), but a method called [monthrange](http://docs.python.org/library/calendar.html#calendar.monthrange) provides this information: > **monthrange(year, month)** >     Returns we...
Get Last Day of the Month in Python
42,950
306
2008-09-04T00:54:44Z
356,535
10
2008-12-10T15:47:57Z
[ "python", "date" ]
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this?
Another solution would be to do something like this: ``` from datetime import datetime def last_day_of_month(year, month): """ Work out the last day of the month """ last_days = [31, 30, 29, 28, 27] for i in last_days: try: end = datetime(year, month, i) except ValueError: ...
Get Last Day of the Month in Python
42,950
306
2008-09-04T00:54:44Z
13,565,185
37
2012-11-26T12:48:40Z
[ "python", "date" ]
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this?
If you don't want to import the `calendar` module, a simple two-step function can also be: ``` import datetime def last_day_of_month(any_day): next_month = any_day.replace(day=28) + datetime.timedelta(days=4) # this will never fail return next_month - datetime.timedelta(days=next_month.day) ``` Outputs: ``...
Get Last Day of the Month in Python
42,950
306
2008-09-04T00:54:44Z
14,994,380
14
2013-02-21T04:09:09Z
[ "python", "date" ]
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this?
This is actually pretty easy with `dateutil.relativedelta` (package python-datetutil for pip). `day=31` will always always return the last day of the month. Example: ``` from datetime import datetime from dateutil.relativedelta import relativedelta date_in_feb = datetime.datetime(2013, 2, 21) print datetime.datetime...
Get Last Day of the Month in Python
42,950
306
2008-09-04T00:54:44Z
23,447,523
7
2014-05-03T17:16:58Z
[ "python", "date" ]
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this?
``` from datetime import timedelta (any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1) ```
How to generate urls in django
43,290
22
2008-09-04T07:36:39Z
43,312
32
2008-09-04T07:54:57Z
[ "python", "django", "url", "django-urls" ]
In Django's template language, you can use `{% url [viewname] [args] %}` to generate a URL to a specific view with parameters. How can you programatically do the same in Python code? What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). ...
If you need to use something similar to the `{% url %}` template tag in your code, Django provides the `django.core.urlresolvers.reverse()`. The `reverse` function has the following signature: ``` reverse(viewname, urlconf=None, args=None, kwargs=None) ``` <https://docs.djangoproject.com/en/dev/ref/urlresolvers/>
How to generate urls in django
43,290
22
2008-09-04T07:36:39Z
55,734
8
2008-09-11T03:05:27Z
[ "python", "django", "url", "django-urls" ]
In Django's template language, you can use `{% url [viewname] [args] %}` to generate a URL to a specific view with parameters. How can you programatically do the same in Python code? What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). ...
I'm using two different approaches in my `models.py`. The first is the `permalink` decorator: ``` from django.db.models import permalink def get_absolute_url(self): """Construct the absolute URL for this Item.""" return ('project.app.views.view_name', [str(self.id)]) get_absolute_url = permalink(get_absolute...
Can I write native iPhone apps using Python
43,315
78
2008-09-04T07:59:57Z
43,331
32
2008-09-04T08:21:31Z
[ "iphone", "python", "cocoa-touch" ]
Using [PyObjC](http://pyobjc.sourceforge.net/), you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?
Not currently, currently the only languages available to access the iPhone SDK are C/C++, Objective C and Swift. There is no technical reason why this could not change in the future but I wouldn't hold your breath for this happening in the short term. That said, Objective-C and Swift really are not too scary... > # ...
Can I write native iPhone apps using Python
43,315
78
2008-09-04T07:59:57Z
43,358
51
2008-09-04T08:44:11Z
[ "iphone", "python", "cocoa-touch" ]
Using [PyObjC](http://pyobjc.sourceforge.net/), you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?
You can use PyObjC on the iPhone as well, due to the excellent work by Jay Freeman (saurik). See [iPhone Applications in Python](http://www.saurik.com/id/5). Note that this requires a jailbroken iPhone at the moment.
Can I write native iPhone apps using Python
43,315
78
2008-09-04T07:59:57Z
2,167,033
22
2010-01-30T06:03:39Z
[ "iphone", "python", "cocoa-touch" ]
Using [PyObjC](http://pyobjc.sourceforge.net/), you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?
Yes you can. You write your code in tinypy (which is restricted Python), then use tinypy to convert it to C++, and finally compile this with XCode into a native iPhone app. Phil Hassey has published a game called Elephants! using this approach. Here are more details, <http://www.philhassey.com/blog/2009/12/23/elephant...
Can I write native iPhone apps using Python
43,315
78
2008-09-04T07:59:57Z
2,637,228
20
2010-04-14T12:18:15Z
[ "iphone", "python", "cocoa-touch" ]
Using [PyObjC](http://pyobjc.sourceforge.net/), you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?
An update to the iOS Developer Agreement means that you can use whatever you like, as long as you meet the developer guidelines. Section 3.3.1, which restricted what developers could use for iOS development, has been entirely removed. Source: <http://daringfireball.net/2010/09/app_store_guidelines>
Can I write native iPhone apps using Python
43,315
78
2008-09-04T07:59:57Z
3,684,714
21
2010-09-10T12:48:14Z
[ "iphone", "python", "cocoa-touch" ]
Using [PyObjC](http://pyobjc.sourceforge.net/), you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?
It seems this is now something developers are allowed to do: the iOS Developer Agreement was changed yesterday and appears to have been ammended in a such a way as to make embedding a Python interpretter in your application legal: **SECTION 3.3.2 — INTERPRETERS** **Old:** > 3.3.2 An Application may not itself inst...
Can I write native iPhone apps using Python
43,315
78
2008-09-04T07:59:57Z
11,448,458
15
2012-07-12T09:07:42Z
[ "iphone", "python", "cocoa-touch" ]
Using [PyObjC](http://pyobjc.sourceforge.net/), you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?
Yes, nowadays you can develop apps for iOS in Python. There are two frameworks that you may want to checkout: [Kivy](http://kivy.org/) and [PyMob](http://pyzia.com/technology.html). Please consider the answers to [this question](http://stackoverflow.com/questions/10664196/is-it-possible-to-use-python-to-write-cross-p...
How to find the mime type of a file in python?
43,580
101
2008-09-04T12:07:27Z
43,588
53
2008-09-04T12:12:20Z
[ "python", "mime" ]
Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in t...
The [mimetypes module](https://docs.python.org/library/mimetypes.html) in the standard library will determine/guess the MIME type from a file extension. If users are uploading files the HTTP post will contain the MIME type of the file alongside the data. For example, Django makes this data available as an attribute of...
How to find the mime type of a file in python?
43,580
101
2008-09-04T12:07:27Z
1,662,074
8
2009-11-02T15:48:09Z
[ "python", "mime" ]
Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in t...
in python 2.6: ``` mime = subprocess.Popen("/usr/bin/file --mime PATH", shell=True, \ stdout=subprocess.PIPE).communicate()[0] ```
How to find the mime type of a file in python?
43,580
101
2008-09-04T12:07:27Z
2,133,843
39
2010-01-25T16:39:06Z
[ "python", "mime" ]
Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in t...
More reliable way than to use the mimetypes library would be to use the python-magic package. ``` import magic m = magic.open(magic.MAGIC_MIME) m.load() m.file("/tmp/document.pdf") ``` This would be equivalent to using file(1). On Django one could also make sure that the MIME type matches that of UploadedFile.conten...
How to find the mime type of a file in python?
43,580
101
2008-09-04T12:07:27Z
2,753,385
111
2010-05-02T12:02:45Z
[ "python", "mime" ]
Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in t...
The python-magic method suggested by toivotuo is outdated. [Python-magic's](http://github.com/ahupp/python-magic) current trunk is at Github and based on the readme there, finding the MIME-type, is done like this. ``` # For MIME types >>> import magic >>> mime = magic.Magic(mime=True) >>> mime.from_file("testdata/test...
How to find the mime type of a file in python?
43,580
101
2008-09-04T12:07:27Z
12,297,929
9
2012-09-06T10:22:50Z
[ "python", "mime" ]
Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in t...
There are 3 different libraries that wraps libmagic. 2 of them are available on pypi (so pip install will work): * filemagic * python-magic And another, similar to python-magic is available directly in the latest libmagic sources, and it is the one you probably have in your linux distribution. In Debian the package...
How to find the mime type of a file in python?
43,580
101
2008-09-04T12:07:27Z
21,755,201
13
2014-02-13T13:09:49Z
[ "python", "mime" ]
Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in t...
This seems to be very easy ``` >>> from mimetypes import MimeTypes >>> import urllib >>> mime = MimeTypes() >>> url = urllib.pathname2url('Upload.xml') >>> mime_type = mime.guess_type(url) >>> print mime_type ('application/xml', None) ``` Please refer [Old Post](http://stackoverflow.com/a/14412233/1182058)
Pros and Cons of different approaches to web programming in Python
43,709
24
2008-09-04T13:00:13Z
43,753
7
2008-09-04T13:24:55Z
[ "python", "frameworks", "cgi", "wsgi" ]
I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that. It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like [web.py](http:/...
If you decide to go with a framework that is WSGI-based (for instance [TurboGears](http://www.turbogears.org/2.0)), I would recommend you go through the excellent article [Another Do-It-Yourself Framework](http://pythonpaste.org/webob/do-it-yourself.html) by Ian Bicking. In the article, he builds a simple web applicat...
Pros and Cons of different approaches to web programming in Python
43,709
24
2008-09-04T13:00:13Z
43,773
17
2008-09-04T13:35:45Z
[ "python", "frameworks", "cgi", "wsgi" ]
I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that. It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like [web.py](http:/...
CGI is great for low-traffic websites, but it has some performance problems for anything else. This is because every time a request comes in, the server starts the CGI application in its own process. This is bad for two reasons: 1) Starting and stopping a process can take time and 2) you can't cache anything in memory....
Pros and Cons of different approaches to web programming in Python
43,709
24
2008-09-04T13:00:13Z
43,835
12
2008-09-04T14:11:54Z
[ "python", "frameworks", "cgi", "wsgi" ]
I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that. It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like [web.py](http:/...
The simplest web program is a CGI script, which is basically just a program whose standard output is redirected to the web browser making the request. In this approach, every page has its own executable file, which must be loaded and parsed on every request. This makes it really simple to get something up and running, ...
Modulus operation with negatives values - weird thing?
43,775
14
2008-09-04T13:36:46Z
43,780
9
2008-09-04T13:40:59Z
[ "python", "math", "modulo" ]
Can you please tell me how much is `(-2) % 5`? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.
Your Python interpreter is correct. One (stupid) way of calculating a modulus is to subtract or add the modulus until the resulting value is between 0 and (modulus − 1). e.g.: 13 mod 5 = (13 − 5) mod 5 = (13 − 10) mod 5 = 3 or in your case: −2 mod 5 = (−2 + 5) mod 5 = 3
Modulus operation with negatives values - weird thing?
43,775
14
2008-09-04T13:36:46Z
43,783
11
2008-09-04T13:41:25Z
[ "python", "math", "modulo" ]
Can you please tell me how much is `(-2) % 5`? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.
The result of the modulus operation on negatives seems to be programming language dependent and here is a listing <http://en.wikipedia.org/wiki/Modulo_operation>
Modulus operation with negatives values - weird thing?
43,775
14
2008-09-04T13:36:46Z
43,794
15
2008-09-04T13:46:23Z
[ "python", "math", "modulo" ]
Can you please tell me how much is `(-2) % 5`? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.
By the way: most programming languages would disagree with Python and give the result `-2`. Depending on the interpretation of modulus this is correct. However, the most agreed-upon mathematical definition states that the modulus of *a* and *b* is the (strictly positive) rest *r* of the division of *a* / *b*. More prec...
How do I document a module in Python?
44,084
31
2008-09-04T16:06:48Z
44,095
33
2008-09-04T16:12:23Z
[ "python", "documentation", "python-module" ]
That's it. If you want to document a function or a class, you put a string just after the definition. For instance: ``` def foo(): """This function does nothing.""" pass ``` But what about a module? How can I document what a *file.py* does?
For the packages, you can document it in `__init__.py`. For the modules, you can add a docstring simply in the module file. All the information is here: <http://www.python.org/dev/peps/pep-0257/>
How do I document a module in Python?
44,084
31
2008-09-04T16:06:48Z
23,450,896
14
2014-05-03T23:29:51Z
[ "python", "documentation", "python-module" ]
That's it. If you want to document a function or a class, you put a string just after the definition. For instance: ``` def foo(): """This function does nothing.""" pass ``` But what about a module? How can I document what a *file.py* does?
Add your docstring as the [first statement in the module](http://legacy.python.org/dev/peps/pep-0257/#what-is-a-docstring). Since I like seeing an example: ``` """ Your module's verbose yet thorough docstring. """ import foo # ... ```
Iterate over subclasses of a given class in a given module
44,352
15
2008-09-04T18:05:23Z
44,381
9
2008-09-04T18:20:21Z
[ "python", "oop" ]
In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?
Here's one way to do it: ``` import inspect def get_subclasses(mod, cls): """Yield the classes in module ``mod`` that inherit from ``cls``""" for name, obj in inspect.getmembers(mod): if hasattr(obj, "__bases__") and cls in obj.__bases__: yield obj ```
Iterate over subclasses of a given class in a given module
44,352
15
2008-09-04T18:05:23Z
408,465
19
2009-01-03T01:56:21Z
[ "python", "oop" ]
In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?
Although Quamrana's suggestion works fine, there are a couple of possible improvements I'd like to suggest to make it more pythonic. They rely on using the inspect module from the standard library. 1. You can avoid the getattr call by using `inspect.getmembers()` 2. The try/catch can be avoided by using `inspect.iscla...
How would you make a comma-separated string from a list?
44,778
180
2008-09-04T21:04:04Z
44,781
333
2008-09-04T21:06:12Z
[ "python", "list" ]
What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, `[ 'a', 'b', 'c' ]` to `'a,b,c'`? (The cases `[ s ]` and `[]` should be mapped to `s` and `''`, respectively.) I usually end up using something li...
``` myList = ['a','b','c','d'] myString = ",".join(myList ) ``` This won't work if the list contains numbers. --- As [Ricardo Reyes](http://stackoverflow.com/users/3399/ricardo-reyes) suggested, if it contains non-string types (such as integers, floats, bools, None) then do: ``` myList = ','.join(map(str, myList)) ...
How would you make a comma-separated string from a list?
44,778
180
2008-09-04T21:04:04Z
44,788
42
2008-09-04T21:08:29Z
[ "python", "list" ]
What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, `[ 'a', 'b', 'c' ]` to `'a,b,c'`? (The cases `[ s ]` and `[]` should be mapped to `s` and `''`, respectively.) I usually end up using something li...
Why the map/lambda magic? Doesn't this work? ``` >>>foo = [ 'a', 'b', 'c' ] >>>print ",".join(foo) a,b,c >>>print ",".join([]) >>>print ",".join(['a']) a ``` Edit: @mark-biek points out the case for numbers. Perhaps the list comprehension: ``` >>>','.join([str(x) for x in foo]) ``` is more "pythonic". Edit2: Than...
How would you make a comma-separated string from a list?
44,778
180
2008-09-04T21:04:04Z
44,791
10
2008-09-04T21:09:33Z
[ "python", "list" ]
What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, `[ 'a', 'b', 'c' ]` to `'a,b,c'`? (The cases `[ s ]` and `[]` should be mapped to `s` and `''`, respectively.) I usually end up using something li...
Don't you just want: ``` ",".join(l) ``` Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library: <https://docs.python.org/library/csv.html>
Can someone explain __all__ in Python?
44,834
409
2008-09-04T21:28:18Z
44,842
198
2008-09-04T21:30:46Z
[ "python", "syntax", "namespaces" ]
I have been using Python more and more, and I keep seeing the variable `__all__` set in different `__init__.py` files. Can someone explain what this does?
It's a list of public objects of that module. It overrides the default of hiding everything that begins with an underscore.
Can someone explain __all__ in Python?
44,834
409
2008-09-04T21:28:18Z
44,843
43
2008-09-04T21:31:16Z
[ "python", "syntax", "namespaces" ]
I have been using Python more and more, and I keep seeing the variable `__all__` set in different `__init__.py` files. Can someone explain what this does?
From [(An Unofficial) Python Reference Wiki](http://effbot.org/pyref/__all__.htm): > The public names defined by a module are determined by checking the module's namespace for a variable named `__all__`; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in...
Can someone explain __all__ in Python?
44,834
409
2008-09-04T21:28:18Z
64,130
483
2008-09-15T15:49:50Z
[ "python", "syntax", "namespaces" ]
I have been using Python more and more, and I keep seeing the variable `__all__` set in different `__init__.py` files. Can someone explain what this does?
Linked to, but not explicitly mentioned here, is exactly when `__all__` is used. It is a list of strings defining what symbols in a module will be exported when `from <module> import *` is used on the module. For example, the following code in a `foo.py` explicitly exports the symbols `bar` and `baz`: ``` __all__ = [...
Can someone explain __all__ in Python?
44,834
409
2008-09-04T21:28:18Z
2,838,800
76
2010-05-15T03:22:29Z
[ "python", "syntax", "namespaces" ]
I have been using Python more and more, and I keep seeing the variable `__all__` set in different `__init__.py` files. Can someone explain what this does?
It also changes what pydoc will show: module1.py ``` a = "A" b = "B" c = "C" ``` module2.py ``` __all__ = ['a', 'b'] a = "A" b = "B" c = "C" ``` $ pydoc module1 ``` Help on module module1: NAME module1 FILE module1.py DATA a = 'A' b = 'B' c = 'C' ``` $ pydoc module2 ``` Help on module mo...
Can someone explain __all__ in Python?
44,834
409
2008-09-04T21:28:18Z
16,595,377
84
2013-05-16T19:01:48Z
[ "python", "syntax", "namespaces" ]
I have been using Python more and more, and I keep seeing the variable `__all__` set in different `__init__.py` files. Can someone explain what this does?
I'm just adding this to be precise: All other answers refer to *modules*. The original question explicitely mentioned `__all__` in `__init__.py` files, so this is about python *packages*. Generally, `__all__` only comes into play when the `from xxx import *` variant of the `import` statement is used. This applies to ...
Can someone explain __all__ in Python?
44,834
409
2008-09-04T21:28:18Z
35,710,527
22
2016-02-29T21:58:50Z
[ "python", "syntax", "namespaces" ]
I have been using Python more and more, and I keep seeing the variable `__all__` set in different `__init__.py` files. Can someone explain what this does?
> **Explain \_\_all\_\_ in Python?** > > I keep seeing the variable `__all__` set in different `__init__.py` files. > > What does this do? # What does `__all__` do? It declares the semantically "public" names from a module. If there is a name in `__all__`, users are expected to use it, and they can have the expectati...
Python packages - import by class, not file
45,122
35
2008-09-05T02:15:33Z
45,126
71
2008-09-05T02:18:21Z
[ "python", "packages" ]
Say I have the following file structure: ``` app/ app.py controllers/ __init__.py project.py plugin.py ``` If app/controllers/project.py defines a class Project, app.py would import it like this: ``` from app.controllers.project import Project ``` I'd like to just be able to do: ``` from app.contro...
You need to put ``` from project import Project ``` in `controllers/__init__.py`. Note that when [Absolute imports](http://www.python.org/dev/peps/pep-0328/) become the default (Python 2.7?), you will want to add a dot before the module name (to avoid collisions with a top-level model named `project`), i.e., ``` fr...
Where can I find the time and space complexity of the built-in sequence types in Python
45,228
14
2008-09-05T04:27:46Z
45,538
12
2008-09-05T11:04:04Z
[ "python", "performance", "complexity-theory", "big-o", "sequences" ]
I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?
Raymond D. Hettinger does [an excellent talk](http://www.youtube.com/watch?v=hYUsssClE94) ([slides](http://wenku.baidu.com/view/9c6fb20dcc1755270722089d.html)) about Python's built-in collections called 'Core Python Containers - Under the Hood'. The version I saw focussed mainly on `set` and `dict`, but `list` was cove...
Where can I find the time and space complexity of the built-in sequence types in Python
45,228
14
2008-09-05T04:27:46Z
46,201
16
2008-09-05T16:19:03Z
[ "python", "performance", "complexity-theory", "big-o", "sequences" ]
I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?
Checkout the [TimeComplexity](http://wiki.python.org/moin/TimeComplexity) page on the py dot org wiki. It covers set/dicts/lists/etc at least as far as time complexity goes.
Analizing MIPS binaries: is there a Python library for parsing binary data?
45,954
10
2008-09-05T14:44:25Z
3,647,010
8
2010-09-05T17:29:19Z
[ "python", "x86", "mips", "elf", "dwarf" ]
I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debuggi...
You might be interested in the DWARF library from [pydevtools](http://code.google.com/p/pydevtools/): ``` >>> from bintools.dwarf import DWARF >>> dwarf = DWARF('test/test') >>> dwarf.get_loc_by_addr(0x8048475) ('/home/emilmont/Workspace/dbg/test/main.c', 36, 0) ```
Django: Print url of view without hardcoding the url
47,207
7
2008-09-06T02:42:49Z
47,304
15
2008-09-06T07:22:52Z
[ "python", "django" ]
Can i print out a url `/admin/manage/products/add` of a certain view in a template? Here is the rule i want to create a link for ``` (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), ``` I would like to have /manage/products/add in a template without hardcoding it. How can i d...
You can use `get_absolute_url`, but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case. You want to use [named URL patterns](https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns). Here's a quick intro: Change the line in your urls....
How do you set up a python wsgi server under IIS?
47,253
22
2008-09-06T04:26:49Z
47,266
20
2008-09-06T05:32:39Z
[ "python", "iis", "deployment", "windows-server", "iis-modules" ]
I work in a windows environment and would prefer to deploy code to IIS. At the same time I would like to code in python. Having read that IIS can run fastCGI application, I went to the IIS site where it describes in detail how to get PHP up and running but not much about anything else. Does anyone have experience get...
There shouldn't be any need to use FastCGI. There exists a [ISAPI extension for WSGI](https://github.com/hexdump42/isapi-wsgi).
Is there a way to attach a debugger to a multi-threaded Python process?
47,701
24
2008-09-06T18:14:05Z
56,510
8
2008-09-11T13:19:10Z
[ "python", "debugging" ]
I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)
Yeah, gdb is good for lower level debugging. You can change threads with the *thread* command. e.g ``` (gdb) thr 2 [Switching to thread 2 (process 6159 thread 0x3f1b)] (gdb) backtrace .... ``` You could also check out Python specific debuggers like [Winpdb](http://winpdb.org/about/), or [pydb](http://bashdb.sourcef...
Is there a way to attach a debugger to a multi-threaded Python process?
47,701
24
2008-09-06T18:14:05Z
553,633
12
2009-02-16T15:18:44Z
[ "python", "debugging" ]
I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)
Use [Winpdb](http://winpdb.org/). It is a **platform independent** graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb. Features: * GPL license. Winpdb is Free Softwa...
Generator Expressions vs. List Comprehension
47,789
213
2008-09-06T20:07:59Z
47,792
59
2008-09-06T20:10:59Z
[ "python", "list-comprehension", "generator" ]
When should you use generator expressions and when should you use list comprehensions in Python? ``` # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] ```
Use list comprehensions when the result needs to be iterated over multiple times, or where speed is paramount. Use generator expressions where the range is large or infinite.
Generator Expressions vs. List Comprehension
47,789
213
2008-09-06T20:07:59Z
47,793
89
2008-09-06T20:11:17Z
[ "python", "list-comprehension", "generator" ]
When should you use generator expressions and when should you use list comprehensions in Python? ``` # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] ```
Iterating over the *generator expression* or the *list comprehension* will do the same thing. However, the *list comprehension* will create the entire list in memory first while the *generator expression* will create the items on the fly, so you are able to use it for very large (and also infinite!) sequences.
Generator Expressions vs. List Comprehension
47,789
213
2008-09-06T20:07:59Z
47,826
168
2008-09-06T20:54:08Z
[ "python", "list-comprehension", "generator" ]
When should you use generator expressions and when should you use list comprehensions in Python? ``` # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] ```
John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work: ``` def gen(): return (something for something in ge...
Generator Expressions vs. List Comprehension
47,789
213
2008-09-06T20:07:59Z
189,840
34
2008-10-10T01:42:30Z
[ "python", "list-comprehension", "generator" ]
When should you use generator expressions and when should you use list comprehensions in Python? ``` # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] ```
The benefit of a generator expression is that it uses less memory since it doesn't build the whole list at once. Generator expressions are best used when the list is an intermediary, such as summing the results, or creating a dict out of the results. For example: ``` sum(x*2 for x in xrange(256)) dict( ((k, some_fun...
Generator Expressions vs. List Comprehension
47,789
213
2008-09-06T20:07:59Z
22,858,478
27
2014-04-04T09:14:57Z
[ "python", "list-comprehension", "generator" ]
When should you use generator expressions and when should you use list comprehensions in Python? ``` # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] ```
The important point is that the list comprehension creates a new list. The generator creates a an iterable object that will "filter" the source material on-the-fly as you consume the bits. Imagine you have a 2TB log file called "hugefile.txt", and you want the content and length for all the lines that start with the w...
What are the advantages of packaging your python library/application as an .egg file?
47,953
23
2008-09-06T23:35:30Z
47,956
29
2008-09-06T23:39:33Z
[ "python", "zip", "packaging", "software-distribution", "egg" ]
I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?
From the [Python Enterprise Application Kit community](http://peak.telecommunity.com/DevCenter/PythonEggs): > *"Eggs are to Pythons as Jars are to Java..."* > > Python eggs are a way of bundling > additional information with a Python > project, that allows the project's > dependencies to be checked and > satisfied at ...
Glade or no glade: What is the best way to use PyGtk?
48,123
27
2008-09-07T04:00:41Z
48,136
12
2008-09-07T04:20:06Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade. The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade. I was wondering if the more experienced ones among us (remember, I'm jus...
Use GtkBuilder instead of Glade, it's integrated into Gtk itself instead of a separate library. The main benefit of Glade is that it's much, much easier to create the interface. It's a bit more work to connect signal handlers, but I've never felt that matters much.
Glade or no glade: What is the best way to use PyGtk?
48,123
27
2008-09-07T04:00:41Z
48,734
19
2008-09-07T20:09:47Z
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade. The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade. I was wondering if the more experienced ones among us (remember, I'm jus...
I would say that it depends: if you find that using Glade you can build the apps you want or need to make than that's absolutely fine. If however you actually want to learn how GTK works or you have some non-standard UI requirements you will **have** to dig into GTK internals (which are not that complicated). Personal...
Project structure for Google App Engine
48,458
112
2008-09-07T14:08:47Z
70,271
96
2008-09-16T08:10:50Z
[ "python", "google-app-engine" ]
I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is [BowlSK](http://www.bowlsk.com). However, as it has grown, and features have been added, it has go...
First, I would suggest you have a look at "[Rapid Development with Python, Django, and Google App Engine](http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine)" GvR describes a general/standard project layout on page 10 of his [slide presentation](http://sites.google.com/site/io/r...
Project structure for Google App Engine
48,458
112
2008-09-07T14:08:47Z
153,862
14
2008-09-30T16:30:58Z
[ "python", "google-app-engine" ]
I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is [BowlSK](http://www.bowlsk.com). However, as it has grown, and features have been added, it has go...
My usual layout looks something like this: * app.yaml * index.yaml * request.py - contains the basic WSGI app * lib + `__init__.py` - common functionality, including a request handler base class * controllers - contains all the handlers. request.yaml imports these. * templates + all the django templates, used by t...
Project structure for Google App Engine
48,458
112
2008-09-07T14:08:47Z
12,535,000
10
2012-09-21T17:07:02Z
[ "python", "google-app-engine" ]
I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is [BowlSK](http://www.bowlsk.com). However, as it has grown, and features have been added, it has go...
I implemented a google app engine boilerplate today and checked it on github. This is along the lines described by Nick Johnson above (who used to work for Google). Follow this link [gae-boilerplate](https://github.com/droot/gae-boilerplate)
Calling python from a c++ program for distribution
49,137
18
2008-09-08T03:53:39Z
49,148
15
2008-09-08T04:01:10Z
[ "c++", "python", "embedded-language" ]
I would like to call python script files from my c++ program. I am not sure that the people I will distribute to will have python installed. Basically I'm looking for a .lib file that I can use that has an Apache like distribution license.
Boost has a python interface library which could help you. [Boost.Python](http://www.boost.org/doc/libs/release/libs/python/doc/index.html)
Calling python from a c++ program for distribution
49,137
18
2008-09-08T03:53:39Z
328,451
32
2008-11-30T04:52:03Z
[ "c++", "python", "embedded-language" ]
I would like to call python script files from my c++ program. I am not sure that the people I will distribute to will have python installed. Basically I'm looking for a .lib file that I can use that has an Apache like distribution license.
> I would like to call python script files from my c++ program. This means that you want to embed Python in your C++ application. As mentioned in [Embedding Python in Another Application](http://docs.python.org/extending/embedding.html): > Embedding Python is similar to > extending it, but not quite. The > difference...
How do I turn a python program into an .egg file?
49,164
13
2008-09-08T04:21:22Z
49,169
9
2008-09-08T04:33:39Z
[ "python", "deployment", "egg" ]
How do I turn a python program into an .egg file?
[Setuptools](http://peak.telecommunity.com/DevCenter/setuptools) is the software that creates [.egg files](http://peak.telecommunity.com/DevCenter/PythonEggs). It's an extension of the [`distutils`](http://docs.python.org/lib/module-distutils.html) package in the standard library. The process involves creating a `setu...
Can parallel traversals be done in MATLAB just as in Python?
49,307
7
2008-09-08T08:25:55Z
65,903
12
2008-09-15T19:20:15Z
[ "python", "arrays", "matlab", "for-loop" ]
Using the `zip` function, Python allows for loops to traverse multiple sequences in parallel. `for (x,y) in zip(List1, List2):` Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?
If x and y are column vectors, you can do: ``` for i=[x';y'] # do stuff with i(1) and i(2) end ``` (with row vectors, just use `x` and `y`). Here is an example run: ``` >> x=[1 ; 2; 3;] x = 1 2 3 >> y=[10 ; 20; 30;] y = 10 20 30 >> for i=[x';y'] disp(['size of i = ' num2str(size(i))...
Java -> Python?
49,824
23
2008-09-08T14:36:24Z
49,828
15
2008-09-08T14:40:36Z
[ "java", "python" ]
Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?
I think this pair of articles by Philip J. Eby does a great job discussing the differences between the two languages (mostly about philosophy/mentality rather than specific language features). * [Python is Not Java](http://dirtsimple.org/2004/12/python-is-not-java.html) * [Java is Not Python, either](http://dirtsimple...
Java -> Python?
49,824
23
2008-09-08T14:36:24Z
49,953
40
2008-09-08T15:35:32Z
[ "java", "python" ]
Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?
1. List comprehensions. I often find myself filtering/mapping lists, and being able to say `[line.replace("spam","eggs") for line in open("somefile.txt") if line.startswith("nee")]` is really nice. 2. Functions are first class objects. They can be passed as parameters to other functions, defined inside other function, ...
Open source alternative to MATLAB's fmincon function?
49,926
22
2008-09-08T15:19:59Z
70,798
13
2008-09-16T09:45:06Z
[ "python", "matlab", "numpy", "numerical", "scientific-computing" ]
Is there an open-source alternative to MATLAB's [`fmincon`](http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html) function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / [NumPy](http://numpy.scipy.org/) / [SciPy](...
The open source Python package,[SciPy](http://www.scipy.org/), has quite a large set of optimization routines including some for multivariable problems with constraints (which is what fmincon does I believe). Once you have SciPy installed type the following at the Python command prompt help(scipy.optimize) The result...
Open source alternative to MATLAB's fmincon function?
49,926
22
2008-09-08T15:19:59Z
196,806
22
2008-10-13T05:51:51Z
[ "python", "matlab", "numpy", "numerical", "scientific-computing" ]
Is there an open-source alternative to MATLAB's [`fmincon`](http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html) function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / [NumPy](http://numpy.scipy.org/) / [SciPy](...
Is your problem convex? Linear? Non-linear? I agree that SciPy.optimize will probably do the job, but fmincon is a sort of bazooka for solving optimization problems, and you'll be better off if you can confine it to one of the categories below (in increasing level of difficulty to solve efficiently) Linear Program (LP...
Open source alternative to MATLAB's fmincon function?
49,926
22
2008-09-08T15:19:59Z
1,856,211
12
2009-12-06T18:51:50Z
[ "python", "matlab", "numpy", "numerical", "scientific-computing" ]
Is there an open-source alternative to MATLAB's [`fmincon`](http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html) function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / [NumPy](http://numpy.scipy.org/) / [SciPy](...
Python optimization software: * **OpenOpt** <http://openopt.org> **(this one is numpy-based as you wish, with automatic differentiation by FuncDesigner)** * **Pyomo** <https://software.sandia.gov/trac/coopr/wiki/Package/pyomo> * **CVXOPT** <http://abel.ee.ucla.edu/cvxopt/> * **NLPy** <http://nlpy.sourceforge.net/>
What Python way would you suggest to check whois database records?
50,394
7
2008-09-08T18:43:52Z
4,078,336
8
2010-11-02T13:53:05Z
[ "python", "sysadmin", "whois" ]
I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly. I did some search to try to find a pythonic way to do this task. Generally I got quite much nothin...
Look at this: <http://code.google.com/p/pywhois/> pywhois - Python module for retrieving WHOIS information of domains Goal: - Create a simple importable Python module which will produce parsed WHOIS data for a given domain. - Able to extract data for all the popular TLDs (com, org, net, ...) - Query a WHOIS server di...
How do I get the path and name of the file that is currently executing?
50,499
262
2008-09-08T19:41:10Z
50,502
11
2008-09-08T19:42:56Z
[ "python", "scripting", "file" ]
I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. For example, let's say I have three files. Using [execfile](http://docs.python.org/library/functions.html#execfile): * `script_1.py` calls `script_2.py`. * In turn, `script_2.py` calls `s...
It's not entirely clear what you mean by "the filepath of the file that is currently running within the process". `sys.argv[0]` usually contains the location of the script that was invoked by the Python interpreter. Check the [sys documentation](https://docs.python.org/2/library/sys.html) for more details. As @Tim and...