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
In managed code, how do I achieve good locality of reference?
1,518,915
9
2009-10-05T08:58:36Z
1,518,958
8
2009-10-05T09:06:35Z
[ "c#", "java", "python", "optimization", "memory-management" ]
Since RAM seems to be [the new disk](http://www.infoq.com/news/2008/06/ram-is-disk), and since that statement also means that access to memory is now considered slow similarly to how disk access has always been, I do want to maximize locality of reference in memory for high performance applications. For example, in a s...
* In .NET, elements of an array are certainly contiguous. In Java I'd expect them to be in most implementations, but it appears not to be guaranteed. * I think it's reasonable to *assume* that the memory used by an instance for fields is in a single block... but don't forget that some of those fields may be references ...
String manipulation in Python docstrings
1,519,029
8
2009-10-05T09:27:01Z
1,519,088
9
2009-10-05T09:41:11Z
[ "python", "string", "documentation" ]
I've been trying to do the following: ``` #[...] def __history_dependent_simulate(self, node, iterations=1, *args, **kwargs): """ For history-dependent simulations only: """ + self.simulate.__doc___ ``` What I tried to accomplish here is to have the sam...
A better solution is probably to use a decorator, eg: ``` def add_docs_for(other_func): def dec(func): func.__doc__ = other_func.__doc__ + "\n\n" + func.__doc__ return func return dec def foo(): """documentation for foo""" pass @add_docs_for(foo) def bar(): """additional notes...
Verifying peer in SSL using python
1,519,074
8
2009-10-05T09:37:53Z
1,522,323
10
2009-10-05T20:51:15Z
[ "python", "ssl" ]
I was trying to find out how I can go about verifying a self-signed certificate by a server in python. I could not find much data in google. I also want to make sure that the server url Thanks in advance for any insights.
From the comments to my first reply I see that there is a general misunderstanding what does 'verify a certificate mean'. I will try to write a brief explanation here to eliminate some of the illusions. Certificate verification is about checking a signature on the certificate metadata (i.e. subject, validity period, e...
Is it normal that running python under valgrind shows many errors with memory?
1,519,276
13
2009-10-05T10:25:48Z
1,519,598
22
2009-10-05T11:45:32Z
[ "python", "debugging", "memory-leaks", "valgrind", "python-c-extension" ]
I've tried to debug memory crash in my Python C extension and tried to run script under valgrind. I found there is too much "noise" in the valgrind output, even if I've ran simple command as: ``` valgrind python -c "" ``` Valgrind output full of repeated info like this: ``` ==12317== Invalid read of size 4 ==12317==...
You could try using the [suppression file](http://svn.python.org/projects/python/trunk/Misc/valgrind-python.supp) that comes with the python source Reading the [Python Valgrind README](http://svn.python.org/projects/python/trunk/Misc/README.valgrind) is a good idea too!
How do you host your own egg repository?
1,519,589
16
2009-10-05T11:43:20Z
1,519,692
8
2009-10-05T12:07:02Z
[ "python" ]
Say you're on a team that's maintaining a lot of internal python libraries(eggs), and for whatever reason uploading them to pypi is not an option. How could you host the libraries(eggs) so that easy\_install can still work for the members of your team? Basically it would be cool if this worked.... ``` (someproj)uberd...
Deploy all your eggs to a directory all devs. can reach (for instance on a webserver). To install eggs from that directory, type: ``` $ easy_install -H None -f http://server/vdir TheEggToInstall ``` or. ``` $ easy_install -H None -f /path/to/directory TheEggToInstall ``` `-H None` means do not allow egg download f...
How to check which version of Numpy I'm using?
1,520,234
118
2009-10-05T13:56:50Z
1,520,264
122
2009-10-05T14:01:19Z
[ "python", "numpy" ]
How can I check which version of Numpy I'm using? I'm using Mac OS X 10.6.1 Snow Leopard.
``` >> import numpy >> print numpy.__version__ ```
How to check which version of Numpy I'm using?
1,520,234
118
2009-10-05T13:56:50Z
1,520,275
174
2009-10-05T14:02:58Z
[ "python", "numpy" ]
How can I check which version of Numpy I'm using? I'm using Mac OS X 10.6.1 Snow Leopard.
``` import numpy numpy.version.version ```
How to check which version of Numpy I'm using?
1,520,234
118
2009-10-05T13:56:50Z
1,958,122
25
2009-12-24T12:10:38Z
[ "python", "numpy" ]
How can I check which version of Numpy I'm using? I'm using Mac OS X 10.6.1 Snow Leopard.
from the command line, you can simply issue: ``` python -c "import numpy; print(numpy.version.version)" ``` or ``` python -c "import numpy; print(numpy.__version__)" ```
How to check which version of Numpy I'm using?
1,520,234
118
2009-10-05T13:56:50Z
16,904,549
12
2013-06-03T19:40:00Z
[ "python", "numpy" ]
How can I check which version of Numpy I'm using? I'm using Mac OS X 10.6.1 Snow Leopard.
You can also check if your version is using MKL with: ``` import numpy numpy.show_config() ```
How to update Numpy on Mac OS X Snow Leopard?
1,520,379
11
2009-10-05T14:17:39Z
1,520,680
25
2009-10-05T15:08:08Z
[ "python", "osx", "osx-snow-leopard", "numpy" ]
How can I update Numpy into the newest one? Should I download .dmg file from here: <http://sourceforge.net/projects/numpy/files/> Is this .dmg only for 10.5? I have installed numpy using these instructions: <http://www.scipy.org/Installing_SciPy/Mac_OS_X> My current Numpy is 1.2.1. I'm running on Mac OS X 10.6.1 Sn...
`sudo easy_install -U numpy` Installing via setuptools will get the new numpy on the sys.path for non-system utilties (I've been told that some Apple utilities rely on the system-numpy). In general, setuptools will "do the right" thing on OS X.
How does Python's triple-quote string work?
1,520,548
17
2009-10-05T14:49:04Z
1,520,704
13
2009-10-05T15:12:28Z
[ "python", "string" ]
How should this function be changed to return `"123456"`? ``` def f(): s = """123 456""" return s ``` UPDATE: Everyone, the question is about understanding how to not have \t or whatever when having a multiline comment, not how to use the `re` module.
``` def f(): s = """123\ 456""" return s ``` Don't indent any of the blockquote lines after the first line; end every line except the last with a backslash.
How does Python's triple-quote string work?
1,520,548
17
2009-10-05T14:49:04Z
1,521,159
12
2009-10-05T16:47:14Z
[ "python", "string" ]
How should this function be changed to return `"123456"`? ``` def f(): s = """123 456""" return s ``` UPDATE: Everyone, the question is about understanding how to not have \t or whatever when having a multiline comment, not how to use the `re` module.
Subsequent strings are concatenated, so you can use: ``` def f(): s = ("123" "456") return s ``` This will allow you to keep indention as you like.
How does Python's triple-quote string work?
1,520,548
17
2009-10-05T14:49:04Z
1,521,440
40
2009-10-05T17:46:54Z
[ "python", "string" ]
How should this function be changed to return `"123456"`? ``` def f(): s = """123 456""" return s ``` UPDATE: Everyone, the question is about understanding how to not have \t or whatever when having a multiline comment, not how to use the `re` module.
Don't use a triple-quoted string when you don't want extra whitespace, tabs and newlines. Use implicit continuation, it's more elegant: ``` def f(): s = ('123' '456') return s ```
What is a good size (in bytes) for a log file?
1,521,082
13
2009-10-05T16:32:49Z
1,521,111
7
2009-10-05T16:37:05Z
[ "python", "logging" ]
I am using the python [logging](http://docs.python.org/library/logging.html#simple-examples) modules [RotatingFileHandler](http://docs.python.org/library/logging.html#rotatingfilehandler), and you can set the maximum size of each log file. What is a good maximum size for a log file? Please give your answer in bytes.
Size isn't as important to me as **dividing at sensible chronological points**. I prefer one log file per day, however, if the file won't open with any notepad program you have at your disposal, it is too big and you might want to go with hourly logs.
What is a good size (in bytes) for a log file?
1,521,082
13
2009-10-05T16:32:49Z
1,521,531
8
2009-10-05T18:05:59Z
[ "python", "logging" ]
I am using the python [logging](http://docs.python.org/library/logging.html#simple-examples) modules [RotatingFileHandler](http://docs.python.org/library/logging.html#rotatingfilehandler), and you can set the maximum size of each log file. What is a good maximum size for a log file? Please give your answer in bytes.
My default logging setup: ``` RotatingFileHandler(filename, maxBytes=10*1024*1024, backupCount=5) ```
Get Root Domain of Link
1,521,592
10
2009-10-05T18:16:12Z
1,521,695
20
2009-10-05T18:35:45Z
[ "python", "regex", "dns", "root" ]
I have a link such as <http://www.techcrunch.com/> and I would like to get just the techcrunch.com part of the link. How do I go about this in python?
Getting the hostname is easy enough using [urlparse](http://docs.python.org/library/urlparse.html): ``` hostname = urlparse.urlparse("http://www.techcrunch.com/").hostname ``` Getting the "root domain", however, is going to be more problematic, because it isn't defined in a syntactic sense. What's the root domain of ...
How to prevent log file truncation with python logging module?
1,521,681
5
2009-10-05T18:32:29Z
1,521,739
11
2009-10-05T18:45:23Z
[ "python", "logging" ]
I need to use python logging module to print debugging info to a file with statements like: ``` logging.debug(something) ``` The file is truncated (i am assuming - by the logging module) and the messages get deleted before I can see them - how can that be prevented? Here is my logging config: ``` logging.basicConfi...
[`logging`](http://docs.python.org/library/logging.html#simple-examples) > If you run the script repeatedly, the additional log messages are appended to the file. **To create a new file each time, you can pass a filemode argument to basicConfig() with a value of 'w'**. Rather than managing the file size yourself, thou...
Cost of list functions in Python
1,521,784
8
2009-10-05T18:58:42Z
1,521,843
15
2009-10-05T19:11:08Z
[ "python", "performance", "list" ]
Based on [this older thread](http://bytes.com/topic/python/answers/101848-list-implementation), it looks like the cost of list functions in Python is: * Random access: O(1) * Insertion/deletion to front: O(n) * Insertion/deletion to back: O(1) Can anyone confirm whether this is still true in Python 2.6/3.x?
Take a look [here](http://www.python.org/dev/peps/pep-3128/#motivation). It's a PEP for a different kind of list. The version specified is 2.6/3.0. Append (insertion to back) is `O(1)`, while insertion (everywhere else) is `O(n)`. So **yes**, it looks like this is still true. ``` Operation...Complexity Copy........O(...
How to specify date and time in python?
1,521,906
2
2009-10-05T19:22:49Z
1,522,043
18
2009-10-05T19:51:58Z
[ "python", "datetime" ]
Quite simple newbie question: What is the object used in python to specify date (and time) in Python? For instance, to create an object that holds a given date and time, (let's say `'05/10/09 18:00'`). **EDIT** As per S.Lott request, what I have so far is: ``` class Some: date = ``` I stop there, after the "=...
Simple example: ``` >>> import datetime # 05/10/09 18:00 >>> d = datetime.datetime(2009, 10, 5, 18, 00) >>> print d.year, d.month, d.day, d.hour, d.second 2009 10 5 18 0 >>> print d.isoformat(' ') 2009-10-05 18:00:00 >>> ```
How do I run a Python program?
1,522,564
36
2009-10-05T21:42:30Z
1,522,567
12
2009-10-05T21:43:01Z
[ "python", "ide", "debugging" ]
So I'm starting like Python a bit, but I'm having trouble erm...running it. Lol I'm using IDLE for now, but its no use whatsoever because you can only run a couple of lines at a time. I'm also using Komodo Edit to create the actual .py files. My question is, how can I run the .py files to test out the actual program...
You can just call ``` python /path/to/filename.py ```
How do I run a Python program?
1,522,564
36
2009-10-05T21:42:30Z
1,522,599
11
2009-10-05T21:52:24Z
[ "python", "ide", "debugging" ]
So I'm starting like Python a bit, but I'm having trouble erm...running it. Lol I'm using IDLE for now, but its no use whatsoever because you can only run a couple of lines at a time. I'm also using Komodo Edit to create the actual .py files. My question is, how can I run the .py files to test out the actual program...
In IDLE press F5 You can open your .py file with IDLE and press F5 to run it. You can open that same file with other editor ( like Komodo as you said ) save it and press F5 again; F5 works with IDLE ( even when the editing is done with another tool ). If you want to run it directly from Komodo according to this arti...
How do I run a Python program?
1,522,564
36
2009-10-05T21:42:30Z
1,527,012
45
2009-10-06T17:37:26Z
[ "python", "ide", "debugging" ]
So I'm starting like Python a bit, but I'm having trouble erm...running it. Lol I'm using IDLE for now, but its no use whatsoever because you can only run a couple of lines at a time. I'm also using Komodo Edit to create the actual .py files. My question is, how can I run the .py files to test out the actual program...
I'm very glad you asked! I was just working on explaining this very thing [in our wikibook](http://en.wikibooks.org/wiki/Choose%5FYour%5FOwn%5FPyventure) (which is obviously incomplete). We're working with Python novices, and had to help a few through exactly what you're asking! **Command-line Python in Windows:** 1....
should I call close() after urllib.urlopen()?
1,522,636
48
2009-10-05T21:59:04Z
1,522,709
80
2009-10-05T22:22:17Z
[ "python", "urllib" ]
I'm new to Python and reading someone else's code: should `urllib.urlopen()` be followed by `urllib.close()`? Otherwise, one would leak connections, correct?
The `close` method must be called on the *result* of `urllib.urlopen`, **not** on the `urllib` module itself as you're thinking about (as you mention `urllib.close` -- which doesn't exist). The best approach: instead of `x = urllib.urlopen(u)` etc, use: ``` import contextlib with contextlib.closing(urllib.urlopen(u)...
should I call close() after urllib.urlopen()?
1,522,636
48
2009-10-05T21:59:04Z
1,522,713
11
2009-10-05T22:24:08Z
[ "python", "urllib" ]
I'm new to Python and reading someone else's code: should `urllib.urlopen()` be followed by `urllib.close()`? Otherwise, one would leak connections, correct?
Like @Peter says, out-of-scope opened URLs will become eligible for garbage collection. However, also note that `urllib.py` defines: ``` def __del__(self): self.close() ``` This means that **when the reference count for that instance reaches zero**, its [`__del__`](http://docs.python.org/reference/datamodel...
How do I get the module instance for a class in Python?
1,522,651
8
2009-10-05T22:03:21Z
1,522,687
11
2009-10-05T22:13:24Z
[ "python" ]
I am learning Python, and as always, I'm being ambitious with my starter projects. I am working on a plugin system for a community site toolkit for App Engine. My plugin superclass has a method called `install_path`. I would like to obtain the `__path__` for the `__module__` for `self` (which in this case will be the s...
The [`sys.modules`](http://docs.python.org/library/sys.html#sys.modules) dict contains all imported modules, so you can use: ``` mod = sys.modules[__module__] ```
Python: List comprehension to assign different values
1,522,960
7
2009-10-05T23:45:02Z
1,522,973
14
2009-10-05T23:49:46Z
[ "python", "list-comprehension" ]
I'm making a 2D list and I would like to initialize it with a list comprehension. I would like it to do something like this: ``` [[x for i in range(3) if j <= 1: x=1 else x=2] for j in range(3)] ``` so it should return something like: ``` [[1,1,1], [1,1,1], [2,2,2]] ``` How might I go about doing this? Thanks fo...
It appears as though you're looking for something like this: ``` [[1 if j <= 1 else 2 for i in range(3)] for j in range(3)] ``` The Python [conditional expression](http://docs.python.org/reference/expressions.html#boolean-operations) is a bit different from what you might be used to if you're coming from something li...
Python: List comprehension to assign different values
1,522,960
7
2009-10-05T23:45:02Z
1,522,986
14
2009-10-05T23:55:08Z
[ "python", "list-comprehension" ]
I'm making a 2D list and I would like to initialize it with a list comprehension. I would like it to do something like this: ``` [[x for i in range(3) if j <= 1: x=1 else x=2] for j in range(3)] ``` so it should return something like: ``` [[1,1,1], [1,1,1], [2,2,2]] ``` How might I go about doing this? Thanks fo...
Greg's response is correct, though a much simpler and faster expression to produce your desired result would be ``` [[j] * 3 for j in (1, 1, 2)] ``` i.e., remember that `for` need not apply to a `range` only;-), list-multiplication exists, and so on;-).
How do I do this in Python? List to function
1,523,348
2
2009-10-06T02:43:50Z
1,523,364
12
2009-10-06T02:50:44Z
[ "python" ]
``` def getStuff(x): return 'stuff'+x def getData(x): return 'data'+x thefunctions = [] thefunctions.append("getStuff") thefunctions.append("getData") for i in thefunctions: print i('abc') ``` Is this possible? Thank you.
``` thefunctions = [ getStuff, getData ] for f in thefunctions: print f('shazam') ``` Once you've done a `def` statement, you've associated a name with a function. Just use that name to refer to the function.
Elegant way to skip first line when using python fileinput module?
1,523,378
11
2009-10-06T02:57:43Z
1,523,396
15
2009-10-06T03:05:47Z
[ "python", "file-io" ]
Is there an elegant way of skipping first line of file when using `python` fileinput module? I have data file with nicely formated data but the first line is header. Using `fileinput` I would have to include check and discard line if the line does not seem to contain data. The problem is that it would apply the same ...
The `fileinput` module contains a bunch of handy functions, one of which seems to do exactly what you're looking for: ``` for line in fileinput.input(["file.dat"]): if not fileinput.isfirstline(): data = proces_line(line); output(data) ``` [fileinput module documentation](http://docs.python.org/library/file...
Elegant way to skip first line when using python fileinput module?
1,523,378
11
2009-10-06T02:57:43Z
1,523,466
14
2009-10-06T03:39:03Z
[ "python", "file-io" ]
Is there an elegant way of skipping first line of file when using `python` fileinput module? I have data file with nicely formated data but the first line is header. Using `fileinput` I would have to include check and discard line if the line does not seem to contain data. The problem is that it would apply the same ...
``` lines = iter(fileinput.input(["file.dat"])) next(lines) # extract and discard first line for line in lines: data = proces_line(line) output(data) ``` or use the itertools.islice way if you prefer ``` import itertools finput = fileinput.input(["file.dat"]) lines = itertools.islice(finput, 1, None) # cuts o...
What is the common header format of Python files?
1,523,427
270
2009-10-06T03:23:14Z
1,523,435
15
2009-10-06T03:25:12Z
[ "python", "header", "comments" ]
I came across the following header format for Python source files in a document about Python coding guidelines: ``` #!/usr/bin/env python """Foobar.py: Description of what foobar does.""" __author__ = "Barack Obama" __copyright__ = "Copyright 2009, Planet Earth" ``` Is this the standard format of headers in ...
Here's a good place to start: [PEP 257](http://www.python.org/dev/peps/pep-0257/), which talks about Docstrings, and links to several other relevant documents.
What is the common header format of Python files?
1,523,427
270
2009-10-06T03:23:14Z
1,523,456
323
2009-10-06T03:34:00Z
[ "python", "header", "comments" ]
I came across the following header format for Python source files in a document about Python coding guidelines: ``` #!/usr/bin/env python """Foobar.py: Description of what foobar does.""" __author__ = "Barack Obama" __copyright__ = "Copyright 2009, Planet Earth" ``` Is this the standard format of headers in ...
Its all metadata for the `Foobar` module. The first one is the `docstring` of the module, that is already explained in [Peter's answer](http://stackoverflow.com/questions/1523427/python-what-is-the-common-header-format/1523435#1523435). > ## [How do I organize my modules (source files)? (Archive)](http://web.archive....
What is the common header format of Python files?
1,523,427
270
2009-10-06T03:23:14Z
1,523,621
12
2009-10-06T04:39:28Z
[ "python", "header", "comments" ]
I came across the following header format for Python source files in a document about Python coding guidelines: ``` #!/usr/bin/env python """Foobar.py: Description of what foobar does.""" __author__ = "Barack Obama" __copyright__ = "Copyright 2009, Planet Earth" ``` Is this the standard format of headers in ...
Also see [PEP 263](http://www.python.org/dev/peps/pep-0263/) if you are using a non-ascii characterset > ## Abstract > > This PEP proposes to introduce a syntax to declare the encoding of > a Python source file. The encoding information is then used by the > Python parser to interpret the file using the given encoding...
What is the common header format of Python files?
1,523,427
270
2009-10-06T03:23:14Z
9,225,336
85
2012-02-10T09:13:33Z
[ "python", "header", "comments" ]
I came across the following header format for Python source files in a document about Python coding guidelines: ``` #!/usr/bin/env python """Foobar.py: Description of what foobar does.""" __author__ = "Barack Obama" __copyright__ = "Copyright 2009, Planet Earth" ``` Is this the standard format of headers in ...
I strongly favour minimal file headers, by which I mean just: * The hashbang (`#!` line) if this is an executable script * Module docstring * Imports, grouped as described in **voyager**’s answer. Everything else is a waste of time, visual space, and is actively misleading. If you have legal disclaimers or licenci...
Binary numbers in Python
1,523,465
34
2009-10-06T03:37:55Z
1,523,478
9
2009-10-06T03:44:47Z
[ "python", "binary" ]
How can I add, subtract, and compare binary numbers in Python without converting to decimal?
I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you'r...
Binary numbers in Python
1,523,465
34
2009-10-06T03:37:55Z
1,523,581
65
2009-10-06T04:19:28Z
[ "python", "binary" ]
How can I add, subtract, and compare binary numbers in Python without converting to decimal?
You can convert between a string representation of the binary using bin() and int() ``` >>> bin(88) '0b1011000' >>> int('0b1011000', 2) 88 >>> >>> a=int('01100000', 2) >>> b=int('00100110', 2) >>> bin(a & b) '0b100000' >>> bin(a | b) '0b1100110' >>> bin(a ^ b) '0b1000110' ```
.vimrc configuration for Python
1,523,482
18
2009-10-06T03:45:54Z
1,523,512
12
2009-10-06T03:54:16Z
[ "python", "vim" ]
My current .vimrc configuration is below: ``` set nohlsearch set ai set bg=dark set showmatch highlight SpecialKey ctermfg=DarkGray set listchars=tab:>-,trail:~ set list autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class set tabstop=4 set shiftwidth=4 set expandtab set au...
The short answer is that your autocmd is missing the BufEnter trigger, so it isn't being fired when you create a new file. Try this instead: ``` au BufEnter,BufRead *.py setlocal smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class ``` Note that I also changed the `set` to `setlocal`. This'll pre...
.vimrc configuration for Python
1,523,482
18
2009-10-06T03:45:54Z
1,523,519
13
2009-10-06T03:56:30Z
[ "python", "vim" ]
My current .vimrc configuration is below: ``` set nohlsearch set ai set bg=dark set showmatch highlight SpecialKey ctermfg=DarkGray set listchars=tab:>-,trail:~ set list autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class set tabstop=4 set shiftwidth=4 set expandtab set au...
Try this: ``` filetype indent on filetype on filetype plugin on ``` I primarily do Python programming and this is the brunt of my vimrc ``` set nobackup set nowritebackup set noswapfile set lines=40 set columns=80 set tabstop=4 set shiftwidth=4 set softtabstop=4 set autoindent set smarttab filetype indent on filetyp...
How to print a list in Python "nicely"
1,523,660
20
2009-10-06T04:55:40Z
1,523,664
47
2009-10-06T04:57:49Z
[ "python" ]
In PHP, I can do this: ``` echo '<pre>' print_r($array); echo '</pre>' ``` In Python, I currently just do this: ``` print the_list ``` However, this will cause a big jumbo of data. Is there any way to print it nicely into a readable tree? (with indents)?
``` from pprint import pprint pprint(the_list) ```
How to print a list in Python "nicely"
1,523,660
20
2009-10-06T04:55:40Z
1,523,674
16
2009-10-06T05:02:42Z
[ "python" ]
In PHP, I can do this: ``` echo '<pre>' print_r($array); echo '</pre>' ``` In Python, I currently just do this: ``` print the_list ``` However, this will cause a big jumbo of data. Is there any way to print it nicely into a readable tree? (with indents)?
You mean something like...: ``` >>> print L ['this', 'is', 'a', ['and', 'a', 'sublist', 'too'], 'list', 'including', 'many', 'words', 'in', 'it'] >>> import pprint >>> pprint.pprint(L) ['this', 'is', 'a', ['and', 'a', 'sublist', 'too'], 'list', 'including', 'many', 'words', 'in', 'it'] >>> ``` ...? From your...
How to print a list more nicely?
1,524,126
6
2009-10-06T07:43:58Z
1,524,132
8
2009-10-06T07:45:33Z
[ "python", "printing" ]
This is similar to [How to print a list in Python “nicely”](http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely), but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns. ``` foolist = ['exiv2-devel', 'mingw-libs...
Simple: ``` l = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf', 'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel', 'qgis1.1', 'php_mapscript'] if len(l) % 2 != 0: l.append(" ") split = len(l)/2 l1 = l[0:split] l2 = l[split:] for key, value in zip(l1,l2): print '%-20...
How to print a list more nicely?
1,524,126
6
2009-10-06T07:43:58Z
25,048,690
7
2014-07-30T23:35:50Z
[ "python", "printing" ]
This is similar to [How to print a list in Python “nicely”](http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely), but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns. ``` foolist = ['exiv2-devel', 'mingw-libs...
This answer uses the same method in the answer by @Aaron Digulla, with slightly more pythonic syntax. It might make some of the above answers easier to understand. ``` >>> for a,b,c in zip(foolist[::3],foolist[1::3],foolist[2::3]): >>> print '{:<30}{:<30}{:<}'.format(a,b,c) exiv2-devel mingw-lib...
Does anyone know a way to scramble the elements in a list?
1,524,160
5
2009-10-06T07:55:21Z
1,524,181
9
2009-10-06T08:00:04Z
[ "python", "random" ]
``` thelist = ['a','b','c','d'] ``` How I can to scramble them in Python?
``` import random random.shuffle(thelist) ``` Note, this shuffles the list in-place.
Does anyone know a way to scramble the elements in a list?
1,524,160
5
2009-10-06T07:55:21Z
1,524,182
12
2009-10-06T08:00:06Z
[ "python", "random" ]
``` thelist = ['a','b','c','d'] ``` How I can to scramble them in Python?
``` >>> import random >>> thelist = ['a', 'b', 'c', 'd'] >>> random.shuffle(thelist) >>> thelist ['d', 'a', 'c', 'b'] ``` Your result will (hopefully!) vary.
How to have an error but continue the script in python?
1,524,216
2
2009-10-06T08:07:41Z
1,524,232
12
2009-10-06T08:11:19Z
[ "python" ]
Suppose I have this code in Python: ``` l = dict['link'] t = dict['title'] <<<<<<<<error here, there is no "title" d = dict['description'] k = dict['keyword'] ``` What if there is an error on line 2, but I want it to continue running the script and assign the other values? Can I just "ignore" the errors? EDIT...
The easiest option is to use [`.get()`](http://docs.python.org/library/stdtypes.html#dict.get): ``` l = dict.get('link') t = dict.get('title') d = dict.get('description') k = dict.get('keyword') ``` The `t` variable will then contain `None` (you can use `dict.get('title', '')` if you want an empty string, for example...
How to have an error but continue the script in python?
1,524,216
2
2009-10-06T08:07:41Z
1,524,233
8
2009-10-06T08:11:26Z
[ "python" ]
Suppose I have this code in Python: ``` l = dict['link'] t = dict['title'] <<<<<<<<error here, there is no "title" d = dict['description'] k = dict['keyword'] ``` What if there is an error on line 2, but I want it to continue running the script and assign the other values? Can I just "ignore" the errors? EDIT...
``` t = dic.get('title') ``` won't produce the error. it's equivalent to: ``` try: t = dic['title'] except KeyError: t = None ``` and please don't shadow built-in, don't use `dict` for a variable name. use something else.
Why do I get encoding error in python warnings.formatwarning on format string?
1,524,262
5
2009-10-06T08:21:07Z
1,524,374
8
2009-10-06T08:49:54Z
[ "python", "encoding", "warnings" ]
I get encoding error on this line: ``` s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) ``` UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 44: ordinal not in range(128) I tried to reproduce this error by passing all combinations of parameters to string format, but...
This happens when Python tries to coerce an argument: ``` s = u"\u00fc" print str(s) UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 0: ordinal not in range(128) ``` This happens because one of your arguments is an object (not a string of any kind) and Python calls `str()` on it. There ar...
Why do I get encoding error in python warnings.formatwarning on format string?
1,524,262
5
2009-10-06T08:21:07Z
1,524,465
8
2009-10-06T09:12:28Z
[ "python", "encoding", "warnings" ]
I get encoding error on this line: ``` s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) ``` UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 44: ordinal not in range(128) I tried to reproduce this error by passing all combinations of parameters to string format, but...
You are mixing unicode and str objects. Explanation: In Python 2.x, there are two kinds of objects that can contain text strings. str, and unicode. str is a string of bytes, so it can only contain characters between 0 and 255. Unicode is a string of unicode characters. You can convert between str and unicode with the...
Python: smarter way to calculate loan payments
1,525,611
6
2009-10-06T13:30:59Z
1,525,889
7
2009-10-06T14:22:32Z
[ "python", "algorithm", "math", "finance" ]
How to calculate the monthly fee on a loan? Given is: * a: an amount to loan. * b: the loan period (number of months). * c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every month). * d: the amount of money ow...
This is a basically a [mortgage repayment calculation](http://en.wikipedia.org/wiki/Mortgage%5Fcalculator). Assuming that start is greater than end, and that interest is between 0 and 1 (i.e. 0.1 for 10% interest) First consider the part of the payment you want to pay off. ``` Principal = start - end ``` The monthl...
Python, subprocess, devenv, why no output?
1,525,696
6
2009-10-06T13:46:06Z
1,646,191
24
2009-10-29T19:59:25Z
[ "python", "subprocess" ]
I build a Visual Studio solution from a Python script. Everything works nicely, except that I am unable to capture the build output. ``` p = subprocess.Popen(['devenv', 'solution.sln', '/build'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() ret = p.returncode ``` Here, both `out` and `...
Change it from 'devenv' to 'devenv.com'. Apparenty Popen looks for .EXEs first but the shell looks for .COMs first. Switching to 'devenv.com' worked for me. devenv is significantly faster then msbuild for incremental builds. I just did a build with an up to date project, meaning nothing should happen. devenv 23 secon...
How do I memoize expensive calculations on Django model objects?
1,526,191
9
2009-10-06T15:06:48Z
1,526,245
16
2009-10-06T15:14:27Z
[ "python", "django", "django-models", "memoization" ]
I have several TextField columns on my UserProfile object which contain JSON objects. I've also defined a setter/getter property for each column which encapsulates the logic for serializing and deserializing the JSON into python datastructures. The nature of this data ensures that it will be accessed many times by vie...
Generally, I use a pattern like this: ``` def get_expensive_operation(self): if not hasattr(self, '_expensive_operation'): self._expensive_operation = self.expensive_operation() return self._expensive_operation ``` Then you use the `get_expensive_operation` method to access the data. However, in your...
How do I memoize expensive calculations on Django model objects?
1,526,191
9
2009-10-06T15:06:48Z
2,634,701
22
2010-04-14T03:28:16Z
[ "python", "django", "django-models", "memoization" ]
I have several TextField columns on my UserProfile object which contain JSON objects. I've also defined a setter/getter property for each column which encapsulates the logic for serializing and deserializing the JSON into python datastructures. The nature of this data ensures that it will be accessed many times by vie...
You may be interested in a built-in django decorator `django.utils.functional.memoize`. Django uses this to cache expensive operation like url resolving.
How do I convert Perl's pack 'Nc*' format to struct.pack for Python?
1,527,534
5
2009-10-06T19:18:42Z
1,527,660
7
2009-10-06T19:39:30Z
[ "python", "perl", "struct", "pack" ]
I'm trying to convert a Perl script to python, and it uses quite a few different packs. I've been able to figure out the lettering differences in the "templates" for each one, but I'm having an issue with understanding how to handle Perl's lack of length declaration. example: ``` pack('Nc*',$some_integer,$long_array_...
How about this? ``` struct.pack('>I', some_integer) + struct.pack('b'*len(long_array), *long_array) ```
How to use JQuery and Django (ajax + HttpResponse)?
1,527,641
4
2009-10-06T19:37:05Z
1,527,666
15
2009-10-06T19:41:04Z
[ "jquery", "python", "django" ]
Suppose I have an AJAX function: ``` function callpage{ $.ajax({ method:"get", url:"/abc/", data:"x="+3 beforeSend:function() {}, success:function(html){ IF HTTPRESPONSE = "1" , ALERT SUCCESS! } }); return false; } } ``` When my "View" executes in Django, I want to return `HttpR...
The typical workflow is to have the server return a JSON object as text, and then [interpret that object in the javascript](http://stackoverflow.com/questions/945015/alternatives-to-javascript-eval-for-parsing-json). In your case you could return the text {"httpresponse":1} from the server, or use the python json libar...
exit from ipython
1,527,689
10
2009-10-06T19:45:21Z
1,528,023
10
2009-10-06T20:48:33Z
[ "python", "interpreter", "ipython" ]
I like IPython a lot for working with the python interpreter. However, I continually find myself typing `exit` to exit, and get prompted "Type exit() to exit." I know I can type Ctrl-D to exit, but is there a way I can type `exit` without parentheses and get IPython to exit? **Update**: Thanks to [nosklo](http://stac...
``` >>> import sys >>> class Quitter(object): ... def __repr__(self): ... sys.exit() ... >>> exit = Quitter() ``` You can use it like this: ``` >>> exit ``` **EDIT:** I dont use `ipython` myself, but it seems to have some wierd `sys.exit` handler. The solution I found is as follows: ``` In [1]: type(e...
How can I handle exceptions in a list comprehension in Python?
1,528,237
35
2009-10-06T21:36:06Z
1,528,244
17
2009-10-06T21:38:18Z
[ "python", "exception-handling", "list-comprehension" ]
I have some a list comprehension in Python in which each iteration can throw an exception. **For instance**, if I have: ``` eggs = (1,3,0,3,2) [1/egg for egg in eggs] ``` I'll get a `ZeroDivisionError` exception in the 3rd element. How can I handle this exception and continue execution of the list comprehension? ...
You can use ``` [1/egg for egg in eggs if egg != 0] ``` this will simply skip elements that are zero.
How can I handle exceptions in a list comprehension in Python?
1,528,237
35
2009-10-06T21:36:06Z
1,528,375
38
2009-10-06T22:10:27Z
[ "python", "exception-handling", "list-comprehension" ]
I have some a list comprehension in Python in which each iteration can throw an exception. **For instance**, if I have: ``` eggs = (1,3,0,3,2) [1/egg for egg in eggs] ``` I'll get a `ZeroDivisionError` exception in the 3rd element. How can I handle this exception and continue execution of the list comprehension? ...
There is no built-in expression in Python that lets you ignore an exception (or return alternate values &c in case of exceptions), so it's impossible, literally speaking, to "handle exceptions in a list comprehension" because a list comprehension is an expression containing other expression, nothing more (i.e., **no** ...
How can I handle exceptions in a list comprehension in Python?
1,528,237
35
2009-10-06T21:36:06Z
8,915,613
30
2012-01-18T18:48:01Z
[ "python", "exception-handling", "list-comprehension" ]
I have some a list comprehension in Python in which each iteration can throw an exception. **For instance**, if I have: ``` eggs = (1,3,0,3,2) [1/egg for egg in eggs] ``` I'll get a `ZeroDivisionError` exception in the 3rd element. How can I handle this exception and continue execution of the list comprehension? ...
I realize this question is quite old, but you can also create a general function to make this kind of thing easier: ``` def catch(func, handle=lambda e : e, *args, **kwargs): try: return func(*args, **kwargs) except Exception as e: return handle(e) ``` Then, in your comprehension: ``` eggs = ...
Does Python have a "compile only" switch like Perl's -c?
1,528,346
13
2009-10-06T22:03:19Z
1,528,351
15
2009-10-06T22:05:11Z
[ "python", "compiler-construction" ]
Perl has the `-c` switch to compile the code without running it. This is convenient for debugging compile errors in Perl. Does Python have a similar switch?
You can say ``` python -m py_compile script_to_check.py ``` However, this will have the side effect of creating a compiled `script_to_check.pyc` file in the same directory as your script. This feature is designed to speed up later uses of a module rather than to make sure that your syntax is correct, though you could...
Does Python have a "compile only" switch like Perl's -c?
1,528,346
13
2009-10-06T22:03:19Z
1,528,456
8
2009-10-06T22:36:35Z
[ "python", "compiler-construction" ]
Perl has the `-c` switch to compile the code without running it. This is convenient for debugging compile errors in Perl. Does Python have a similar switch?
Even better is to run [pyflakes](http://divmod.org/trac/wiki/DivmodPyflakes), [pychecker](http://pychecker.sourceforge.net/) or maybe [pylint](http://www.logilab.org/857) at the code. They catch some common errors that compiling won't.
Idiomatic way to do list/dict in Cython?
1,528,691
32
2009-10-06T23:37:44Z
2,699,569
24
2010-04-23T14:58:39Z
[ "c++", "python", "c", "cython" ]
My problem: I've found that processing large data sets with raw C++ using the STL map and vector can often be considerably faster (and with lower memory footprint) than using Cython. I figure that part of this speed penalty is due to using Python lists and dicts, and that there might be some tricks to use less encumbe...
Doing similar operations in Python as in C++ can often be slower. `list` and `dict` are actually implemented very well, but you gain a lot of overhead using Python objects, which are more abstract than C++ objects and require a lot more lookup at runtime. Incidentally, `std::vector` is implemented in a pretty similar ...
Idiomatic way to do list/dict in Cython?
1,528,691
32
2009-10-06T23:37:44Z
6,139,683
7
2011-05-26T13:55:00Z
[ "c++", "python", "c", "cython" ]
My problem: I've found that processing large data sets with raw C++ using the STL map and vector can often be considerably faster (and with lower memory footprint) than using Cython. I figure that part of this speed penalty is due to using Python lists and dicts, and that there might be some tricks to use less encumbe...
C++ is fast not just because of the static declarations of the vector and the elements that go into it, but crucially because using templates/generics one specifies that the vector will *only* contain elements of a certain type, e.g. vector with tuples of three elements. Cython can't do this last thing and it sounds no...
Idiomatic way to do list/dict in Cython?
1,528,691
32
2009-10-06T23:37:44Z
8,508,658
23
2011-12-14T17:09:26Z
[ "c++", "python", "c", "cython" ]
My problem: I've found that processing large data sets with raw C++ using the STL map and vector can often be considerably faster (and with lower memory footprint) than using Cython. I figure that part of this speed penalty is due to using Python lists and dicts, and that there might be some tricks to use less encumbe...
Cython now has template support, and comes with declarations for some of the STL containers. See <http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html#standard-library> Here's the example they give: ``` from libcpp.vector cimport vector cdef vector[int] vect cdef int i for i in range(10): vect.push_back...
reading lines 2 at a time
1,528,711
10
2009-10-06T23:42:02Z
1,528,769
14
2009-10-06T23:57:23Z
[ "python" ]
Is there a better way to read lines two at a time from a file in python than: ``` with open(fn) as f: for line in f: try: line2 = f.next() except StopIteration: line2 = '' print line, line2 # or something more interesting ``` I'm in 2.5.4. Anything different in newe...
``` import itertools with open(fn) as f: for line, line2 in itertools.izip_longest(f, f, fillvalue=''): print line, line2 ``` Alas, `izip_longest` requires Python 2.6 or better; 2.5 only has `izip`, which would truncate the last line if `f` has an odd number of lines. It's quite easy to supply the equivalent fu...
How to write an empty indentation block in Python?
1,528,903
24
2009-10-07T00:34:09Z
1,528,905
64
2009-10-07T00:34:35Z
[ "python", "syntax", "try-catch", "indentation" ]
The runtime keeps telling me: > expected an indented block But I don't want write nothing inside my except block, I just want it to catch and swallow the exception.
Just write ``` pass ``` as in ``` try: # Do something illegal. ... except: # Pretend nothing happened. pass ``` EDIT: @swillden brings up a good point, viz., this is a terrible idea in general. You should, at the least, say ``` except TypeError, DivideByZeroError: ``` or whatever kinds of errors y...
How to create inline objects with properties in Python?
1,528,932
23
2009-10-07T00:43:55Z
1,528,939
10
2009-10-07T00:47:01Z
[ "python", "instantiation", "dynamic-languages" ]
In Javascript it would be: ``` var newObject = { 'propertyName' : 'propertyValue' }; ``` How to do it in Python?
I don't know if there's a built-in way to do it, but you can always define a class like this: ``` class InlineClass(object): def __init__(self, dict): self.__dict__ = dict obj = InlineClass({'propertyName' : 'propertyValue'}) ```
How to create inline objects with properties in Python?
1,528,932
23
2009-10-07T00:43:55Z
1,528,993
47
2009-10-07T01:04:15Z
[ "python", "instantiation", "dynamic-languages" ]
In Javascript it would be: ``` var newObject = { 'propertyName' : 'propertyValue' }; ``` How to do it in Python?
``` obj = type('obj', (object,), {'propertyName' : 'propertyValue'}) ``` there are [two kinds of `type` function uses](http://docs.python.org//library/functions.html#type).
How to create inline objects with properties in Python?
1,528,932
23
2009-10-07T00:43:55Z
1,529,041
12
2009-10-07T01:23:07Z
[ "python", "instantiation", "dynamic-languages" ]
In Javascript it would be: ``` var newObject = { 'propertyName' : 'propertyValue' }; ``` How to do it in Python?
Peter's answer ``` obj = lambda: None obj.propertyName = 'propertyValue' ```
Is there an equivalent of Python's itertools for Java?
1,528,966
14
2009-10-07T00:57:24Z
5,767,853
10
2011-04-24T00:22:34Z
[ "java", "python", "combinatorics", "itertools" ]
I'm searching for a library (preferably generic) that generates iterable combinations and permutations of data contained in collections. Cartesian product would also be nice. The best way of describing what I want would be "itertools for Java".
I'm actually making a port of itertools to java: it's called [neoitertools](http://code.google.com/p/neoitertools/) Any feedback appreciated as it still in beta. Missing the "product" function yet, and some intensive tests.
Can't set attributes of object class
1,529,002
53
2009-10-07T01:07:55Z
1,529,099
88
2009-10-07T01:47:26Z
[ "python", "attributes", "language-design" ]
So, I was playing around with Python while answering [this question](http://stackoverflow.com/questions/1528932/how-to-create-inline-objects-with-properties-in-python/), and I discovered that this is not valid: ``` o = object() o.attr = 'hello' ``` due to an `AttributeError: 'object' object has no attribute 'attr'`. ...
An instance of `object` does **not** carry around a `__dict__` -- if it did, before the horrible circular dependence problem (since `dict`, like most everything else, inherits from `object`;-), this would saddle *every* object in Python with a dict, which would mean an overhead of *many* bytes per object that currently...
Can't set attributes of object class
1,529,002
53
2009-10-07T01:07:55Z
22,966,774
15
2014-04-09T15:09:53Z
[ "python", "attributes", "language-design" ]
So, I was playing around with Python while answering [this question](http://stackoverflow.com/questions/1528932/how-to-create-inline-objects-with-properties-in-python/), and I discovered that this is not valid: ``` o = object() o.attr = 'hello' ``` due to an `AttributeError: 'object' object has no attribute 'attr'`. ...
As other answerers have said, an `object` does not have a `__dict__`. `object` is the base class of **all** types, including `int` or `str`. Thus whatever is provided by `object` will be a burden to them as well. Even something as simple as an *optional* `__dict__` would need an extra pointer for each value; this would...
Print extremely large long in scientific notation in python
1,529,569
12
2009-10-07T05:03:35Z
1,529,607
15
2009-10-07T05:14:12Z
[ "python" ]
Is there a way to get python to print extremely large longs in scientific notation? I am talking about numbers on the order of 10^1000 or larger, at this size the standard print "%e" % num fails. For example: ``` Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "c...
[gmpy](http://code.google.com/p/gmpy/) to the rescue...: ``` >>> import gmpy >>> x = gmpy.mpf(10**1000) >>> x.digits(10, 0, -1, 1) '1.e1000' ``` I'm biased, of course, as the original author and still a committer of `gmpy`, but I do think it eases tasks such as this one that can be quite a chore without it (I don't k...
How to change the foreground or background colour of a Tkinter Button on Mac OS X?
1,529,847
7
2009-10-07T06:28:57Z
1,530,913
10
2009-10-07T10:58:11Z
[ "python", "osx", "tkinter" ]
I've been working through the Tkinter chapters in Programming Python and encountered a problem where the foreground and background colours of a button will not change. I am working on a Mac OS X 10.6 system with Python 2.6.1. The colours of a label will change, but not the colours of a button. For example: ``` from Tk...
I think the answer is that the buttons on the mac simply don't support changing the background and foreground colors. As you've seen, this isn't unique to Tk.
How to change the foreground or background colour of a Tkinter Button on Mac OS X?
1,529,847
7
2009-10-07T06:28:57Z
9,543,342
8
2012-03-03T04:04:44Z
[ "python", "osx", "tkinter" ]
I've been working through the Tkinter chapters in Programming Python and encountered a problem where the foreground and background colours of a button will not change. I am working on a Mac OS X 10.6 system with Python 2.6.1. The colours of a label will change, but not the colours of a button. For example: ``` from Tk...
For anyone else who happens upon this question as I did, the solution is to use the [ttk](http://docs.python.org/library/ttk.html) module, which is available by default on OS X 10.7. Unfortunately, setting the background color still doesn't work out of the box, but text color does. It requires a small change to the co...
Debugging a scripting language like ruby
1,529,896
6
2009-10-07T06:41:49Z
1,529,996
10
2009-10-07T07:09:05Z
[ "python", "ruby", "scripting-language" ]
I am basically from the world of C language programming, now delving into the world of scripting languages like Ruby and Python. I am wondering how to do debugging. At present the steps I follow is, * I complete a large script, * Comment everything but the portion I want to check * Execute the script Though it wor...
Your sequence seems entirely backwards to me. Here's how I do it: 1. I write a test for the functionality I want. 2. I start writing the script, executing bits and verifying test results. 3. I review what I'd done to document and publish. Specifically, I execute *before* I complete. It's way too late by then. There ...
Ruby methods equivalent of "if a in list" in python?
1,529,986
16
2009-10-07T07:05:15Z
1,529,991
25
2009-10-07T07:07:30Z
[ "python", "ruby", "syntax" ]
In python I can use this to check if the element in list `a`: ``` >>> a = range(10) >>> 5 in a True >>> 16 in a False ``` How this can be done in Ruby?
Use the `include?()` method: ``` (1..10).include?(5) #=>true (1..10).include?(16) #=>false ``` EDIT: `(1..10)` is [Range](http://ruby-doc.org/core/classes/Range.html) in Ruby , in the case you want an Array(list) : ``` (1..10).to_a #=> [1,2,3,4,5,6,7,8,9,10] ```
Ruby methods equivalent of "if a in list" in python?
1,529,986
16
2009-10-07T07:05:15Z
1,530,866
10
2009-10-07T10:50:48Z
[ "python", "ruby", "syntax" ]
In python I can use this to check if the element in list `a`: ``` >>> a = range(10) >>> 5 in a True >>> 16 in a False ``` How this can be done in Ruby?
Range has the === method, which checks whether the argument is part of the range. You use it like this: ``` (1..10) === 5 #=> true (1..10) === 15 #=> false ``` or as you wrote it: ``` a= (1..10) a === 5 #=> true a === 16 #=> false ``` You must be sure the values of the range and the value you are testing are of ...
Cannot shuffle list in Python
1,530,161
3
2009-10-07T07:53:55Z
1,530,164
16
2009-10-07T07:55:35Z
[ "python", "list", "random" ]
This is my list: ``` biglist = [ {'title':'U2','link':'u2.com'}, {'title':'beatles','link':'beatles.com'} ] print random.shuffle(biglist) ``` that doesn't work! It returns none.
`random.shuffle` shuffles the list, it does not return a new list. So check `biglist`, not the result of `random.shuffle`. Documentation for the `random` module: <http://docs.python.org/library/random.html>
I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?
1,530,245
2
2009-10-07T08:21:31Z
1,530,257
12
2009-10-07T08:23:19Z
[ "c++", "python", "garbage-collection" ]
I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?
Try [reading](http://en.wikipedia.org/wiki/Garbage%5Fcollection%5F%28computer%5Fscience%29) up on it.
I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?
1,530,245
2
2009-10-07T08:21:31Z
1,530,262
8
2009-10-07T08:24:03Z
[ "c++", "python", "garbage-collection" ]
I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?
That means that python user doesn't need to clean his dynamic created objects, like you're obligated to do it in C/C++. Example in C++: ``` char *ch = new char[100]; ch[0]='a'; ch[1]='b'; //.... // somewhere else in your program you need to release the alocated memory. delete [] ch; // use *delete ch;* if you've ini...
How do I change my float into a two decimal number with a comma as a decimal point separator in python?
1,530,430
6
2009-10-07T09:06:12Z
1,530,644
7
2009-10-07T10:03:22Z
[ "python", "floating-point", "decimal" ]
I have a float: 1.2333333 How do I change it into a two decimal number with a comma as a decimal point separator, eg 1,23?
The [locale module](http://docs.python.org/library/locale.html) can help you with reading and writing numbers in the locale's format. ``` >>> import locale >>> locale.setlocale(locale.LC_ALL, "") 'sv_SE.UTF-8' >>> locale.format("%f", 2.2) '2,200000' >>> locale.format("%g", 2.2) '2,2' >>> locale.atof("3,1415926") 3.141...
Don't touch my shebang!
1,530,702
20
2009-10-07T10:15:31Z
1,530,808
13
2009-10-07T10:37:09Z
[ "python", "distutils", "virtualenv" ]
One thing I hate about [*distutils*](http://docs.python.org/distutils/) (I guess he is the evil who does this) is that it changes the shebang line. In other words, the more rational and environment-vars decided scripture ``` #!/usr/bin/env python ``` gets magically converted into ``` #!/whatever/absolute/path/is/my/...
Of course you can move the development directory around. Distutils changes the paths to the python that you should run with when you run it. It's in Grok run when you run the buildout. Move and re-run the bootstrap and the buildout. Done! Distutils changes the path to the Python you use to run distutils with. If it di...
Don't touch my shebang!
1,530,702
20
2009-10-07T10:15:31Z
1,719,991
8
2009-11-12T05:01:14Z
[ "python", "distutils", "virtualenv" ]
One thing I hate about [*distutils*](http://docs.python.org/distutils/) (I guess he is the evil who does this) is that it changes the shebang line. In other words, the more rational and environment-vars decided scripture ``` #!/usr/bin/env python ``` gets magically converted into ``` #!/whatever/absolute/path/is/my/...
Distutils will automatically replace the shebang with the location of the Python binary that was used to execute setup.py. To override this behavior you have two options: **Option 1: Manually** You may pass the flag **--executable=/path/to/my/python** to setup.py. Arguments are accepted. Example: ``` % python setup...
Incrementally building a numpy array and measuring memory usage
1,530,960
11
2009-10-07T11:08:36Z
1,534,233
7
2009-10-07T21:14:40Z
[ "python", "numpy", "memory-management" ]
I have a series of large text files (up to 1 gig) that are output from an experiment that need to be analysed in Python. They would be best loaded into a 2D numpy array, which presents the first question: * As the number of rows is unknown at the beginning of the loading, how can a very large numpy array be most eff...
There's no way to ensure you can grow the array in place other than creating an empty array (numpy.empty) of the maximum possible size and then using a view of that at the end. You can't start small because there's no guarantee that you can expand whatever memory the map is without clobbering some other data. (And all ...
For list unless empty in python
1,531,402
12
2009-10-07T12:43:07Z
1,531,525
7
2009-10-07T13:05:42Z
[ "for-loop", "python" ]
I've been writing a lot of constructs like this the past couple of days: ``` list = get_list() if list: for i in list: pass # do something with the list else: pass # do something if the list was empty ``` Lot of junk and I assign the list to a real variable (keeping it in memory longer than needed). P...
Use a list comprehension: ``` def do_something(x): return x**2 list = [] result = [do_something(x) for x in list if list] print result # [] list = [1, 2, 3] result = [do_something(x) for x in list if list] print result # [1, 4, 9] ```
For list unless empty in python
1,531,402
12
2009-10-07T12:43:07Z
1,534,260
16
2009-10-07T21:21:24Z
[ "for-loop", "python" ]
I've been writing a lot of constructs like this the past couple of days: ``` list = get_list() if list: for i in list: pass # do something with the list else: pass # do something if the list was empty ``` Lot of junk and I assign the list to a real variable (keeping it in memory longer than needed). P...
Based on the other answers, I think the cleanest solutions are ``` #Handles None return from get_list for item in get_list() or []: pass #do something ``` or the comprehension equiv ``` result = [item*item for item in get_list() or []] ```
JSON serialization of Google App Engine models
1,531,501
83
2009-10-07T13:01:17Z
1,532,035
60
2009-10-07T14:36:52Z
[ "python", "json", "google-app-engine" ]
I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? **Model:** ``` class Photo(db.Model): filename = db.StringProperty() title = db.StringPr...
A simple recursive function can be used to convert an entity (and any referents) to a nested dictionary that can be passed to `simplejson`: ``` import datetime import time SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list) def to_dict(model): output = {} for key, prop in model.properties().iter...
JSON serialization of Google App Engine models
1,531,501
83
2009-10-07T13:01:17Z
2,305,601
58
2010-02-21T10:42:46Z
[ "python", "json", "google-app-engine" ]
I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? **Model:** ``` class Photo(db.Model): filename = db.StringProperty() title = db.StringPr...
This is the simplest solution I found. It requires only 3 lines of codes. Simply add a method to your model to return a dictionary: ``` class DictModel(db.Model): def to_dict(self): return dict([(p, unicode(getattr(self, p))) for p in self.properties()]) ``` SimpleJSON now works properly: ``` class Photo...
JSON serialization of Google App Engine models
1,531,501
83
2009-10-07T13:01:17Z
3,063,649
7
2010-06-17T16:39:10Z
[ "python", "json", "google-app-engine" ]
I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? **Model:** ``` class Photo(db.Model): filename = db.StringProperty() title = db.StringPr...
To serialize models, add a custom json encoder as in the following python: ``` import datetime from google.appengine.api import users from google.appengine.ext import db from django.utils import simplejson class jsonEncoder(simplejson.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datet...
JSON serialization of Google App Engine models
1,531,501
83
2009-10-07T13:01:17Z
6,829,471
15
2011-07-26T11:43:18Z
[ "python", "json", "google-app-engine" ]
I've been searching for quite a while with no success. My project isn't using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model) into JSON or do I need to write my own serializer? **Model:** ``` class Photo(db.Model): filename = db.StringProperty() title = db.StringPr...
In the latest (1.5.2) release of the App Engine SDK, a `to_dict()` function that converts model instances to dictionaries was introduced in `db.py`. See the [release notes](http://code.google.com/p/googleappengine/wiki/SdkReleaseNotes#Version_1.5.2_-_July_21,_2011). There is no reference to this function in the docume...
How to yank an entire block in Vim?
1,531,551
17
2009-10-07T13:10:07Z
1,531,576
18
2009-10-07T13:15:24Z
[ "python", "vim" ]
Is it possible to yank an entire block of Python code in Vim? Be it a `def`, `for`, `if`, etc. block...
You can yank a paragraph with `y}`. This will not yank all the methods if you have a blank line though.
Supporting Multiple Python Versions In Your Code?
1,532,488
6
2009-10-07T15:48:28Z
1,532,531
9
2009-10-07T15:55:20Z
[ "python", "versioning" ]
Today I tried using [pyPdf](http://pybrary.net/pyPdf/) 1.12 in a script I was writing that targets Python 2.6. When running my script, and even importing pyPdf, I get complaints about deprecated functionality (md5->hashsum, sets). I'd like to contribute a patch to make this work cleanly in 2.6, but I imagine the author...
There are two ways to do this: --- (1) Just like you described: Try something and work around the exception for old versions. For example, you could try to import the `json` module and import a userland implementation if this fails: ``` try: import json except ImportError: import myutils.myjson as json ``` ...
Is there anyway to persuade python's getopt to handle optional parameters to options?
1,532,737
6
2009-10-07T16:30:58Z
1,532,761
7
2009-10-07T16:36:27Z
[ "python", "getopt", "getopt-long" ]
According to the documentation on python's `getopt` (I think) the options fields should behave as the `getopt()` function. However I can't seem to enable optional parameters to my code: ``` #!/usr/bin/python import sys,getopt if __name__ == "__main__": try: opts, args = getopt.gnu_getopt(sys.argv[1:], "v:...
`getopt` doesn't support optional parameters. in case of long option you could do: ``` $ ./testopt.py --verbose= ``` which will result in empty-string value. You could find [`argparse`](http://code.google.com/p/argparse/) module to be more flexible.
How to read lines from a file into a multidimensional array (or an array of lists) in python
1,532,810
3
2009-10-07T16:46:05Z
1,532,816
7
2009-10-07T16:47:42Z
[ "python", "list", "multidimensional-array" ]
I have a file with a format similar to this: ``` a,3,4,2,1 3,2,1,a,2 ``` I want to read the file and create an array of lists in a way that: ``` array[0] = ['a','3','4','2','1'] array[1] = ['3','2','1','a','2'] ``` How can I do that? So far I am stuck with: ``` f = open('./urls-eu.csv', 'r') for line in f: a...
you're almost there, you just need to do: ``` arr = [line.split(',') for line in open('./urls-eu.csv')] ``` it iteratively process file line by line, splits each line by comma and accumulates resulting lists into a list of lists. you can drop opening mode (`'r'`) since it's a default one.
How to read lines from a file into a multidimensional array (or an array of lists) in python
1,532,810
3
2009-10-07T16:46:05Z
1,532,899
16
2009-10-07T17:00:16Z
[ "python", "list", "multidimensional-array" ]
I have a file with a format similar to this: ``` a,3,4,2,1 3,2,1,a,2 ``` I want to read the file and create an array of lists in a way that: ``` array[0] = ['a','3','4','2','1'] array[1] = ['3','2','1','a','2'] ``` How can I do that? So far I am stuck with: ``` f = open('./urls-eu.csv', 'r') for line in f: a...
Batteries included: ``` >>> import csv >>> array = list( csv.reader( open( r'./urls-eu.csv' ) ) ) >>> array[0] ['a', '3', '4', '2', '1'] >>> array[1] ['3', '2', '1', 'a', '2'] ```
Open IE Browser Window
1,532,884
8
2009-10-07T16:58:10Z
1,532,990
14
2009-10-07T17:14:03Z
[ "python", "internet-explorer", "browser" ]
The [`webbrowser` library](http://docs.python.org/library/webbrowser.html) provides a convenient way to launch a URL with a browser window through the `webbrowser.open()` method. Numerous browser types are available, but there does not appear to be an explicit way to launch Internet Explorer when running python on wind...
``` >>> ie = webbrowser.get('c:\\program files\\internet explorer\\iexplore.exe') >>> ie.open('http://google.com') True ```
Open IE Browser Window
1,532,884
8
2009-10-07T16:58:10Z
11,976,103
15
2012-08-15T19:43:36Z
[ "python", "internet-explorer", "browser" ]
The [`webbrowser` library](http://docs.python.org/library/webbrowser.html) provides a convenient way to launch a URL with a browser window through the `webbrowser.open()` method. Numerous browser types are available, but there does not appear to be an explicit way to launch Internet Explorer when running python on wind...
More elegant code: ``` import webbrowser ie = webbrowser.get(webbrowser.iexplore) ie.open('google.com') ```
Use different Python version with virtualenv
1,534,210
501
2009-10-07T21:11:22Z
1,534,343
753
2009-10-07T21:33:12Z
[ "python", "virtualenv", "virtualenvwrapper" ]
I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python? I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary...
Just use the -p flag when creating your virtualenv instance to specify the Python executable you want to use, e.g.: ``` virtualenv -p /usr/bin/python2.6 <path/to/new/virtualenv/> ```
Use different Python version with virtualenv
1,534,210
501
2009-10-07T21:11:22Z
1,674,444
74
2009-11-04T15:15:15Z
[ "python", "virtualenv", "virtualenvwrapper" ]
I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python? I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary...
``` virtualenv --python=/usr/bin/python2.6 <path/to/myvirtualenv> ```
Use different Python version with virtualenv
1,534,210
501
2009-10-07T21:11:22Z
6,892,302
49
2011-07-31T21:04:32Z
[ "python", "virtualenv", "virtualenvwrapper" ]
I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python? I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary...
Under Windows for me this works: ``` virtualenv --python=c:\Python25\python.exe envname ``` without the `python.exe` I got `WindowsError: [Error 5] Access is denied` I have Python2.7.1 installed with virtualenv 1.6.1, and I wanted python 2.5.2.