title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python read a single character from the user
510,357
157
2009-02-04T07:08:03Z
510,364
105
2009-02-04T07:11:04Z
[ "python", "input" ]
Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform.
Here's a link to a site that says how you can read a single character in Windows, Linux and OSX: <http://code.activestate.com/recipes/134892/> ``` class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() getch = _Getch() ```
Python read a single character from the user
510,357
157
2009-02-04T07:08:03Z
510,404
54
2009-02-04T07:30:51Z
[ "python", "input" ]
Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform.
``` sys.stdin.read(1) ``` will basically read 1 byte from STDIN. If you must use the method which does not wait for the `\n` you can use this code as suggested in previous answer: ``` class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() getch = _Getch() ``` (*taken from* [*http://code.activestate.com/recipes/134892/*](http://code.activestate.com/recipes/134892/))
Python read a single character from the user
510,357
157
2009-02-04T07:08:03Z
510,897
12
2009-02-04T11:04:26Z
[ "python", "input" ]
Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform.
I think it gets extremely clunky at this point, and debugging on the different platforms is a big mess. You'd be better off using something like pyglet, pygame, cocos2d - if you are doing something more elaborate than this and will need visuals, OR **curses** if you are going to work with the terminal. Curses is standard: <http://docs.python.org/library/curses.html>
Python read a single character from the user
510,357
157
2009-02-04T07:08:03Z
7,259,460
14
2011-08-31T15:30:40Z
[ "python", "input" ]
Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform.
An alternative method: ``` import os import sys import termios import fcntl def getch(): fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) try: while 1: try: c = sys.stdin.read(1) break except IOError: pass finally: termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) return c ``` From [this blog post](http://love-python.blogspot.com/2010/03/getch-in-python-get-single-character.html).
Python read a single character from the user
510,357
157
2009-02-04T07:08:03Z
20,865,751
9
2014-01-01T05:13:33Z
[ "python", "input" ]
Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform.
This code, based off [here](http://code.activestate.com/recipes/134892/), will correctly raise KeyboardInterrupt and EOFError if `Ctrl`+`C` or `Ctrl`+`D` are pressed. Should work on Windows and Linux. An OS X version is available from the original source. ``` class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): char = self.impl() if char == '\x03': raise KeyboardInterrupt elif char == '\x04': raise EOFError return char class _GetchUnix: def __init__(self): import tty import sys def __call__(self): import sys import tty import termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() getch = _Getch() ```
Python read a single character from the user
510,357
157
2009-02-04T07:08:03Z
21,659,588
31
2014-02-09T13:27:42Z
[ "python", "input" ]
Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform.
The ActiveState [recipe](http://code.activestate.com/recipes/134892/) quoted verbatim in two answers is over-engineered. It can be boiled down to this: ``` def _find_getch(): try: import termios except ImportError: # Non-POSIX. Return msvcrt's (Windows') getch. import msvcrt return msvcrt.getch # POSIX system. Create and return a getch that manipulates the tty. import sys, tty def _getch(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch return _getch getch = _find_getch() ```
Python read a single character from the user
510,357
157
2009-02-04T07:08:03Z
25,342,814
21
2014-08-16T18:47:41Z
[ "python", "input" ]
Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform.
Also worth trying is the [readchar](https://github.com/magmax/python-readchar) library, which is in part based on the ActiveState recipe mentioned in other answers. Installation: ``` pip install readchar ``` Usage: ``` import readchar print("Reading a char:") print(repr(readchar.readchar())) print("Reading a key:") print(repr(readchar.readkey())) ``` Tested on Windows and Linux with Python 2.7. On Windows, only keys which map to letters or ASCII control codes are supported (`Backspace`, `Enter`, `Esc`, `Tab`, `Ctrl`+*letter*). On GNU/Linux (depending on exact terminal, perhaps?) you also get `Insert`, `Delete`, `Pg Up`, `Pg Dn`, `Home`, `End` and `F n` keys... but then, there's issues separating these special keys from an `Esc`. Caveat: Like with most (all?) answers in here, signal keys like `Ctrl`+`C`, `Ctrl`+`D` and `Ctrl`+`Z` are caught and returned (as `'\x03'`, `'\x04'` and `'\x1a'` respectively); your program can be come difficult to abort.
Is there a way to get the current ref count of an object in Python?
510,406
34
2009-02-04T07:32:51Z
510,411
36
2009-02-04T07:36:25Z
[ "python", "refcounting" ]
Is there a way to get the current ref count of an object in Python?
Using the `gc` module, the interface to the garbage collector guts, you can call `gc.get_referrers(foo)` to get a list of everything referring to `foo`. Hence, `len(gc.get_referrers(foo))` will give you the length of that list: the number of referrers, which is what you're after. See also the [`gc` module documentation](http://docs.python.org/library/gc.html).
Is there a way to get the current ref count of an object in Python?
510,406
34
2009-02-04T07:32:51Z
510,417
41
2009-02-04T07:39:03Z
[ "python", "refcounting" ]
Is there a way to get the current ref count of an object in Python?
According to some Python 2.0 reference (<http://www.brunningonline.net/simon/python/quick-ref2_0.html>), the sys module contains a function: ``` import sys sys.getrefcount(object) #-- Returns the reference count of the object. ``` Generally 1 higher than you might expect, because of object arg temp reference.
Getting the class name of an instance in Python
510,972
689
2009-02-04T11:37:48Z
510,988
52
2009-02-04T11:42:31Z
[ "python", "introspection", "instanceof", "python-datamodel" ]
How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived? Was thinking maybe [the inspect module](https://docs.python.org/2/library/inspect.html) might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the `__class__` member, I'm not sure how to get at this information.
type() ? ``` >>> class A(object): ... def whoami(self): ... print type(self).__name__ ... >>> >>> class B(A): ... pass ... >>> >>> >>> o = B() >>> o.whoami() 'B' >>> ```
Getting the class name of an instance in Python
510,972
689
2009-02-04T11:37:48Z
511,059
948
2009-02-04T12:02:12Z
[ "python", "introspection", "instanceof", "python-datamodel" ]
How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived? Was thinking maybe [the inspect module](https://docs.python.org/2/library/inspect.html) might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the `__class__` member, I'm not sure how to get at this information.
Have you tried the `__name__` attribute of the class? ie `type(x).__name__` will give you the name of the class, which I think is what you want. ``` >>> import itertools >>> x = itertools.count(0) >>> type(x).__name__ 'count' ``` This method works with [new-style classes](https://wiki.python.org/moin/NewClassVsClassicClass) only. Your code might use some old-style classes. The following works for both: ``` x.__class__.__name__ ```
Getting the class name of an instance in Python
510,972
689
2009-02-04T11:37:48Z
511,060
177
2009-02-04T12:02:16Z
[ "python", "introspection", "instanceof", "python-datamodel" ]
How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived? Was thinking maybe [the inspect module](https://docs.python.org/2/library/inspect.html) might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the `__class__` member, I'm not sure how to get at this information.
Do you want the name of the class as a string? ``` instance.__class__.__name__ ```
Getting the class name of an instance in Python
510,972
689
2009-02-04T11:37:48Z
9,383,568
9
2012-02-21T19:07:40Z
[ "python", "introspection", "instanceof", "python-datamodel" ]
How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived? Was thinking maybe [the inspect module](https://docs.python.org/2/library/inspect.html) might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the `__class__` member, I'm not sure how to get at this information.
Good question. Here's a simple example based on GHZ's which might help someone: ``` >>> class person(object): def init(self,name): self.name=name def info(self) print "My name is {0}, I am a {1}".format(self.name,self.__class__.__name__) >>> bob = person(name='Robert') >>> bob.info() My name is Robert, I am a person ```
Getting the class name of an instance in Python
510,972
689
2009-02-04T11:37:48Z
16,293,038
16
2013-04-30T05:50:38Z
[ "python", "introspection", "instanceof", "python-datamodel" ]
How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived? Was thinking maybe [the inspect module](https://docs.python.org/2/library/inspect.html) might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the `__class__` member, I'm not sure how to get at this information.
``` type(instance).__name__ != instance.__class__.__name #if class A is defined like class A(): ... type(instance) == instance.__class__ #if class A is defined like class A(object): ... ``` Example: ``` >>> class aclass(object): ... pass ... >>> a = aclass() >>> type(a) <class '__main__.aclass'> >>> a.__class__ <class '__main__.aclass'> >>> >>> type(a).__name__ 'aclass' >>> >>> a.__class__.__name__ 'aclass' >>> >>> class bclass(): ... pass ... >>> b = bclass() >>> >>> type(b) <type 'instance'> >>> b.__class__ <class __main__.bclass at 0xb765047c> >>> type(b).__name__ 'instance' >>> >>> b.__class__.__name__ 'bclass' >>> ```
Getting the class name of an instance in Python
510,972
689
2009-02-04T11:37:48Z
24,130,402
12
2014-06-09T23:04:17Z
[ "python", "introspection", "instanceof", "python-datamodel" ]
How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived? Was thinking maybe [the inspect module](https://docs.python.org/2/library/inspect.html) might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the `__class__` member, I'm not sure how to get at this information.
``` class A: pass a = A() str(a.__class__) ``` The sample code above (when input in the interactive interpreter) will produce `'__main__.A'` as opposed to `'A'` which is produced if the `__name__` attribute is invoked. By simply passing the result of `A.__class__` to the `str` constructor the parsing is handled for you. However, you could also use the following code if you want something more explicit. ``` "{0}.{1}".format(a.__class__.__module__,a.__class__.__name__) ``` This behavior can be preferable if you have classes with the same name defined in separate modules. **The sample code provided above was tested in Python 2.7.5.**
How to print a string without including '\n' in Python
511,204
15
2009-02-04T12:52:14Z
511,208
19
2009-02-04T12:53:50Z
[ "python", "string" ]
Suppose my string is: ``` ' Hai Hello\nGood eve\n' ``` How do I eliminate the `'\n'` in between and make a string print like : ``` Hai Hello Good eve ``` ?
You can use the `replace` method: ``` >>> a = "1\n2" >>> print a 1 2 >>> a = a.replace("\n", " ") >>> print a 1 2 ```
How to print a string without including '\n' in Python
511,204
15
2009-02-04T12:52:14Z
511,216
22
2009-02-04T12:55:43Z
[ "python", "string" ]
Suppose my string is: ``` ' Hai Hello\nGood eve\n' ``` How do I eliminate the `'\n'` in between and make a string print like : ``` Hai Hello Good eve ``` ?
If you don't want the newline at the end of the print statement: ``` import sys sys.stdout.write("text") ```
How to print a string without including '\n' in Python
511,204
15
2009-02-04T12:52:14Z
1,038,910
11
2009-06-24T15:00:05Z
[ "python", "string" ]
Suppose my string is: ``` ' Hai Hello\nGood eve\n' ``` How do I eliminate the `'\n'` in between and make a string print like : ``` Hai Hello Good eve ``` ?
In Python 2.6: ``` print "Hello.", print "This is on the same line" ``` In Python 3.0 ``` print("Hello", end = " ") print("This is on the same line") ```
Django Installed Apps Location
511,291
13
2009-02-04T13:15:59Z
511,408
35
2009-02-04T13:41:41Z
[ "python", "django" ]
I am an experienced PHP programmer using Django for the first time, and I think it is incredible! I have a project that has a lot of apps, so I wanted to group them in an apps folder. So the structure of the project is: ``` /project/ /project/apps/ /project/apps/app1/ /project/apps/app2 ``` Then in Django settings I have put this: ``` INSTALLED_APPS = ( 'project.apps.app1', 'project.apps.app2', ) ``` This does not seem to work? Any ideas on how you can put all your apps into a seprate folder and not in the project root? Many thanks.
Make sure that the '\_\_init\_\_.py' file is in your apps directory, if it's not there it won't be recognized as part of the package. So each of the folders here should have '\_\_init\_\_.py' file in it. (empty is fine). ``` /project/ /project/apps/ /project/apps/app1/ /project/apps/app2 ``` Then as long as your root 'module' folder is in your PYTHONPATH you'll be able to import from your apps. Here's the documentation regarding the python search path for your reading pleasure: <http://docs.python.org/install/index.html#modifying-python-s-search-path> And a nice simple explanation of what \_\_init\_\_.py file is for: <http://effbot.org/pyfaq/what-is-init-py-used-for.htm>
How to copy a directory and its contents to an existing location using Python?
512,173
32
2009-02-04T16:41:12Z
512,273
41
2009-02-04T17:03:21Z
[ "python", "operating-system", "filesystems", "copy" ]
I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the `shutil.copytree()` function expects that the destination path not exist beforehand. The exact result I'm looking for is to copy an entire folder structure on top of another, overwriting silently on any duplicates found. Before I jump in and start writing my own function to do this I thought I'd ask if anyone knows of an existing recipe or snippet that does this.
[`distutils.dir_util.copy_tree`](http://docs.python.org/distutils/apiref.html#distutils.dir_util.copy_tree) does what you want. > Copy an entire directory tree src to a > new location dst. Both src and dst > must be directory names. If src is not > a directory, raise DistutilsFileError. > If dst does not exist, it is created > with mkpath(). The end result of the > copy is that every file in src is > copied to dst, and directories under > src are recursively copied to dst. > Return the list of files that were > copied or might have been copied, > using their output name. The return > value is unaffected by update or > dry\_run: it is simply the list of all > files under src, with the names > changed to be under dst. (more documentation at the above url)
gedit plugin development in python
512,600
10
2009-02-04T18:15:16Z
536,198
7
2009-02-11T10:08:36Z
[ "python", "plugins", "gedit" ]
Does anyone know where information about writing gedit plugins can be found ? I'm interested in writing them in Python. I know of [Gedit/PythonPluginHowTo](http://live.gnome.org/Gedit/PythonPluginHowTo) , but it isn't very good . Besides the code of writing a plugin that does nothing , I can't seem to find more information . I started to look at other people's code , but I think this shouldn't be the natural way of writing plugins . Can someone help ?
When I started working on my gedit plugin, I used the howto you gave a link to, also startign with [this URL](http://www.russellbeattie.com/blog/my-first-gedit-plugin). Then it was looking at other plugins code... I'm sorry to say that, but for me this topic is poorly documented and best and fastest way is to get a pluging done that actually does something.
memory use in large data-structures manipulation/processing
512,893
4
2009-02-04T19:25:03Z
515,820
7
2009-02-05T13:09:36Z
[ "python", "data-structures", "memory-leaks", "garbage-collection" ]
I have a number of large (~100 Mb) files which I'm regularly processing. While I'm trying to delete unneeded data structures during processing, memory consumption is a bit too high. I was wondering if there is a way to efficiently manipulate large data, e.g.: ``` def read(self, filename): fc = read_100_mb_file(filename) self.process(fc) def process(self, content): # do some processing of file content ``` Is there a duplication of data structures? Isn't it more memory efficient to use a class-wide attribute like self.fc? When should I use garbage collection? I know about the gc module, but do I call it after I `del fc` for example? **update** p.s. 100 Mb is not a problem in itself. but float conversion, further processing add significantly more to both working set and virtual size (I'm on Windows).
I'd suggest looking at the [presentation by David Beazley](http://www.dabeaz.com/generators/) on using generators in Python. This technique allows you to handle a lot of data, and do complex processing, quickly and without blowing up your memory use. IMO, the trick isn't holding a huge amount of data in memory as efficiently as possible; the trick is avoiding loading a huge amount of data into memory at the same time.
pure web based versioning system
513,173
3
2009-02-04T20:34:13Z
513,231
7
2009-02-04T20:45:06Z
[ "php", "python", "version-control", "web-applications" ]
My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server. I am looking for a **pure php/python/ruby version control system** (not just a *client* for a version control system) that does not require any services running on the server machine, something that could use the http interface to upload/download and sync files - basically offering a back end into my 'live' site for version control. Additionally, I would think that such a system would be easy to develop an 'online' ide for, so that I could develop directly on the production server. (issues of testing aside of course) Does anyone know if such a system exists? ==Edit== Really, I want a wiki front end for a version control / development system - Basically look like a wiki and edit development files so that I could easily make and roll back changes via the web. I doubt this exists, but it would be easy to extend an existing php port of svn...
Get a better hosting service. Seriously. Even if you found something that worked in PHP/Ruby/Perl/Whatever, it would still be a sub-par solution. It most likely wouldn't integrate with any IDE you have, and wouldn't have a good tool set available for working with it. It would be really clunky to do correctly. The other option is to get a free SVN host, or host SVN on your own machine, and then just push updates from your SVN host to your web site via ftp.
Delete file from zipfile with the ZipFile Module
513,788
22
2009-02-04T23:00:26Z
513,889
28
2009-02-04T23:31:37Z
[ "python", "zip" ]
The only way i came up for deleting a file from a zipfile was to create a temporary zipfile without the file to be deleted and then rename it to the original filename. In python 2.4 the ZipInfo class had an attribute `file_offset`, so it was possible to create a second zip file and copy the data to other file without decompress/recompressing. This `file_offset` is missing in python 2.6, so is there another option than creating another zipfile by uncompressing every file and then recompressing it again? Is there maybe a direct way of deleting a file in the zipfile, i searched and didn't find anything. Thanks in advance.
The following snippet worked for me (deletes all \*.exe files from a Zip archive): ``` zin = zipfile.ZipFile ('archive.zip', 'r') zout = zipfile.ZipFile ('archve_new.zip', 'w') for item in zin.infolist(): buffer = zin.read(item.filename) if (item.filename[-4:] != '.exe'): zout.writestr(item, buffer) zout.close() zin.close() ``` If you read everything into memory, you can eliminate the need for a second file. However, this snippet recompresses everything. After closer inspection the `ZipInfo.header_offset` is the offset from the file start. The name is misleading, but the main Zip header is actually stored at the end of the file. My hex editor confirms this. So the problem you'll run into is the following: You need to delete the directory entry in the main header as well or it will point to a file that doesn't exist anymore. Leaving the main header intact might work if you keep the local header of the file you're deleting as well, but I'm not sure about that. How did you do it with the old module? Without modifying the main header I get an error "missing X bytes in zipfile" when I open it. [This](http://www.pkware.com/documents/casestudies/APPNOTE.TXT) might help you to find out how to modify the main header.
Python: List vs Dict for look up table
513,882
79
2009-02-04T23:28:41Z
513,890
28
2009-02-04T23:31:41Z
[ "python", "performance" ]
I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a *list* or *dict*? I know you can do something like this for both: ``` if something in dict_of_stuff: pass ``` and ``` if something in list_of_stuff: pass ``` My thought is the dict will be faster and more efficient. Thanks for your help. **EDIT 1** Little more info on what I'm trying to do. [Euler Problem 92](http://projecteuler.net/index.php?section=problems&id=92). I'm making a look up table to see if a value calculated has all ready been calculated. **EDIT 2** Efficiency for look up. **EDIT 3** There are no values assosiated with the value...so would a *set* be better?
A dict is a hash table, so it is really fast to find the keys. So between dict and list, dict would be faster. But if you don't have a value to associate, it is even better to use a set. It is a hash table, without the "table" part. --- EDIT: for your new question, YES, a set would be better. Just create 2 sets, one for sequences ended in 1 and other for the sequences ended in 89. I have sucessfully solved this problem using sets.
Python: List vs Dict for look up table
513,882
79
2009-02-04T23:28:41Z
513,906
109
2009-02-04T23:38:36Z
[ "python", "performance" ]
I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a *list* or *dict*? I know you can do something like this for both: ``` if something in dict_of_stuff: pass ``` and ``` if something in list_of_stuff: pass ``` My thought is the dict will be faster and more efficient. Thanks for your help. **EDIT 1** Little more info on what I'm trying to do. [Euler Problem 92](http://projecteuler.net/index.php?section=problems&id=92). I'm making a look up table to see if a value calculated has all ready been calculated. **EDIT 2** Efficiency for look up. **EDIT 3** There are no values assosiated with the value...so would a *set* be better?
# Speed Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets. # Memory Both dictionaries and sets use hashing and they use much more memory than only for object storage. According to A.M. Kuchling in *Beautiful Code*, the implementation tries to keep the hash 2/3 full, so you might waste quite some memory. If you do not add new entries on the fly (which you do, based on your updated question), it might be worthwhile to sort the list and use binary search. This is O(log n), and is likely to be slower for strings, impossible for objects which do not have a natural ordering.
Python: List vs Dict for look up table
513,882
79
2009-02-04T23:28:41Z
578,968
17
2009-02-23T19:24:39Z
[ "python", "performance" ]
I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a *list* or *dict*? I know you can do something like this for both: ``` if something in dict_of_stuff: pass ``` and ``` if something in list_of_stuff: pass ``` My thought is the dict will be faster and more efficient. Thanks for your help. **EDIT 1** Little more info on what I'm trying to do. [Euler Problem 92](http://projecteuler.net/index.php?section=problems&id=92). I'm making a look up table to see if a value calculated has all ready been calculated. **EDIT 2** Efficiency for look up. **EDIT 3** There are no values assosiated with the value...so would a *set* be better?
[`set()`](http://docs.python.org/library/sets.html) is exactly what you want. O(1) lookups, and smaller than a dict.
Python: List vs Dict for look up table
513,882
79
2009-02-04T23:28:41Z
11,241,481
12
2012-06-28T09:16:06Z
[ "python", "performance" ]
I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a *list* or *dict*? I know you can do something like this for both: ``` if something in dict_of_stuff: pass ``` and ``` if something in list_of_stuff: pass ``` My thought is the dict will be faster and more efficient. Thanks for your help. **EDIT 1** Little more info on what I'm trying to do. [Euler Problem 92](http://projecteuler.net/index.php?section=problems&id=92). I'm making a look up table to see if a value calculated has all ready been calculated. **EDIT 2** Efficiency for look up. **EDIT 3** There are no values assosiated with the value...so would a *set* be better?
I did some benchmarking and it turns out that dict is faster than both list and set for large data sets, running python 2.7.3 on an i7 CPU on linux: * `python -mtimeit -s 'd=range(10**7)' '5*10**6 in d'` 10 loops, best of 3: 64.2 msec per loop * `python -mtimeit -s 'd=dict.fromkeys(range(10**7))' '5*10**6 in d'` 10000000 loops, best of 3: 0.0759 usec per loop * `python -mtimeit -s 'from sets import Set; d=Set(range(10**7))' '5*10**6 in d'` 1000000 loops, best of 3: 0.262 usec per loop As you can see, dict is considerably faster than list and about 3 times faster than set. In some applications you might still want to choose set for the beauty of it, though. And if the data sets are really small (< 1000 elements) lists perform pretty well.
How to split a string by using [] in Python
514,029
2
2009-02-05T00:37:27Z
514,045
13
2009-02-05T00:42:05Z
[ "python", "string" ]
So from this string: "name[id]" I need this: "id" I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?
Use a regular expression: ``` import re s = "name[id]" re.find(r"\[(.*?)\]", s).group(1) # = 'id' ``` `str.split()` takes a string on which to split input. For instance: ``` "i,split,on commas".split(',') # = ['i', 'split', 'on commas'] ``` The `re` module also allows you to split by regular expression, which can be *very* useful, and I think is what you meant to do. ``` import re s = "name[id]" # split by either a '[' or a ']' re.split('\[|\]', s) # = ['name', 'id', ''] ```
How to split a string by using [] in Python
514,029
2
2009-02-05T00:37:27Z
514,047
7
2009-02-05T00:42:15Z
[ "python", "string" ]
So from this string: "name[id]" I need this: "id" I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?
Either ``` "name[id]".split('[')[1][:-1] == "id" ``` or ``` "name[id]".split('[')[1].split(']')[0] == "id" ``` or ``` re.search(r'\[(.*?)\]',"name[id]").group(1) == "id" ``` or ``` re.split(r'[\[\]]',"name[id]")[1] == "id" ```
Elegant ways to return multiple values from a function
514,038
27
2009-02-05T00:39:48Z
514,071
24
2009-02-05T00:48:27Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
It seems like in most mainstream programming languages, **returning multiple values from a function** is an extremely awkward thing. The typical solutions are to make either a **struct** or a plain old data **class** and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types. The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking: ``` a, b = foo(c) # a and b are regular variables. myTuple = foo(c) # myTuple is a tuple of (a, b) ``` Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.
Pretty much all ML-influenced functional langues (which is most of them) also have great tuple support that makes this sort of thing trivial. For C++ I like boost::tuple plus boost::tie (or std::tr1 if you have it) ``` typedef boost::tuple<double,double,double> XYZ; XYZ foo(); double x,y,z; boost::tie(x,y,z) = foo(); ``` or a less contrived example ``` MyMultimap::iterator lower,upper; boost::tie(lower,upper) = some_map.equal_range(key); ```
Elegant ways to return multiple values from a function
514,038
27
2009-02-05T00:39:48Z
514,114
9
2009-02-05T01:05:05Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
It seems like in most mainstream programming languages, **returning multiple values from a function** is an extremely awkward thing. The typical solutions are to make either a **struct** or a plain old data **class** and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types. The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking: ``` a, b = foo(c) # a and b are regular variables. myTuple = foo(c) # myTuple is a tuple of (a, b) ``` Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.
A few languages, notably Lisp and JavaScript, have a feature called destructuring assignment or destructuring bind. This is essentially tuple unpacking on steroids: rather than being limited to sequences like tuples, lists, or generators, you can unpack more complex object structures in an assignment statement. For more details, see [here for the Lisp version](http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/mac_destructuring-bind.html) or [here for the (rather more readable) JavaScript version](https://developer.mozilla.org/en/New_in_JavaScript_1.7#Destructuring_assignment). Other than that, I don't know of many language features for dealing with multiple return values generally. However, there are a few specific uses of multiple return values that can often be replaced by other language features. For example, if one of the values is an error code, it might be better replaced with an exception. While creating new classes to hold multiple return values feels like clutter, the fact that you're returning those values together is often a sign that your code will be better overall once the class is created. In particular, other functions that deal with the same data can then move to the new class, which may make your code easier to follow. This isn't universally true, but it's worth considering. (Cpeterso's answer about data clumps expresses this in more detail).
Elegant ways to return multiple values from a function
514,038
27
2009-02-05T00:39:48Z
514,300
7
2009-02-05T02:31:32Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
It seems like in most mainstream programming languages, **returning multiple values from a function** is an extremely awkward thing. The typical solutions are to make either a **struct** or a plain old data **class** and return that, or to pass at least some of the parameters by reference or pointer instead of returning them. Using references/pointers is pretty awkward because it relies on side effects and means you have yet another parameter to pass. The class/struct solution is also IMHO pretty awkward because you then end up with a million little classes/structs that are only used to return values from functions, generating unnecessary clutter and verbosity. Furthermore, a lot of times there's one return value that is always needed, and the rest are only used by the caller in certain circumstances. Neither of these solutions allow the caller to ignore unneeded return types. The one language I'm aware of that handles multiple return values elegantly is Python. For those of you who are unfamiliar, it uses tuple unpacking: ``` a, b = foo(c) # a and b are regular variables. myTuple = foo(c) # myTuple is a tuple of (a, b) ``` Does anyone have any other good solutions to this problem? Both idioms that work in existing mainstream languages besides Python and language-level solutions you've seen in non-mainstream languages are welcome.
PHP example: ``` function my_funct() { $x = "hello"; $y = "world"; return array($x, $y); } ``` Then, when run: ``` list($x, $y) = my_funct(); echo $x.' '.$y; // "hello world" ```
Extension methods in Python
514,068
23
2009-02-05T00:47:37Z
514,081
7
2009-02-05T00:53:57Z
[ "python", "function", "extension-methods" ]
Does Python have extension methods like C#? Is it possible to call a method like: ``` MyRandomMethod() ``` on existing types like `int`? ``` myInt.MyRandomMethod() ```
not sure if that what you're asking but you can extend existing types and then call whatever you like on the new thing: ``` class int(int): def random_method(self): return 4 # guaranteed to be random v = int(5) # you'll have to instantiate all you variables like this v.random_method() class int(int): def xkcd(self): import antigravity print(42) >>>v.xkcd() Traceback (most recent call last): File "<pyshell#81>", line 1, in <module> v.xkcd() AttributeError: 'int' object has no attribute 'xkcd' c = int(1) >>> c.random_method() 4 >>> c.xkcd() 42 ``` hope that clarifies your question
Extension methods in Python
514,068
23
2009-02-05T00:47:37Z
514,101
32
2009-02-05T00:59:31Z
[ "python", "function", "extension-methods" ]
Does Python have extension methods like C#? Is it possible to call a method like: ``` MyRandomMethod() ``` on existing types like `int`? ``` myInt.MyRandomMethod() ```
You can add whatever methods you like on class objects defined in Python code (AKA monkey patching): ``` >>> class A(object): >>> pass >>> def stuff(self): >>> print self >>> A.test = stuff >>> A().test() ``` This does not work on builtin types, because their `__dict__` is not writable (it's a `dictproxy`). So no, there is no "real" extension method mechanism in Python.
What's the bad magic number error?
514,371
140
2009-02-05T02:59:47Z
514,395
174
2009-02-05T03:09:40Z
[ "python" ]
What's the "Bad magic number" ImportError in python, and how do I fix it? The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why. The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps: ``` Traceback (most recent call last): File "run.py", line 7, in <module> from Normalization import Normalizer ```
The magic number comes from UNIX-type systems where the first few bytes of a file held a marker indicating the file type. Python puts a similar marker into its `pyc` files when it creates them. Then the python interpreter makes sure this number is correct when loading it. Anything that damages this magic number will cause your problem. This includes editing the `pyc` file or trying to run a `pyc` from a different version of python (usually later) than your interpreter. If they are *your* `pyc` files, just delete them and let the interpreter re-compile the `py` files. On UNIX type systems, that could be something as simple as: ``` rm *.pyc ``` or: ``` find . -name '*.pyc' -delete ``` If they are not yours, you'll have to either get the `py` files for re-compilation, or an interpreter that can run the `pyc` files with that particular magic value. One thing that might be causing the intermittent nature. The `pyc` that's causing the problem may only be imported under certain conditions. It's highly unlikely it would import sometimes. You should check the actual full stack trace when the import fails? As an aside, the first word of all my `2.5.1(r251:54863)` `pyc` files is `62131`, `2.6.1(r261:67517)` is `62161`. The list of all magic numbers can be found in `Python/import.c`, reproduced here for completeness (current as at the time the answer was posted, it may have changed since then): ``` 1.5: 20121 1.5.1: 20121 1.5.2: 20121 1.6: 50428 2.0: 50823 2.0.1: 50823 2.1: 60202 2.1.1: 60202 2.1.2: 60202 2.2: 60717 2.3a0: 62011 2.3a0: 62021 2.3a0: 62011 2.4a0: 62041 2.4a3: 62051 2.4b1: 62061 2.5a0: 62071 2.5a0: 62081 2.5a0: 62091 2.5a0: 62092 2.5b3: 62101 2.5b3: 62111 2.5c1: 62121 2.5c2: 62131 2.6a0: 62151 2.6a1: 62161 2.7a0: 62171 ```
What's the bad magic number error?
514,371
140
2009-02-05T02:59:47Z
2,905,435
28
2010-05-25T14:12:02Z
[ "python" ]
What's the "Bad magic number" ImportError in python, and how do I fix it? The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why. The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps: ``` Traceback (most recent call last): File "run.py", line 7, in <module> from Normalization import Normalizer ```
Deleting all .pyc files will fix "Bad Magic Number" error. ``` find . -name "*.pyc" -delete ```
What's the bad magic number error?
514,371
140
2009-02-05T02:59:47Z
4,854,784
10
2011-01-31T18:52:09Z
[ "python" ]
What's the "Bad magic number" ImportError in python, and how do I fix it? The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure why. The information python's providing in the traceback isn't particularly helpful (which is why I was asking here...), but here it is in case it helps: ``` Traceback (most recent call last): File "run.py", line 7, in <module> from Normalization import Normalizer ```
Loading a python3 generated \*.pyc file with python2 also causes this error
Python: loop over consecutive characters?
514,448
8
2009-02-05T03:41:31Z
514,466
31
2009-02-05T03:47:46Z
[ "python", "algorithm", "python-3.x", "character" ]
In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode: ``` for Ch from 'a' to 'z' inclusive: # f(Ch) ``` Example: how about a nice "pythonic" version of the following? ``` def Pangram(Str): ''' Returns True if Str contains the whole alphabet, else False ''' for Ch from 'a' to 'z' inclusive: # M[Ch] = False for J in range(len(Str)): Ch = lower(Str[J]) if 'a' <= Ch <= 'z': M[Ch] = True return reduce(and, M['a'] to M['z'] inclusive) # ``` The lines marked # are pseudocode. Of course reduce() is real Python! Dear wizards (specially old, gray-bearded wizards), perhaps you can tell that my favorite language used to be Pascal.
You have a constant in the string module called `ascii_lowercase`, try that out: ``` >>> from string import ascii_lowercase ``` Then you can iterate over the characters in that string. ``` >>> for i in ascii_lowercase : ... f(i) ``` For your pangram question, there is a very simple way to find out if a string contains all the letters of the alphabet. Using ascii\_lowercase as before, ``` >>> def pangram(str) : ... return set(ascii_lowercase).issubset(set(str)) ```
Python: loop over consecutive characters?
514,448
8
2009-02-05T03:41:31Z
514,517
8
2009-02-05T04:04:39Z
[ "python", "algorithm", "python-3.x", "character" ]
In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode: ``` for Ch from 'a' to 'z' inclusive: # f(Ch) ``` Example: how about a nice "pythonic" version of the following? ``` def Pangram(Str): ''' Returns True if Str contains the whole alphabet, else False ''' for Ch from 'a' to 'z' inclusive: # M[Ch] = False for J in range(len(Str)): Ch = lower(Str[J]) if 'a' <= Ch <= 'z': M[Ch] = True return reduce(and, M['a'] to M['z'] inclusive) # ``` The lines marked # are pseudocode. Of course reduce() is real Python! Dear wizards (specially old, gray-bearded wizards), perhaps you can tell that my favorite language used to be Pascal.
Iterating a constant with all the characters you need is very Pythonic. However if you don't want to import anything and are only working in Unicode, use the built-ins ord() and its inverse chr(). ``` for code in range(ord('a'), ord('z') + 1): print chr(code) ```
Most pythonic way to extend a potentially incomplete list
516,039
6
2009-02-05T14:11:32Z
516,129
7
2009-02-05T14:31:59Z
[ "python" ]
What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too. An example transformation would be ``` ['a','b',None,'c'] ``` to ``` ['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9'] ``` My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well: ``` def extendChoices(cList): for i in range(0,9): try: if cList[i] is None: cList[i] = "Choice %d"%(i+1) except IndexError: cList.append("Choice %d"%(i+1) ``` and ``` def extendChoices(cList): # Fill in any blank entries for i, v in enumerate(cList): cList[i] = v or "Choice %s" % (i+1) # Extend the list to 9 choices for j in range(len(cList)+1, 10): cList.append("Choice %s" % (j)) ``` I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.
My initial reaction was to split the list extension and "filling in the blanks" into separate parts as so: ``` for i, v in enumerate(my_list): my_list[i] = v or "Choice %s" % (i+1) for j in range(len(my_list)+1, 10): my_list.append("Choice %s" % (j)) # maybe this is nicer for the extension? while len(my_list) < 10: my_list.append("Choice %s" % (len(my_list)+1)) ``` If you do stick with the `try...except` approach, do catch a specific exception as [Douglas](http://stackoverflow.com/questions/516039/most-pythonic-way-to-extend-a-potentially-incomplete-list/516070#516070) shows. Otherwise, you'll catch **everything**: `KeyboardInterrupts`, `RuntimeErrors`, `SyntaxErrors`, ... . You do not want to do that. **EDIT:** fixed 1-indexed list error - thanks [DNS](http://stackoverflow.com/users/51025/dns)! **EDIT:** added alternative list extension
Most pythonic way to extend a potentially incomplete list
516,039
6
2009-02-05T14:11:32Z
516,491
8
2009-02-05T15:54:23Z
[ "python" ]
What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too. An example transformation would be ``` ['a','b',None,'c'] ``` to ``` ['a','b','Choice 3','c','Choice 5','Choice 6','Choice 7','Choice 8','Choice 9'] ``` My initial code abused try/except and had an off-by-one error I didn't notice; thanks to joeforker and everyone who pointed it out. Based on the comments I tried two short solutions that test equally well: ``` def extendChoices(cList): for i in range(0,9): try: if cList[i] is None: cList[i] = "Choice %d"%(i+1) except IndexError: cList.append("Choice %d"%(i+1) ``` and ``` def extendChoices(cList): # Fill in any blank entries for i, v in enumerate(cList): cList[i] = v or "Choice %s" % (i+1) # Extend the list to 9 choices for j in range(len(cList)+1, 10): cList.append("Choice %s" % (j)) ``` I think #2 wins as being more pythonic, so it's the one I'll use. It's easy to understand and uses common constructs. Splitting the steps is logical and would make it easier for someone to understand at a glance.
Unlike `zip`, Python's `map` automatically extends shorter sequences with `None`. ``` map(lambda a, b: b if a is None else a, choicesTxt, ['Choice %i' % n for n in range(1, 10)]) ``` You could simplify the lambda to ``` map(lambda a, b: a or b, choicesTxt, ['Choice %i' % n for n in range(1, 10)]) ``` if it's okay to treat other false-like objects in `choicesTxt` the same as `None`.
Python regex: Turn "ThisFileName.txt" into "This File Name.txt"
516,451
2
2009-02-05T15:46:33Z
516,486
9
2009-02-05T15:53:24Z
[ "python", "regex" ]
I'm trying to add a space before every capital letter, except the first one. Here's what I have so far, and the output I'm getting: ``` >>> tex = "ThisFileName.txt" >>> re.sub('[A-Z].', ' ', tex) ' his ile ame.txt' ``` I want: 'This File Name.txt' (It'd be nice if I could also get rid of .txt, but I can do that in a separate operation.)
Key concept here is backreferences in regular expressions: ``` import re text = "ThisFileName.txt" print re.sub('([a-z])([A-Z])', r'\1 \2', text) # Prints: "This File Name.txt" ``` For pulling off the '.txt' in a reliable way, I recommend `os.path.splitext()` ``` import os filename = "ThisFileName.txt" print os.path.splitext(filename) # Prints: ('ThisFileName', '.txt') ```
Is there a Vim equivalent to the Linux/Unix "fold" command?
516,501
6
2009-02-05T15:56:00Z
516,536
11
2009-02-05T16:02:09Z
[ "python", "vim", "formatting", "comments", "textwrapping" ]
I realize there's a way in Vim to hide/fold lines, but what I'm looking for is a way to select a block of text and have Vim wrap lines at or near column 80. Mostly I want to use this on comments in situations where I'm adding some text to an existing comment that pushes it over 80 characters. It would also be nice if it could insert the comment marker at the beginning of the line when it wraps too. Also I'd prefer the solution to not autowrap the entire file since I have a particular convention that I use when it comes to keeping my structured code under the 80 character line-length. This is mostly for Python code, but I'm also interested in learning the general solution to the problem in case I have to apply it to other types of text.
``` gq ``` It's controlled by the textwidth option, see `":help gq"` for more info. `gq` will work on the current line by default, but you can highlight a visual block with `Ctrl`+`V` and format multiple lines / paragraphs like that. `gqap` does the current "paragraph" of text.
return eats exception
517,060
13
2009-02-05T17:59:35Z
517,082
40
2009-02-05T18:03:39Z
[ "python", "exception", "return", "finally" ]
I found the following behavior at least *weird*: ``` def errors(): try: ErrorErrorError finally: return 10 print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined ``` The exception disappears when you use `return` inside a `finally` clause. Is that a bug? Is that documented anywhere? But the real question (and the answer I will mark as correct) is: What is the python developers' reason to allow that odd behavior?
> The exception disappears when you use `return` inside a `finally` clause. .. Is that documented anywhere? [It is:](http://docs.python.org/reference/compound_stmts.html#the-try-statement) > If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. **If the finally clause raises another exception or executes a return or break statement, the saved exception is lost.**
return eats exception
517,060
13
2009-02-05T17:59:35Z
525,967
23
2009-02-08T16:15:35Z
[ "python", "exception", "return", "finally" ]
I found the following behavior at least *weird*: ``` def errors(): try: ErrorErrorError finally: return 10 print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined ``` The exception disappears when you use `return` inside a `finally` clause. Is that a bug? Is that documented anywhere? But the real question (and the answer I will mark as correct) is: What is the python developers' reason to allow that odd behavior?
You asked about the Python developers' reasoning. I can't speak for them, but no other behavior makes sense. A function can either return a value, or it can raise an exception; it can't do both. The purpose of a "finally" clause is to provide cleanup code that is "guaranteed" to be run, regardless of exceptions. By putting a return statement in a finally clause, you have declared that you want to return a value, no matter what, regardless of exceptions. If Python behaved as you are asking and raised the exception, it would be breaking the contract of the "finally" clause (because it would fail to return the value you told it to return).
How do I write output in same place on the console?
517,127
82
2009-02-05T18:11:47Z
517,148
10
2009-02-05T18:14:06Z
[ "python", "console-output" ]
I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as: output: > Downloading File FooFile.txt [47%] I'm trying to avoid something like this: ``` Downloading File FooFile.txt [47%] Downloading File FooFile.txt [48%] Downloading File FooFile.txt [49%] ``` How should I go about doing this? --- **Duplicate**: <http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360>
Print the backspace character `\b` several times, and then overwrite the old number with the new number.
How do I write output in same place on the console?
517,127
82
2009-02-05T18:11:47Z
517,179
19
2009-02-05T18:19:09Z
[ "python", "console-output" ]
I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as: output: > Downloading File FooFile.txt [47%] I'm trying to avoid something like this: ``` Downloading File FooFile.txt [47%] Downloading File FooFile.txt [48%] Downloading File FooFile.txt [49%] ``` How should I go about doing this? --- **Duplicate**: <http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360>
Use a terminal-handling library like the [curses module](http://docs.python.org/library/curses.html): > The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.
How do I write output in same place on the console?
517,127
82
2009-02-05T18:11:47Z
517,207
142
2009-02-05T18:22:47Z
[ "python", "console-output" ]
I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as: output: > Downloading File FooFile.txt [47%] I'm trying to avoid something like this: ``` Downloading File FooFile.txt [47%] Downloading File FooFile.txt [48%] Downloading File FooFile.txt [49%] ``` How should I go about doing this? --- **Duplicate**: <http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360>
You can also use the carriage return: ``` sys.stdout.write("Download progress: %d%% \r" % (progress) ) sys.stdout.flush() ```
How do I write output in same place on the console?
517,127
82
2009-02-05T18:11:47Z
517,523
8
2009-02-05T19:29:23Z
[ "python", "console-output" ]
I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as: output: > Downloading File FooFile.txt [47%] I'm trying to avoid something like this: ``` Downloading File FooFile.txt [47%] Downloading File FooFile.txt [48%] Downloading File FooFile.txt [49%] ``` How should I go about doing this? --- **Duplicate**: <http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360>
I like the following: ``` print 'Downloading File FooFile.txt [%d%%]\r'%i, ``` Demo: ``` import time for i in range(100): time.sleep(0.1) print 'Downloading File FooFile.txt [%d%%]\r'%i, ```
How do I write output in same place on the console?
517,127
82
2009-02-05T18:11:47Z
7,975,759
7
2011-11-02T04:14:27Z
[ "python", "console-output" ]
I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as: output: > Downloading File FooFile.txt [47%] I'm trying to avoid something like this: ``` Downloading File FooFile.txt [47%] Downloading File FooFile.txt [48%] Downloading File FooFile.txt [49%] ``` How should I go about doing this? --- **Duplicate**: <http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360>
``` #kinda like the one above but better :P from __future__ import print_function from time import sleep for i in range(101): str1="Downloading File FooFile.txt [{}%]".format(i) back="\b"*len(str1) print(str1, end="") sleep(0.1) print(back, end="") ```
String formatting in Python
517,355
21
2009-02-05T18:53:29Z
517,372
16
2009-02-05T18:59:07Z
[ "python", "string", "formatting" ]
I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns: ``` [1, 2, 3] ``` How do I do this in Python?
You're looking for string formatting, which in python is based on the sprintf function in C. ``` print "[%s, %s, %s]" % (1, 2, 3) ``` For a complete reference look here: <http://docs.python.org/library/stdtypes.html#string-formatting>
String formatting in Python
517,355
21
2009-02-05T18:53:29Z
517,471
53
2009-02-05T19:16:29Z
[ "python", "string", "formatting" ]
I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns: ``` [1, 2, 3] ``` How do I do this in Python?
The previous answers have used % formatting, which is being phased out in Python 3.0+. Assuming you're using Python 2.6+, a more future-proof formatting system is described here: <http://docs.python.org/library/string.html#formatstrings> Although there are more advanced features as well, the simplest form ends up looking very close to what you wrote: ``` >>> "[{0}, {1}, {2}]".format(1, 2, 3) [1, 2, 3] ```
String formatting in Python
517,355
21
2009-02-05T18:53:29Z
628,974
25
2009-03-10T04:54:35Z
[ "python", "string", "formatting" ]
I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns: ``` [1, 2, 3] ``` How do I do this in Python?
You can do it three ways: --- Use Python's automatic pretty printing: ``` print [1, 2, 3] # Prints [1, 2, 3] ``` Showing the same thing with a variable: ``` numberList = [1, 2] numberList.append(3) print numberList # Prints [1, 2, 3] ``` --- Use 'classic' string substitutions (ala C's printf). Note the different meanings here of % as the string-format specifier, and the % to apply the list (actually a tuple) to the formatting string. (And note the % is used as the modulo(remainder) operator for arithmetic expressions.) ``` print "[%i, %i, %i]" % (1, 2, 3) ``` Note if we use our pre-defined variable, we'll need to turn it into a tuple to do this: ``` print "[%i, %i, %i]" % tuple(numberList) ``` --- Use Python 3 string formatting. This is still available in earlier versions (from 2.6), but is the 'new' way of doing it in Py 3. Note you can either use positional (ordinal) arguments, or named arguments (for the heck of it I've put them in reverse order. ``` print "[{0}, {1}, {2}]".format(1, 2, 3) ``` Note the names 'one' ,'two' and 'three' can be whatever makes sense.) ``` print "[{one}, {two}, {three}]".format(three=3, two=2, one=1) ```
What is the best way to remove accents in a Python unicode string?
517,923
230
2009-02-05T21:10:40Z
517,974
83
2009-02-05T21:19:34Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
I have a Unicode string in Python, and I would like to remove all the accents (diacritics). I found on the Web an elegant way to do this in Java: 1. convert the Unicode string to its long normalized form (with a separate character for letters and diacritics) 2. remove all the characters whose Unicode type is "diacritic". Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3? Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.
I just found this answer on the Web: ``` import unicodedata def remove_accents(input_str): nfkd_form = unicodedata.normalize('NFKD', input_str) only_ascii = nfkd_form.encode('ASCII', 'ignore') return only_ascii ``` It works fine (for French, for example), but I think the second step (removing the accents) could be handled better than dropping the non-ASCII characters, because this will fail for some languages (Greek, for example). The best solution would probably be to explicitly remove the unicode characters that are tagged as being diacritics. **Edit**: this does the trick: ``` import unicodedata def remove_accents(input_str): nfkd_form = unicodedata.normalize('NFKD', input_str) return u"".join([c for c in nfkd_form if not unicodedata.combining(c)]) ``` `unicodedata.combining(c)` will return true if the character `c` can be combined with the preceding character, that is mainly if it's a diacritic. **Edit 2**: `remove_accents` expects a *unicode* string, not a byte string. If you have a byte string, then you must decode it into a unicode string like this: ``` encoding = "utf-8" # or iso-8859-15, or cp1252, or whatever encoding you use byte_string = b"café" # or simply "café" before python 3. unicode_string = byte_string.decode(encoding) ```
What is the best way to remove accents in a Python unicode string?
517,923
230
2009-02-05T21:10:40Z
518,232
164
2009-02-05T22:17:22Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
I have a Unicode string in Python, and I would like to remove all the accents (diacritics). I found on the Web an elegant way to do this in Java: 1. convert the Unicode string to its long normalized form (with a separate character for letters and diacritics) 2. remove all the characters whose Unicode type is "diacritic". Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3? Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.
How about this: ``` import unicodedata def strip_accents(s): return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') ``` This works on greek letters, too: ``` >>> strip_accents(u"A \u00c0 \u0394 \u038E") u'A A \u0394 \u03a5' >>> ``` The [character category](http://www.unicode.org/reports/tr44/#GC_Values_Table) "Mn" stands for `Nonspacing_Mark`, which is similar to unicodedata.combining in MiniQuark's answer (I didn't think of unicodedata.combining, but it is probably the better solution, because it's more explicit). And keep in mind, these manipulations may significantly alter the meaning of the text. Accents, Umlauts etc. are not "decoration".
What is the best way to remove accents in a Python unicode string?
517,923
230
2009-02-05T21:10:40Z
2,633,310
155
2010-04-13T21:21:14Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
I have a Unicode string in Python, and I would like to remove all the accents (diacritics). I found on the Web an elegant way to do this in Java: 1. convert the Unicode string to its long normalized form (with a separate character for letters and diacritics) 2. remove all the characters whose Unicode type is "diacritic". Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3? Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.
[Unidecode](https://pypi.python.org/pypi/Unidecode) is the correct answer for this. It transliterates any unicode string into the closest possible representation in ascii text.
What is the best way to remove accents in a Python unicode string?
517,923
230
2009-02-05T21:10:40Z
15,547,803
9
2013-03-21T12:39:18Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
I have a Unicode string in Python, and I would like to remove all the accents (diacritics). I found on the Web an elegant way to do this in Java: 1. convert the Unicode string to its long normalized form (with a separate character for letters and diacritics) 2. remove all the characters whose Unicode type is "diacritic". Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3? Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.
This handles not only accents, but also "strokes" (as in ø etc.): ``` import unicodedata as ud def rmdiacritics(char): ''' Return the base character of char, by "removing" any diacritics like accents or curls and strokes and the like. ''' desc = ud.name(unicode(char)) cutoff = desc.find(' WITH ') if cutoff != -1: desc = desc[:cutoff] return ud.lookup(desc) ``` This is the most elegant way I can think of (and it has been mentioned by alexis in a comment on this page), although I don't think it is very elegant indeed. There are still special letters that are not handled by this, such as turned and inverted letters, since their unicode name does not contain 'WITH'. It depends on what you want to do anyway. I sometimes needed accent stripping for achieving dictionary sort order.
What is the best way to remove accents in a Python unicode string?
517,923
230
2009-02-05T21:10:40Z
17,069,876
8
2013-06-12T15:48:48Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
I have a Unicode string in Python, and I would like to remove all the accents (diacritics). I found on the Web an elegant way to do this in Java: 1. convert the Unicode string to its long normalized form (with a separate character for letters and diacritics) 2. remove all the characters whose Unicode type is "diacritic". Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3? Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.
In response to @MiniQuark's answer: I was trying to read in a csv file that was half-French (containing accents) and also some strings which would eventually become integers and floats. As a test, I created a `test.txt` file that looked like this: > Montréal, über, 12.89, Mère, Françoise, noël, 889 I had to include lines `2` and `3` to get it to work (which I found in a python ticket), as well as incorporate @Jabba's comment: ``` import sys reload(sys) sys.setdefaultencoding("utf-8") import csv import unicodedata def remove_accents(input_str): nkfd_form = unicodedata.normalize('NFKD', unicode(input_str)) return u"".join([c for c in nkfd_form if not unicodedata.combining(c)]) with open('test.txt') as f: read = csv.reader(f) for row in read: for element in row: print remove_accents(element) ``` The result: ``` Montreal uber 12.89 Mere Francoise noel 889 ``` (Note: I am on Mac OS X 10.8.4 and using Python 2.7.3)
How to clear python interpreter console?
517,970
169
2009-02-05T21:19:20Z
517,992
56
2009-02-05T21:22:43Z
[ "windows", "console", "clear", "python" ]
Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling `cls` on Windows or `clear` on Linux, but I was hoping there was something I could command the interpreter itself to do. **Note:** I'm running on Windows, so Ctrl+L doesn't work.
Well, here's a quick hack: ``` >>> clear = "\n" * 100 >>> print clear >>> ...do some other stuff... >>> print clear ``` Or to save some typing, put this file in your python search path: ``` # wiper.py class Wipe(object): def __repr__(self): return '\n'*1000 wipe = Wipe() ``` Then you can do this from the interpreter all you like :) ``` >>> from wiper import wipe >>> wipe >>> wipe >>> wipe ```
How to clear python interpreter console?
517,970
169
2009-02-05T21:19:20Z
518,007
218
2009-02-05T21:25:08Z
[ "windows", "console", "clear", "python" ]
Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling `cls` on Windows or `clear` on Linux, but I was hoping there was something I could command the interpreter itself to do. **Note:** I'm running on Windows, so Ctrl+L doesn't work.
As you mentioned, you can do a system call: ``` >>> import os >>> clear = lambda: os.system('cls') >>> clear() ``` I am not sure of any other way in Windows.
How to clear python interpreter console?
517,970
169
2009-02-05T21:19:20Z
684,344
111
2009-03-26T02:42:42Z
[ "windows", "console", "clear", "python" ]
Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling `cls` on Windows or `clear` on Linux, but I was hoping there was something I could command the interpreter itself to do. **Note:** I'm running on Windows, so Ctrl+L doesn't work.
here something handy that is a little more cross-platform ``` import os def cls(): os.system('cls' if os.name=='nt' else 'clear') # now, to clear the screen cls() ```
How to clear python interpreter console?
517,970
169
2009-02-05T21:19:20Z
3,917,856
22
2010-10-12T18:36:11Z
[ "windows", "console", "clear", "python" ]
Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling `cls` on Windows or `clear` on Linux, but I was hoping there was something I could command the interpreter itself to do. **Note:** I'm running on Windows, so Ctrl+L doesn't work.
Although this is an older question, I thought I'd contribute something summing up what I think were the best of the other answers and add a wrinkle of my own by suggesting that you put these command(s) into a file and set your PYTHONSTARTUP environment variable to point to it. Since I'm on Windows at the moment, it's slightly biased that way, but could easily be slanted some other direction. Here's some articles I found that describe how to set environment variables on Windows:     [When to use sys.path.append and when modifying %PYTHONPATH% is enough](http://stackoverflow.com/a/4209102/355230)     [How To Manage Environment Variables in Windows XP](http://support.microsoft.com/kb/310519)     [Configuring System and User Environment Variables](http://technet.microsoft.com/en-us/library/bb726962.aspx)     [How to Use Global System Environment Variables in Windows](http://www.howtogeek.com/51807/how-to-create-and-use-global-system-environment-variables/) BTW, don't put quotes around the path to the file even if it has spaces in it. Anyway, here's my take on the code to put in (or add to your existing) Python startup script: ``` # ==== pythonstartup.py ==== # add something to clear the screen class cls(object): def __repr__(self): import os os.system('cls' if os.name == 'nt' else 'clear') return '' cls = cls() # ==== end pythonstartup.py ==== ``` BTW, you can also use @[Triptych's](http://stackoverflow.com/questions/517970/how-to-clear-python-interpreter-console/517992#517992) `__repr__` trick to change `exit()` into just `exit` (and ditto for its alias `quit`): ``` class exit(object): exit = exit # original object def __repr__(self): self.exit() # call original return '' quit = exit = exit() ``` Lastly, here's something else that changes the primary interpreter prompt from `>>>` to *cwd*+`>>>`: ``` class Prompt: def __str__(self): import os return '%s >>> ' % os.getcwd() import sys sys.ps1 = Prompt() del sys del Prompt ```
Getting the length of an array in Python
518,021
400
2009-02-05T21:26:47Z
518,038
718
2009-02-05T21:29:48Z
[ "python", "arrays" ]
In [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), is the following the only way to get the number of elements? ``` arr.__len__() ``` If so, why the strange syntax?
``` my_list = [1,2,3,4,5] len(my_list) ``` The same works for tuples: ``` my_tuple = (1,2,3,4,5) len(my_tuple) ``` And strings, which are really just arrays of characters: ``` my_string = 'hello world' len(my_string) ``` It was [intentionally done this way](http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm) so that lists, tuples and other container types didn't all need to explicitly implement a public `.length()` method, instead you can just check the `len()` of anything that implements the 'magic' `__len__()` method. Sure, this may seem redundant, but length checking implementations can vary considerably, even within the same language. It's not uncommon to see one collection type use a `.length()` method while another type uses a `.length` property, while yet another uses `.count()`. Having a language-level keyword unifies the entry point for all these types. So even objects you may not consider to be lists of elements could still be length-checked. This includes strings, queues, trees, etc.
Getting the length of an array in Python
518,021
400
2009-02-05T21:26:47Z
518,039
13
2009-02-05T21:30:05Z
[ "python", "arrays" ]
In [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), is the following the only way to get the number of elements? ``` arr.__len__() ``` If so, why the strange syntax?
Just use len(arr): ``` >>> import array >>> arr = array.array('i') >>> arr.append('2') >>> arr.__len__() 1 >>> len(arr) 1 ```
Getting the length of an array in Python
518,021
400
2009-02-05T21:26:47Z
518,053
19
2009-02-05T21:32:43Z
[ "python", "arrays" ]
In [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), is the following the only way to get the number of elements? ``` arr.__len__() ``` If so, why the strange syntax?
The preferred way to get the length of any python object is to pass it as an argument to the `len` function. Internally, python will then try to call the special `__len__` method of the object that was passed.
Getting the length of an array in Python
518,021
400
2009-02-05T21:26:47Z
518,061
32
2009-02-05T21:34:00Z
[ "python", "arrays" ]
In [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), is the following the only way to get the number of elements? ``` arr.__len__() ``` If so, why the strange syntax?
The way you take a length of anything for which that makes sense (a list, dictionary, tuple, string, ...) is to call `len` on it. ``` l = [1,2,3,4] s = 'abcde' len(l) #returns 4 len(s) #returns 5 ``` The reason for the "strange" syntax is that internally python translates `len(object)` into `object.__len__()`. This applies to any object. So, if you are defining some class and it makes sense for it to have a length, just define a `__len__()` method on it and then one can call `len` on those instances.
Getting the length of an array in Python
518,021
400
2009-02-05T21:26:47Z
519,644
18
2009-02-06T09:15:37Z
[ "python", "arrays" ]
In [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), is the following the only way to get the number of elements? ``` arr.__len__() ``` If so, why the strange syntax?
Python uses [duck typing](http://en.wikipedia.org/wiki/Duck_typing): it doesn't care about what an object *is*, as long as it has the appropriate interface for the situation at hand. When you call the built-in function len() on an object, you are actually calling its internal \_\_len\_\_ method. A custom object can implement this interface and len() will return the answer, even if the object is not conceptually a sequence. For a complete list of interfaces, have a look here: <http://docs.python.org/reference/datamodel.html#basic-customization>
Lazy Method for Reading Big File in Python?
519,633
156
2009-02-06T09:11:13Z
519,653
231
2009-02-06T09:20:08Z
[ "python", "file-io", "generator" ]
I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece. Is there any method to `yield` these pieces ? I would love to have a **lazy method**.
To write a lazy function, just use [`yield`](http://docs.python.org/tutorial/classes.html#generators): ``` def read_in_chunks(file_object, chunk_size=1024): """Lazy function (generator) to read a file piece by piece. Default chunk size: 1k.""" while True: data = file_object.read(chunk_size) if not data: break yield data f = open('really_big_file.dat') for piece in read_in_chunks(f): process_data(piece) ``` --- Another option would be to use [`iter`](http://docs.python.org/library/functions.html#iter) and a helper function: ``` f = open('really_big_file.dat') def read1k(): return f.read(1024) for piece in iter(read1k, ''): process_data(piece) ``` --- If the file is line-based, the file object is already a lazy generator of lines: ``` for line in open('really_big_file.dat'): process_data(line) ```
Lazy Method for Reading Big File in Python?
519,633
156
2009-02-06T09:11:13Z
519,667
18
2009-02-06T09:28:12Z
[ "python", "file-io", "generator" ]
I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece. Is there any method to `yield` these pieces ? I would love to have a **lazy method**.
Take a look at [this post on Neopythonic](http://neopythonic.blogspot.com/2008/10/sorting-million-32-bit-integers-in-2mb.html): "Sorting a million 32-bit integers in 2MB of RAM using Python"
Lazy Method for Reading Big File in Python?
519,633
156
2009-02-06T09:11:13Z
519,693
20
2009-02-06T09:41:29Z
[ "python", "file-io", "generator" ]
I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece. Is there any method to `yield` these pieces ? I would love to have a **lazy method**.
You can use the [mmap module](http://docs.python.org/library/mmap.html) to map the contents of the file into memory and access it with indices and slices. Here an example from the documentation: ``` import mmap with open("hello.txt", "r+") as f: # memory-map the file, size 0 means whole file map = mmap.mmap(f.fileno(), 0) # read content via standard file methods print map.readline() # prints "Hello Python!" # read content via slice notation print map[:5] # prints "Hello" # update content using slice notation; # note that new content must have same size map[6:] = " world!\n" # ... and read again using standard file methods map.seek(0) print map.readline() # prints "Hello world!" # close the map map.close() ```
Lazy Method for Reading Big File in Python?
519,633
156
2009-02-06T09:11:13Z
2,111,801
18
2010-01-21T18:27:59Z
[ "python", "file-io", "generator" ]
I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece. Is there any method to `yield` these pieces ? I would love to have a **lazy method**.
file.readlines() takes in an optional size argument which approximates the number of lines read in the lines returned. ``` bigfile = open('bigfilename','r') tmp_lines = bigfile.readlines(BUF_SIZE) while tmp_lines: process([line for line in tmp_lines]) tmp_lines = bigfile.readlines(BUF_SIZE) ```
Is there a HAML implementation for use with Python and Django
519,671
68
2009-02-06T09:30:01Z
519,679
21
2009-02-06T09:36:46Z
[ "python", "django", "django-templates", "haml" ]
I happened to stumble across [HAML](http://haml-lang.com/), an interesting and beautiful way to mark up contents and write templates for HTML. Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.
I'd check out [GHRML](https://github.com/derdon/ghrml), Haml for Genshi. The author admits that it's basically Haml for Python and that most of the syntax is the same (and that it works in Django). Here's some GHRML just to show you how close they are: ``` %html %head %title Hello World %style{'type': 'text/css'} body { font-family: sans-serif; } %script{'type': 'text/javascript', 'src': 'foo.js'} %body #header %h1 Hello World %ul.navigation %li[for item in navigation] %a{'href': item.href} $item.caption #contents Hello World! ```
Is there a HAML implementation for use with Python and Django
519,671
68
2009-02-06T09:30:01Z
1,934,207
35
2009-12-19T21:33:50Z
[ "python", "django", "django-templates", "haml" ]
I happened to stumble across [HAML](http://haml-lang.com/), an interesting and beautiful way to mark up contents and write templates for HTML. Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.
You might be interested in SHPAML: <http://shpaml.com/> I am actively maintaining it. It is a simple preprocessor, so it is not tied to any other tools like Genshi. I happen to use it with Django, so there is a little bit of Django support, but it should not interfere with most other use cases.
Is there a HAML implementation for use with Python and Django
519,671
68
2009-02-06T09:30:01Z
3,324,983
18
2010-07-24T11:56:45Z
[ "python", "django", "django-templates", "haml" ]
I happened to stumble across [HAML](http://haml-lang.com/), an interesting and beautiful way to mark up contents and write templates for HTML. Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.
i'm looking for the same. I haven't tried it, but found this: <http://github.com/jessemiller/HamlPy>
Cross-platform gui toolkit for deploying Python applications
520,015
45
2009-02-06T11:43:30Z
520,055
42
2009-02-06T12:06:10Z
[ "python", "user-interface", "cross-platform" ]
Building on: <http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/> # Merits: 1 - ease of design / integration - learning curve 2 - support / availability for \*nix, Windows, Mac, extra points for native l&f, support for mobile or web 3 - pythonic API 4 - quality of documentation - I want to do something a bit more complicated, now what? 5 - light weight packaging so it's not necessary to include a full installer (py2exe, py2app would ideally work as-is and not generate a gazillion MBs file) 6 - licensing 7 - others? (specify) --- # Contenders: 1 - tkinter, as currently supported (as of 2.6, 3.0) 2 - pyttk library 3 - pyGTK 4 - pyQt 5 - wxPython 6 - HTML-CGI via Python-based framework (Django, Turbogears, web.py, Pylons...) or Paste 7 - others? (specify)
Please don't hesitate to expand this answer. # [Tkinter](http://wiki.python.org/moin/TkInter) Tkinter is the toolkit that comes with python. That means you already have everything you need to write a GUI. What that also means is that if you choose to distribute your program, most likely everyone else already has what they need to run your program. Tkinter is mature and stable, and is (at least arguably) quite easy to use.I found it easier to use than wxPython, but obviously that's somewhat subjective. Tkinter gets a bad rap for looking ugly and out of date. While it's true that it's easy to create ugly GUIs with Tkinter, it's also pretty easy to create nice looking GUIs. Tkinter doesn't hold your hand, but it doesn't much get in the way, either. Tkinter looks best on the Mac and Windows since it uses native widgets there, but it looks OK on linux, too. The other point about the look of Tkinter is that, for the most part, look isn't as important as people make it out to be. Most applications written with toolkits such as Tkinter, wxPython, PyQT, etc are special-purpose applications. For the types of applications these toolkits are used for, usability trumps looks. If the look of the application is important, it's easy enough to polish up a Tkinter application. Tkinter has some features that other toolkits don't come close to matching. Variable traces, named fonts, geometry (layout) managers, and the way Tkinter processes events are still the standard to which other toolkits should be judged. On the downside, Tkinter is a wrapper around a Tcl interpreter that runs inside python. This is mostly invisible to anyone developing with Tkinter, but it sometimes results in error messages that expose this architecture. You'll get an error complaining about a widget with a name like ".1245485.67345" which will make almost no sense to anyone unless you're also familiar with how Tcl/tk works. Another downside is that Tkinter doesn't have as many pre-built widgets as wxPython. The hierarchical tree widget in Tkinter is a little weak, for example, and there's no built-in table widget. On the other hand, Tkinter's canvas and text widgets are extremely powerful and easy to use. For most types of applications you will write, however, you'll have everything you need. Just don't expect to replicate Microsoft Word or Photoshop with Tkinter. I don't know what the license is for Tkinter, I assume the same as for python as a whole. Tcl/tk has a BSD-style license. # [PyQt](http://www.riverbankcomputing.co.uk/software/pyqt/intro) It's build on top of [Qt](http://qt.nokia.com/), a C++ framework. It's quite advanced and has some good tools like the Qt Designer to design your applications. You should be aware though, that it doesn't feel like Python 100%, but close to it. The [documentation](http://doc.qt.nokia.com/4.5/index.html) is excellent This framework is really good. It's being actively developed by Trolltech, who is owned by Nokia. The bindings for Python are developed by Riverbank. PyQt is available under the GPL license or a commercial one. The price of a riverbank PyQt license is about 400 euro per developer. Qt is not only a GUI-framework but has a lot of other classes too, one can create an application by just using Qt classes. (Like SQL, networking, scripting, …) Qt used to emulate GUI elements on every platform but now uses native styles of the platforms (although not native GUI toolkits): see [the documentation for Mac OS X](http://doc.qt.nokia.com/4.4/qtmac-as-native.html) and [the windows XP style](http://doc.qt.nokia.com/4.5/qwindowsxpstyle.html#details) Packaging is as simple as running py2exe or pyInstaller. The content of my PyQt app looks like this on windows (I have used InnoSetup on top of it for proper installation): ``` pyticroque.exe PyQt4.QtGui.pyd unicodedata.pyd MSVCP71.dll PyQt4._qt.pyd unins000.dat MSVCR71.dll python25.dll unins000.exe PyQt4.QtCore.pyd sip.pyd _socket.pyd ``` QT comes with a widget designer and even in recent versions with an [IDE](http://qt.nokia.com/products/developer-tools) to help design Qt software. # [PySide](http://pyside.org) PySide is a LGPL binding to Qt. It's developed by nokia as a replacement for the GPL PyQt. > Although based on a different > technology than the existing > GPL-licensed PyQt bindings, PySide > will initially aim to be > API-compatible with them. In addition > to the PyQt-compatible API, a more > Pythonic API will be provided in the > future. # [wxPython](http://www.wxpython.org/) wxPython is a binding for Python using the [wxWidgets](http://www.wxwidgets.org/)-Framework. This framework is under the LGPL licence and is developed by the open source community. What I'm really missing is a good tool to design the interface, they have about 3 but none of them is usable. One thing I should mention is that I found a bug in the tab-view despite the fact that I didn't use anything advanced. (Only on Mac OS X) I think [wxWidgets](http://www.wxwidgets.org/) isn't as polished as [Qt](http://qt.nokia.com/). wxPython is really only about the GUI-classes, there isn't much else. wxWidgets uses native GUI elements. An advantage wxPython has over Tkinter is that wxPython has a much larger library of widgets from which to choose from. # Others I haven't got any experience with other GUI frameworks, maybe someone else has.
What's the cleanest way to extract URLs from a string using Python?
520,031
18
2009-02-06T11:51:57Z
520,036
8
2009-02-06T11:54:44Z
[ "python", "regex", "url" ]
Although I know I could use some hugeass regex such as the one posted [here](http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx) I'm wondering if there is some tweaky as hell way to do this either with a standard module or perhaps some third-party add-on? Simple question, but nothing jumped out on Google (or Stackoverflow). Look forward to seeing how y'all do this!
Use a regular expression. Reply to comment from the OP: I know this is not helpful. I am telling you the correct way to solve the problem as you stated it is to use a regular expression.
What's the cleanest way to extract URLs from a string using Python?
520,031
18
2009-02-06T11:51:57Z
1,855,891
10
2009-12-06T17:03:32Z
[ "python", "regex", "url" ]
Although I know I could use some hugeass regex such as the one posted [here](http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx) I'm wondering if there is some tweaky as hell way to do this either with a standard module or perhaps some third-party add-on? Simple question, but nothing jumped out on Google (or Stackoverflow). Look forward to seeing how y'all do this!
Look at Django's approach here: [`django.utils.urlize()`](https://github.com/django/django/blob/98c5370ef673bc83deaf24c197e0bb22a75071e3/django/utils/html.py#L257). Regexps are too limited for the job and you have to use heuristics to get results that are mostly right.
Where is Python used? I read about it a lot on Reddit
520,210
8
2009-02-06T13:08:13Z
520,230
17
2009-02-06T13:12:56Z
[ "python" ]
I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India.
Everywhere. It's used [extensively by google](http://panela.blog-city.com/python_at_google_greg_stein__sdforum.htm) for one. See [list of python software](http://en.wikipedia.org/wiki/Python_software) for more info, and also [who uses python on the web?](http://www.python.org/doc/essays/ppt/www8-py-www/sld010.htm)
Where is Python used? I read about it a lot on Reddit
520,210
8
2009-02-06T13:08:13Z
520,247
10
2009-02-06T13:16:37Z
[ "python" ]
I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India.
In many large companies it is a primary scripting language. Google is using it along with Java and C++ and almost nothing else. Also many web pages are built on top of python and Django. Another place is game development. Many games have their engines written in C++ but all the logic in Python. In other words it is one of the most valuable tools. This might be of interest for you as well: * [Is Python good for big software projects (not web based)?](http://stackoverflow.com/questions/35753/is-python-good-for-big-software-projects-not-web-based) * [Are there any good reasons why I should not use Python?](http://stackoverflow.com/questions/371966/are-there-any-good-reasons-why-i-should-not-use-python) * [What did you use to teach yourself python?](http://stackoverflow.com/questions/111857/what-did-you-use-to-teach-yourself-python)
Event handling with Jython & Swing
520,615
8
2009-02-06T15:09:13Z
523,456
11
2009-02-07T08:35:51Z
[ "java", "python", "user-interface", "swing", "jython" ]
I'm making a GUI by using Swing from Jython. Event handling seems to be particularly elegant from Jython, just set ``` JButton("Push me", actionPerformed = nameOfFunctionToCall) ``` However, trying same thing inside a class gets difficult. Naively trying ``` JButton("Push me", actionPerformed = nameOfMethodToCall) ``` or ``` JButton("Push me", actionPerformed = nameOfMethodToCall(self)) ``` from a GUI-construction method of the class doesn't work, because the first argument of a method to be called should be *self*, in order to access the data members of the class, and on the other hand, it's not possible to pass any arguments to the event handler through AWT event queue. The only option seems to be using lambda (as advised at <http://www.javalobby.org/articles/jython/>) which results in something like this: ``` JButton("Push me", actionPerformed = lambda evt : ClassName.nameOfMethodToCall(self)) ``` It works, but the elegance is gone. All this just because the method being called needs a *self* reference from somewhere. Is there any other way around this?
``` JButton("Push me", actionPerformed=self.nameOfMethodToCall) ``` Here's a modified example from the article you cited: ``` from javax.swing import JButton, JFrame class MyFrame(JFrame): def __init__(self): JFrame.__init__(self, "Hello Jython") button = JButton("Hello", actionPerformed=self.hello) self.add(button) self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setSize(300, 300) self.show() def hello(self, event): print "Hello, world!" if __name__=="__main__": MyFrame() ```
Python loops with multiple lists?
521,321
15
2009-02-06T17:42:27Z
521,345
10
2009-02-06T17:46:38Z
[ "python", "arrays", "loops", "list" ]
**<edit>** Thanks to everyone who has answered so far. The zip and os.path.join are really helpful. Any suggestions on ways to list the counter in front, without doing something like this: ``` zip(range(len(files)), files, directories) ``` **</edit>** Hi, I'm in the process of learning Python, but I come from a background where the following pseudocode is typical: ``` directories = ['directory_0', 'directory_1', 'directory_2'] files = ['file_a', 'file_b', 'file_c'] for(i = 0; i < directories.length; i++) { print (i + 1) + '. ' + directories[i] + '/' + files[i] + '\n' } # Output: # 1. directory_0/file_a # 2. directory_1/file_b # 3. directory_2/file_c ``` In Python, the way I would write the above right now, would be like this: ``` directories = ['directory_0', 'directory_1', 'directory_2'] files = ['file_a', 'file_b', 'file_c'] for i in range(len(directories)): print '%s. %s/%s' % ((i + 1), directories[i], files[i] # Output: # 1. directory_0/file_a # 2. directory_1/file_b # 3. directory_2/file_c ``` While reading Dive into Python, Mark Pilgrim says that using for loops for counters is "Visual Basic-style thinking" ([Simple Counters](http://diveintopython.net/file_handling/for_loops.html#fileinfo.for.counter)). He goes on to show how to use loops with dictionaries, but never really addresses a python solution in regards to how for loop counters are typically used in other languages. I was hoping somebody could show me how to properly write the above scenario in Python. Is it possible to do it a different way? If I took out the incrementing line count, is it possible to just match the two lists together using some kind of list comprehension? For example, if all I wanted from the output was this (no counters, is that possible with list comprehension): ``` # Output: # directory_0/file_a # directory_1/file_b # directory_2/file_c ``` Thanks in advance for any help.
Try this: ``` directories = ['directory_0', 'directory_1', 'directory_2'] files = ['file_a', 'file_b', 'file_c'] for file, dir in zip(files, directories): print dir + '/' + file ``` To explain, the `zip()` function takes lists as input and returns a list of "zipped" tuples. so `zip([1,2,3,4,5],[a,b,c,d,e])` would return `[(1,a),(2,b)` and so on. You can then assign the members of the tuples to variables with the python `for <var> in <list>` syntax. There are a million different ways to do what you are asking, but the above uses some more "pythonic" constructs to make the code a lot more readable (IMHO, anyway).
Python loops with multiple lists?
521,321
15
2009-02-06T17:42:27Z
521,361
35
2009-02-06T17:49:07Z
[ "python", "arrays", "loops", "list" ]
**<edit>** Thanks to everyone who has answered so far. The zip and os.path.join are really helpful. Any suggestions on ways to list the counter in front, without doing something like this: ``` zip(range(len(files)), files, directories) ``` **</edit>** Hi, I'm in the process of learning Python, but I come from a background where the following pseudocode is typical: ``` directories = ['directory_0', 'directory_1', 'directory_2'] files = ['file_a', 'file_b', 'file_c'] for(i = 0; i < directories.length; i++) { print (i + 1) + '. ' + directories[i] + '/' + files[i] + '\n' } # Output: # 1. directory_0/file_a # 2. directory_1/file_b # 3. directory_2/file_c ``` In Python, the way I would write the above right now, would be like this: ``` directories = ['directory_0', 'directory_1', 'directory_2'] files = ['file_a', 'file_b', 'file_c'] for i in range(len(directories)): print '%s. %s/%s' % ((i + 1), directories[i], files[i] # Output: # 1. directory_0/file_a # 2. directory_1/file_b # 3. directory_2/file_c ``` While reading Dive into Python, Mark Pilgrim says that using for loops for counters is "Visual Basic-style thinking" ([Simple Counters](http://diveintopython.net/file_handling/for_loops.html#fileinfo.for.counter)). He goes on to show how to use loops with dictionaries, but never really addresses a python solution in regards to how for loop counters are typically used in other languages. I was hoping somebody could show me how to properly write the above scenario in Python. Is it possible to do it a different way? If I took out the incrementing line count, is it possible to just match the two lists together using some kind of list comprehension? For example, if all I wanted from the output was this (no counters, is that possible with list comprehension): ``` # Output: # directory_0/file_a # directory_1/file_b # directory_2/file_c ``` Thanks in advance for any help.
``` import os.path for dir, file in zip(directories, files): print(os.path.join(dir, file)) # for directories, files ``` you can have it as a list comprehension as well, creating list of string with print going after that] with counter: ``` for i, (dir, file) in enumerate(zip(directories, files)): print(i, os.path.join(dir, file)) ```
Why True/False is capitalized in Python?
521,476
34
2009-02-06T18:13:04Z
521,508
49
2009-02-06T18:20:10Z
[ "python", "camelcasing" ]
All members are camel case, right? Why True/False but not true/false, which is more relaxed?
From [Pep 285](http://www.python.org/dev/peps/pep-0285/): > Should the constants be called 'True' > and 'False' (similar to > None) or 'true' and 'false' (as in C++, Java and C99)? > > => True and False. > > Most reviewers agree that consistency within Python is more > important than consistency with other languages. This, as Andrew points out, is probably because [all (most)? built-in constants are capitalized](http://docs.python.org/library/constants.html).
Why True/False is capitalized in Python?
521,476
34
2009-02-06T18:13:04Z
521,515
10
2009-02-06T18:21:40Z
[ "python", "camelcasing" ]
All members are camel case, right? Why True/False but not true/false, which is more relaxed?
All of python's [built-in constants](http://docs.python.org/library/constants.html) are capitalized or [upper] CamelCase:
How do i get python's pprint to return a string instead of printing?
521,532
76
2009-02-06T18:25:53Z
521,545
123
2009-02-06T18:28:30Z
[ "python" ]
In other words, what's the sprintf equivalent to pprint?
The [pprint](http://docs.python.org/library/pprint.html) module has a command named [pformat](http://docs.python.org/library/pprint.html#pprint.pformat), for just that purpose. From the documentation: > Return the formatted representation of object as a string. indent, > width and depth will be passed to the PrettyPrinter constructor as > formatting parameters. Example: ``` >>> import pprint >>> people = [ ... {"first": "Brian", "last": "Kernighan"}, ... {"first": "Dennis", "last": "Richie"}, ... ] >>> pprint.pformat(people, indent=4) "[ { 'first': 'Brian', 'last': 'Kernighan'},\n { 'first': 'Dennis', 'last': 'Richie'}]" ```
How do i get python's pprint to return a string instead of printing?
521,532
76
2009-02-06T18:25:53Z
521,546
7
2009-02-06T18:29:14Z
[ "python" ]
In other words, what's the sprintf equivalent to pprint?
Are you looking for `pprint.pformat`?
How do i get python's pprint to return a string instead of printing?
521,532
76
2009-02-06T18:25:53Z
521,550
10
2009-02-06T18:29:47Z
[ "python" ]
In other words, what's the sprintf equivalent to pprint?
Assuming you really do mean `pprint` from the [pretty-print library](http://docs.python.org/library/pprint.html), then you want the `pprint.pformat` method. If you just mean `print`, then you want `str()`
How do i get python's pprint to return a string instead of printing?
521,532
76
2009-02-06T18:25:53Z
6,472,848
8
2011-06-24T19:30:38Z
[ "python" ]
In other words, what's the sprintf equivalent to pprint?
``` >>> import pprint >>> pprint.pformat({'key1':'val1', 'key2':[1,2]}) "{'key1': 'val1', 'key2': [1, 2]}" >>> ```
Is there a way to decode numerical COM error-codes in pywin32
521,759
24
2009-02-06T19:18:01Z
531,105
33
2009-02-10T05:01:04Z
[ "python", "windows", "excel", "com", "pywin32" ]
Here is part of a stack-trace from a recent run of an unreliable application written in Python which controls another application written in Excel: ``` pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None) ``` Obviously something has gone wrong ... but what?[1] These COM error codes seem to be excessively cryptic. How can I decode this error message? Is there a table somewhere that allows me to convert this numerical error code into something more meaningful? [1] I actually know what went wrong in this case, it was attempting to access a Name prperty on a Range object which did not have a Name property... not all bugs are this easy to find!
You are not doing anything wrong. The first item in your stack trace (the number) is the error code returned by the COM object. The second item is the description associated with the error code which in this case is "Exception Occurred". pywintypes.com\_error already called the equivalent of win32api.FormatMessage(errCode) for you. We'll look at the second number in a minute. *By the way, you can use the "Error Lookup" utility that comes in Visual Studio (C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\ErrLook.exe) as a quick launching pad to check COM error codes. That utility also calls FormatMessage for you and displays the result. Not all error codes will work with this mechanism, but many will. That's usually my first stop.* Error handling and reporting in COM is a bit messy. I'll try to give you some background. All COM method calls will return a numeric code called an HRESULT that can indicate success or failure. All forms of error reporting in COM build on top of that. The codes are commonly expressed in hex, although sometimes you will see them as large 32-bit numbers, like in your stack trace. There are all kinds of predefined return codes for common results and problems, or the object can return custom numeric codes for special situations. For example, the value 0 (called S\_OK) universally means "No error" and 0x80000002 is E\_OUTOFMEMORY. Sometimes the HRESULT codes are returned by the object, sometimes by the COM infrastructure. A COM object can also choose to provide much richer error information by implementing an interface called IErrorInfo. When an object implements IErrorInfo, it can provide all kinds of detail about what happened, such as a detailed custom error message and even the name of a help file that describes the problem. In VB6 and VBA. the `Err` object allows you to access all that information (`Err.Description`, etc). To complicate matters, late bound COM objects (which use a mechanism called COM Automation or IDispatch) add some layers that need to be peeled off to get information out. Excel is usually manipulated via late binding. Now let's look at your situation again. What you are getting as the first number is a fairly generic error code: DISP\_E\_EXCEPTION. *Note: you can usually figure out the official name of an HRESULT by googling the number, although sometimes you will have to use the hex version to find anything useful.* Errors that begin with DISP\_ are IDISPATCH error codes. The error loosely means "There was a COM exception thrown by the object", with more information packed elsewhere (although I don't quite know where; I'll have to look it up). From what I understand of pywintypes.com\_error, the last number in your message is the actual error code that was returned by the object during the exception. It's the actual numeric code that you would get out of VBA's `Err.Number`. Unfortunately, that second code -2146788248 (0x800A9C68) is in the range reserved for custom application-defined error messages (in VBA: `VbObjectError + someCustomErrorNumber`), so there is no centralized meaning. The same number can mean entirely different things for different programs. In this case, we have reached a dead end: > The error code is "custom", and the application needs to document what it is, except that Excel doesn't. Also, Excel (or the actual source of the error) doesn't seem to be providing any more information via IErrorInfo. Excel is notorious (to me at least) for cryptic error codes from automation and obscure situations that cause them. This is especially so for errors that one could consider "design-time errors" ("you should have known better than calling a method that doesn't exist in the object"). Instead of a nice "Could not read the Name property", you get "***Run-time error '1004': Application defined or object-defined error***" (which I just got by trying to access a Name property on a Range, from VBA in Excel). That is NOT very helpful. The problem is not routed on Python or it's interface to Excel. Excel itself doesn't explain what happened, even to VBA. However, the general procedure above remains valid. If you get an error from Excel in the future, you might get a better error message that you can track the same way. Good luck!
Finding first and last index of some value in a list in Python
522,372
23
2009-02-06T22:00:00Z
522,401
39
2009-02-06T22:05:06Z
[ "python", "list", "search" ]
Is there any built-in methods that are part of lists that would give me the first and last index of some value, like: ``` verts.IndexOf(12.345) verts.LastIndexOf(12.345) ```
Sequences have a method `index(value)` which returns index of first occurrence. You can run it on `verts[::-1]` to find out the last index.
Finding first and last index of some value in a list in Python
522,372
23
2009-02-06T22:00:00Z
6,194,807
10
2011-05-31T23:48:50Z
[ "python", "list", "search" ]
Is there any built-in methods that are part of lists that would give me the first and last index of some value, like: ``` verts.IndexOf(12.345) verts.LastIndexOf(12.345) ```
Use `i1 = yourlist.index(yourvalue)` and `i2 = yourlist.rindex(yourvalue).`
Finding first and last index of some value in a list in Python
522,372
23
2009-02-06T22:00:00Z
18,157,104
7
2013-08-09T23:23:39Z
[ "python", "list", "search" ]
Is there any built-in methods that are part of lists that would give me the first and last index of some value, like: ``` verts.IndexOf(12.345) verts.LastIndexOf(12.345) ```
if you are searching for the index of the last occurance of myvalue in mylist: ``` len(mylist) - mylist[::-1].index(myvalue) - 1 ```
Is there a way to loop through a sub section of a list in Python
522,430
3
2009-02-06T22:15:20Z
522,439
7
2009-02-06T22:16:58Z
[ "python", "loops", "list" ]
So for a list that has 1000 elements, I want to loop from 400 to 500. How do you do it? I don't see a way by using the for each and for range techniques.
``` for element in allElements[400:501]: # do something ``` These are [slices](http://docs.python.org/reference/expressions.html#id8) and generate a sublist of the whole list. They are one of the main elements of Python.
Is there a way to loop through a sub section of a list in Python
522,430
3
2009-02-06T22:15:20Z
522,442
22
2009-02-06T22:17:21Z
[ "python", "loops", "list" ]
So for a list that has 1000 elements, I want to loop from 400 to 500. How do you do it? I don't see a way by using the for each and for range techniques.
``` for x in thousand[400:500]: pass ``` If you are working with an iterable instead of a list, you should use [itertools](http://docs.python.org/library/itertools): ``` import itertools for x in itertools.islice(thousand, 400, 500): pass ``` If you need to loop over `thousand[500]`, then use 501 as the latter index. This will work even if `thousand[501]` is not a valid index.
Accessing the index in Python 'for' loops
522,563
1,512
2009-02-06T22:47:54Z
522,569
37
2009-02-06T22:49:23Z
[ "python", "loops", "list" ]
How do I access the index itself for a list like the following? ``` ints = [8, 23, 45, 12, 78] ``` When I loop through it using a `for` loop, how do I access the loop index, from 1 to 5 in this case?
``` for i in range(len(ints)): print i, ints[i] ```
Accessing the index in Python 'for' loops
522,563
1,512
2009-02-06T22:47:54Z
522,578
2,666
2009-02-06T22:52:36Z
[ "python", "loops", "list" ]
How do I access the index itself for a list like the following? ``` ints = [8, 23, 45, 12, 78] ``` When I loop through it using a `for` loop, how do I access the loop index, from 1 to 5 in this case?
Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic. The better option is to use the built-in function [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate), available in both Python 2 and 3: ``` for idx, val in enumerate(ints): print(idx, val) ``` Check out [PEP 279](https://www.python.org/dev/peps/pep-0279/) for more.
Accessing the index in Python 'for' loops
522,563
1,512
2009-02-06T22:47:54Z
23,886,515
64
2014-05-27T10:04:52Z
[ "python", "loops", "list" ]
How do I access the index itself for a list like the following? ``` ints = [8, 23, 45, 12, 78] ``` When I loop through it using a `for` loop, how do I access the loop index, from 1 to 5 in this case?
It's pretty simple to start it from `1` other than `0`: ``` for index in enumerate(iterable, start=1): print index ``` ## Note Important hint, though a little misleading, since `index` will be a `tuple` `(idx, item)` here. Good to go.
Accessing the index in Python 'for' loops
522,563
1,512
2009-02-06T22:47:54Z
28,072,982
155
2015-01-21T17:11:49Z
[ "python", "loops", "list" ]
How do I access the index itself for a list like the following? ``` ints = [8, 23, 45, 12, 78] ``` When I loop through it using a `for` loop, how do I access the loop index, from 1 to 5 in this case?
> # Using a for loop, how do I access the loop index, from 1 to 5 in this case? Use `enumerate`: ``` for index, item in enumerate(items): print(index, item) ``` And note that indexes start at zero, so you would get 0 to 4 with this. If you want the count, I explain that below. # Unidiomatic control flow What you are asking for is the Pythonic equivalent of the following, which is the algorithm most programmers of lower-level languages would use: > ``` > index = 0 # Python's indexing starts at zero > for item in items: # Python's for loops are a "for each" loop > print(index, item) > index += 1 > ``` Or in languages that do not have a for-each loop: > ``` > index = 0 > while index < len(items): > print(index, items[index]) > index += 1 > ``` or sometimes more commonly (but unidiomatically) found in Python: > ``` > for index in range(len(items)): > print(index, items[index]) > ``` # Use the Enumerate Function Python's [`enumerate` function](https://docs.python.org/2/library/functions.html#enumerate) reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable (an `enumerate` object) that yields a two-item tuple of the index and the item that the original iterable would provide. That looks like this: ``` for index, item in enumerate(items, start=0): # default is zero print(index, item) ``` This code sample is fairly well the [canonical](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#index-item-2-enumerate) example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient. ## Getting a count Even if you don't need indexes as you go, but you need a count of the iterations (sometimes desirable) you can start with `1` and the final number will be your count. ``` for count, item in enumerate(items, start=1): # default is zero print(item) print('there were {0} items printed'.format(count)) ``` The count seems to be more what you intend to ask for (as opposed to index) when you said you wanted from 1 to 5. --- ## Breaking it down - a step by step explanation To break these examples down, say we have a list of items that we want to iterate over with an index: ``` items = ['a', 'b', 'c', 'd', 'e'] ``` Now we pass this iterable to enumerate, creating an enumerate object: ``` enumerate_object = enumerate(items) # the enumerate object ``` We can pull the first item out of this iterable that we would get in a loop with the `next` function: ``` iteration = next(enumerate_object) # first iteration from enumerate print(iteration) ``` And we see we get a tuple of `0`, the first index, and `'a'`, the first item: ``` (0, 'a') ``` we can use what is referred to as "[sequence unpacking](https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences)" to extract the elements from this two-tuple: ``` index, item = iteration # 0, 'a' = (0, 'a') # essentially this. ``` and when we inspect `index`, we find it refers to the first index, 0, and `item` refers to the first item, `'a'`. ``` >>> print(index) 0 >>> print(item) a ``` # Conclusion * Python indexes start at zero * To get these indexes from an iterable as you iterate over it, use the enumerate function * Using enumerate in the idiomatic way (along with tuple unpacking) creates code that is more readable and maintainable: So do this: ``` for index, item in enumerate(items, start=0): # Python indexes start at zero print(index, item) ```
How can I strip Python logging calls without commenting them out?
522,730
25
2009-02-07T00:08:11Z
526,078
19
2009-02-08T17:33:41Z
[ "python", "optimization", "logging", "bytecode" ]
Today I was thinking about a Python project I wrote about a year back where I used `logging` pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (`hotshot` indicated it was one of my biggest bottlenecks). I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and **target only the code objects that are causing bottlenecks**. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so: ``` [Leave ERROR and above] my_module.SomeClass.method_with_lots_of_warn_calls [Leave WARN and above] my_module.SomeOtherClass.method_with_lots_of_info_calls [Leave INFO and above] my_module.SomeWeirdClass.method_with_lots_of_debug_calls ``` Of course, **you'd want to use it sparingly and probably with per-function granularity** -- only for code objects that have shown `logging` to be a bottleneck. Anybody know of anything like this? **Note:** There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named `debug` may have to be wrapped with an `if not isinstance(log, Logger)`. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)
What about using [logging.disable](http://docs.python.org/library/logging.html?highlight=logging#logging.disable)? I've also found I had to use [logging.isEnabledFor](http://docs.python.org/library/logging.html?highlight=logging#logging.Logger.isEnabledFor) if the logging message is expensive to create.