Page 3 - 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.
Receive the tools necessary to be the rock star of your field. Our 12-month program teaches you the evolving world of multi-channel marketing as well as the complex issues and opportunities found in the industry.
ASP Free and Iron Speed Designer are giving away $5,500+ in FREE licenses. Iron Speed's RAD CASE toolset can save up to 80% of your coding time. One free license per week, one perpetual license per month! Download and Activate to enter!
Web development can be a daunting task, even for specialists. There is a lot of information to absorb and a lot of technologies to learn in order to manage a superior website. When trying to learn the ropes, developers need a reliable source to introduce new ideas that can be easily implemented. When working on large projects, even web veterans may run into a technology or an aspect of a technology that they are unfamiliar with.
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 67
This is a follow up to my last post about Mac OS X clickable Python programs. As I mentioned there seemed to be a problem running Python programs from the Script Menu, I've since figured out that the script is run however it is run in the background and not in the Terminal like you would expect .
It is possible to wrap the Python program in a simple Applescript to force the script to open it in Terminal
Note: This can even be done from the command line using one of the osa* commands.
This is probably overkill unless you need to interact with the program – supply input – in which case I would suggest that you just do some typing and run it from the command line .
It is also handy to redirect stdout to a specified file so that you can read any results from there. This can be done something like this:
This can be done with any of the standard file handles but I'n the case of stderr I suggest that you get the program working before adding it to the Script Menu since the lack of Terminal Window makes spotting errors troublesome at best.
Have fun all,
Mark.
__________________
programming language development: www.netytan.com– Hula
Posts: 3
Time spent in forums: 32 m 40 sec
Reputation Power: 0
Timing with decorators
I've found the new (2.4) 'decorator' feature to be quite useful for abstracting away 'aspects' as they say:
(based on an earlier post about timing)
Code:
import time
def print_timing(func):
def wrapper(*arg):
t1 = time.clock()
res = func(*arg)
t2 = time.clock()
print '%s took %sms.' % (func.func_name, (t2-t1)*1000.)
return res
return wrapper
@print_timing
def f1():
x=[]
for i in xrange(1,10000):
x.append(str(i))
s = ''.join(x)
@print_timing
def f2():
x=''
for i in xrange(1, 10000):
x += str(i)
if __name__ == '__main__':
f1()
f2()
Quote:
Result:
f1 took 17.1052466165ms.
f2 took 18.325234073ms.
You can see how nicely you could use this for logging, synchonization, contracts, etc..
Posts: 4
Time spent in forums: 1 h 52 m 19 sec
Reputation Power: 0
Operator overloading
Python supports operator overloading, and does so with methods of a class.
For example, you can add 2 objects together with __add__. But, you SHOULD create a new object of the class BEFORE adding........__iadd__ excludes that suggestion.
Code:
class Foo:
def __init__(self, integer=0):
if not isinstance(integer, int):
try:
integer = int(integer)
except: raise
self.i = integer
def __add__(self, other): # new = self + other
new = self.__class__() # 1. Create
if isinstance(other, self.__class__): # 2. Check
new.i = other.i
else: raise ValueError("foo+other: Incompatible type addition (got %s, expected %s)" % (other, self.__class__.__name__))
return new # 3. Return
def __iadd__(self, other): self += other
if isinstance(other, self.__class__):
self.i = other.i
return self
else:
raise ValueError("foo+=other: Incompatible type addition (got %s, expected %s)" % (other, self.__class__.__name__))
As you can see, there is a constitent way to object addition, subtraction, etc. See http://www.python.org/doc/2.1.3/ref/numeric-types.html
Posts: 350
Time spent in forums: 2 Days 11 h 53 m 20 sec
Reputation Power: 26
Quote:
Originally Posted by cgreb
I've found the new (2.4) 'decorator' feature to be quite useful for abstracting away 'aspects' as they say:
(based on an earlier post about timing)
Code:
import time
def print_timing(func):
def wrapper(*arg):
t1 = time.clock()
res = func(*arg)
t2 = time.clock()
print '%s took %sms.' % (func.func_name, (t2-t1)*1000.)
return res
return wrapper
@print_timing
def f1():
x=[]
for i in xrange(1,10000):
x.append(str(i))
s = ''.join(x)
@print_timing
def f2():
x=''
for i in xrange(1, 10000):
x += str(i)
if __name__ == '__main__':
f1()
f2()
Shouldn't ...
Code:
print '%s took %sms.' % (func.func_name, (t2-t1)*1000.)
... be something like...
Code:
print '%s took %0.3fms.' % (func.func_name, (t2-t1)*1000.)
For some odd reason the %s works even though (t2-t1)*1000 gives a float. The wonders of Python! Maybe that is supposed to be the real trick!
By the way, if you run that code a few times the results flip all over. Sometimes f1() is faster than f2(), other times it's the reverse.
Posts: 1,585
Time spent in forums: 2 Weeks 4 Days 2 h 58 m 23 sec
Reputation Power: 1371
Quote:
Originally Posted by Dietrich
For some odd reason the %s works even though (t2-t1)*1000 gives a float. The wonders of Python! Maybe that is supposed to be the real trick!
It is not some odd reason, it is by design. The %s operator will convert any operand to a string (using its __str__ method) and display the result. There is also a %r operator that converts it using repr instead.
e.g.
Code:
Python 2.4.1 (#1, May 27 2005, 18:02:40)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print '-%s-' % 123
-123-
>>> print '-%s-' % 'hello'
-hello-
>>> print '-%s-' % 123.456
-123.456-
>>> print '-%r-' % 'hello'
-'hello'-
>>> print '-%s-' % Exception
-exceptions.Exception-
>>> print '-%r-' % Exception
-<class exceptions.Exception at 0x46526c>-
>>>
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 67
The jumping around likely has something to do with how the time.clock() function works on different platforms; in any case using time.time() in its place with a few mod's should fix the problem .
Posts: 5,535
Time spent in forums: 1 Month 3 Weeks 1 Day 19 h 30 m 28 sec
Reputation Power: 1049
Quote:
Originally Posted by sf2k
For newb's like me. Seems to me that time and time again I'm looking through the string and os modules. Get to know them. They are your friends.
If you do a lot of file processing, knowing the os module (there's a lot) makes using the filesystem a breeze. If you ever have to work with string constants, look at the string module. Odds are it's already there. (ie: string.digits, string.punctuation etc)
So for example, I was making a general utility to search all my source files for a phrase inside my code. (I forget where I put stuff right?) Checked the os module. Sure enough, I found os.walk, (os.path.walk < 2.3) which was immediately useful for my code. This is a recursive search, taking a walk down each tree branch from whatever starting point. I can't imagine how much time this has saved me. Sweet.
Cheers
sf2k
Isn't os.path.walk the single most annoying function in the world? No longer fear it, I saw this and thought of Jason Orendorff's path module
Here's a code sample That walks your home directory and deletes all emacs backup files (which end in ~)
Posts: 350
Time spent in forums: 2 Days 11 h 53 m 20 sec
Reputation Power: 26
Just a few tricks you can play with the homely input() function:
Code:
# input() actually uses raw_input() and then tries to
# convert the input data to a number using eval()
# this leads to some unexpected results
x = 123
a = input('Enter x: ')
# if the user enters the character x instead of a value then a = 123, try it
print a
b = input('Enter 355/113.0 : ')
# eval() will give b the result of the math expression, can be useful
print b
# this would be the more dangerous side of input() and its hidden partner eval()
# eval() evaluates this statement and executes it
# and will actually create a new directory on your C drive, somewhat harmless
# but a troublemaker could enter a similar statement to wipe out files!!!!
z = input("Enter __import__('os').mkdir('C:/Aatest') : ")
c = input('Enter "Hello" : ')
# since "Hello" is a string it will be passed on to c (who needs raw_input()?)
print c, type(c)
d = input('Enter a list like [1,2,3] : ')
# you guessed it, d will be a list, can be useful
print d, type(d)
# this will give an error since eval() doesn't know what to do with just enter
z = input('Press Enter ...')
__________________
Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
Posts: 2,306
Time spent in forums: 3 Days 6 h 42 m 51 sec
Reputation Power: 59
iPython -- nice shell
I know it's been mentioned a few times in this forum, but it should be stuck here: use ipython for an interactive shell rather than 'python'.
Do this especially if you envy the Ruby shell (irb), with it's introspection and helpful shortcuts. Python's default shell is nowhere near this helpful, but iPython has most of the advantages of irb and a few extras.
- tab-completion for classes, objects, and methods, as well as local filesystem searching
- "help [function]" brings up a nice help menu
- "? [classname]" brings up a quick class description with docstring
- nicely colorized/formatted output
This is just the beginning. Take a look at the full list of features.
Posts: 350
Time spent in forums: 2 Days 11 h 53 m 20 sec
Reputation Power: 26
Along the same line:
Code:
# an improved switch/case like statement to replace
# multiple if/elif/else statements
def switch_case(case):
return "You entered " + {
'1' : "one",
'2' : "two",
'3' : "three"
}.get(case, "a bad number")
num = raw_input("Input a number between 1 and 3: ")
print switch_case(num)
Posts: 2
Time spent in forums: 35 m 32 sec
Reputation Power: 0
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!
Last edited by jack0 : March 2nd, 2011 at 08:54 PM.
Reason: Removed random keywords at end
Posts: 5
Time spent in forums: 8 m 49 sec
Reputation Power: 0
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: