Discuss Tips, tricks, inspiration, etc in the Python Programming forum on Dev Shed. Tips, tricks, inspiration, etc Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
Posts: 543
Time spent in forums: 1 Day 11 h 18 m 34 sec
Reputation Power: 23
Tips, tricks, inspiration, etc
I had an idea to make a thread where people can post tips, tricks, thing to inspire or motivate people, links, etc.
Hopefully this thread will be able to help any Pythoner. Whether it be a complete beginner or a very advanced expert.
Tips: An example would be stuff that will help improve someone's programming. Such as: "Instead of using all of these functions, you can easily accomplish the same thing just using these two functions."
Tricks: An example would be stuff that will help someone program faster.
Inspiration: An example would be anything that serves as a great source of inspiration.
Motivation: An example would be anything that helps motivate someone.
Links: This could be newsgroups, mailing lists, IRC channels, web sites, etc.
If people like this thread and post a lot of stuff, I will make a documentation.
Posts: 325
Time spent in forums: 7 h 58 m 36 sec
Reputation Power: 11
I like this idea. Hope ppl can try keep the msgs consice
Here's a couple of things I just picked up.
I'm on a few python mailing lists and this one came up recently.
This is supposed to be much faster than providing a comparison function to list.sort()
Code:
unsorted_list = [{'id':99, 'title':'a'},{'id':42, 'title':'b'}, ... ]
decorated_list = [(x['id'],x) for x in unsorted_list]
decorated_list.sort()
sorted_list = [y for (x,y) in decorated_list]
Another thing: using : 'dictarray = [{}]*10' creates only one dictionary, with ten references to it.
whereas 'dictarray = [{} for i in range(10)]' creates 10 seperate dictionaries
Posts: 383
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 12
TIP:
Write unit tests! Python comes with PyUnit (the unittest module), and you should take advantage of that. It makes adding incremental improvements a LOT less painful because you can test and make sure your existing functionality isn't broken. In fact, the way we prefer to do tests on the IRC bot I'm working (link) is that you write the test first and then you code the functionality so that it passes the tests that you code. Same goes for bugs that we find. Instead of trying to fix the bug right away we write a test that (currently) pokes the bug and causes the error. Then we know the bug is fixed once we run the test and it passes.
Posts: 383
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 12
Oh yeah, just remembered another trick.
If you're going to be building a string iteratively (in a loop, for example), then instead of using string concatenation each time, the most efficient way of doing it is actually aggregating the component strings into a list and then joining them. So, for example:
Code:
somedict = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
L = []
for (k,v) in somedict:
L.append('%s (%s)' % (v, k))
results = ' '.join(L)
instead of:
Code:
somedict = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
s = ""
for (k,v) in somedict:
s += '%s (%s) ' % (v, k)
results = s[:-1] # Remove trailing space
Actually, I hadn't thought of the trailing space issue, but using a list makes that issue go away too
The reason it's faster is because every time you concatenate a string it has to use 3 strings: the original, the stuff to add, and the result string (because strings are immutable!!, so you can't just add to the original string object). So all the build-up/tear-down time for each of those objects is incurred with each iteration. When using a list you just have to build a string and append it to a list (which is a cheap operation, no new objects required since lists are mutable) each time. Then you just join them at the end, which is cheaper than concatenating one at a time.
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
print without the new line...
Usually not a problem but from time to time that extra \n can get in the way! Now before today i would have used sys.stdout.write(str) but i just discovered this handy little syntax treat.
By adding an extra comma at the end of you're print statment you can actually avoid outputting the \n char i.e.
Code:
>>> for each in ('just', 'a', 'few', 'strings'):
... print each
...
just
a
few
strings
>>> for each in ('just', 'a', 'few', 'strings'):
... print each,
...
just a few strings
>>>
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
PyCrust
Just started using PyCrust, i'm very impressed so far, definatly a good enough reason to install wxPython even if you don't plan on doing any GUI development!
PyCrust is an interactive Python shell written in Python using wxPython. PyCrust is now part of wxPython (www.wxpython.org), so packaged files are no longer available here, and the latest development version has moved to the wxWindows CVS repository.
All of the replies so far work very well! Thanks guys! Keep them coming.
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
PyCrust is awesum, yet another reason in my lets do away with Tkinter argument .
When installing wxPython (on windows) a new folder is created in the menu; containing docs, examples and a few wx applications with a Pie icon... and one called PyCrust!
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
As far as i know it doesn't, but you can select all and copy you're program then 'paste plus' it into you're Python shell with the same effect as running (in theory).
I would quite like to know why PyCrust, PyAlaMode etc arn't just one program... this would make an awesum IDE for Python! But it seems to be in pieces
In any case the wxPython shell is definatly gonna replace IDLE for me!
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
Backticks
I did something today i'd been wanting to do for a while... that is figure out what in hell backticks do in Python. And to my surprise what they actually did was no-where near what i expected having used perl.
In perl backticks indicate system calls but in Python, using backticks is like putting an object directly into a string and escaping special chars that could cause a problem (kinda like raw strings) i.e.
Code:
>>> v1 = 'string'
>>> v2 = "string"
>>> v3 = 'C:\Documents and Settings\Mark\Desktop'
>>> v4 = 'just a "string" in double quotes'
>>> `v1`
"'string'"
>>> `v2`
"'string'"
>>> `v3`
"'C:\\\\Documents and Settings\\\\Mark\\\\Desktop'"
>>> `v4`
'\'just a "string" in double quotes\''
print `v1`
'string'
print `v2`
'string'
print `v3`
'C:\\Documents and Settings\\Mark\\Desktop'
print `v4`
'just a "string" in double quotes'
>>> v5 = (`v1`,`v2`,`v3`,`v4`)
>>> v5
("'string'", "'string'", "'C:\\\\Documents and Settings\\\\Mark\\\\Desktop'", '\'just a "string" in double quotes\'')
>>>
Posts: 1,585
Time spent in forums: 2 Weeks 4 Days 2 h 58 m 23 sec
Reputation Power: 1372
Get to know the Python help system
One of favourite features of Python is the extensive help system, but it is not well documented and many people probably don't know of it's existence. Spending a little time to learn how to use it can pay huge dividends.
There are three components to the help system:
1) the extensive documentation that is installed with Python. This is also available in a wide range of formats, including PDF, HTML and Windows Help. If you have installed the Windows version of Python then you will get the WinHelp version, but I recommend installing the HTML version as well, for reasons we shall see in a minute. Download it from http://www.python.org/doc/current/download.html and unzip it, then set the environment variable PYTHONDOCS to point to the directory.
2) the interactive help system. Type help() at the interactive prompt and you will enter the help mode. You can get help on any module, class or function that has a docstring - not just from the modules that originally came with Python, but from any module on the path. If you have the HTML help files installed as described above, then you can also get help on a wide range of language features, such as keywords.
When at the interactive prompt you can also get help directly for any object currently in the namespace, e.g.
Code:
>>> import string
>>> help(string.atoi)
Help on function atoi in module string:
atoi(s, base=10)
atoi(s [,base]) -> int
Return the integer represented by the string s in the given
base, which defaults to 10. The string s must consist of one
or more digits, possibly preceded by a sign. If base is 0, it
is chosen from the leading characters of s, 0 for octal, 0x or
0X for hexadecimal. If base is 16, a preceding 0x or 0X is
accepted.
You can also get help on language features or from modules that are not currently imported by putting the help string in quotes:
Code:
>>> help('re.match')
Help on function match in re:
re.match = match(pattern, string, flags=0)
Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found.
Type help('modules') for a list of modules that Python currently knows about.
3) there is a script that will run an HTTP server that will let you browse web pages generated dynamically from the __doc__ strings: PYTHON/tools/scripts/pydocgui.pyw. If you have installed the Windows version then you should have a shortcut to it set up in the Start menu called 'module docs'. Again, this Tkinter program displays help for any module on the path, not just the standard library. It also lets you search the __doc__ strings.
I believe that the combination of of the help system with the interactive mode and the simple, regular syntax make Python the easiest language on earth to learn.