Python Best Practice Patterns
stevenloria.com
Python Best Practice Patterns
1–10 of 97 posts
Re: Python Best Practice Patterns
#2Re: Python Best Practice Patterns
#3http://stackoverflow.com/questions/1275646/python-3-and-stat...
Re: Python Best Practice Patterns
#4I never knew you could use __enter__ and __exit__ to code your own things that work with the 'with' statement. Well worth the read!
from contextlib import contextmanager
@contextmanager
def tag(name):
print "" % name
yield
print "" % name
with tag("h1"):
print "foo"
"""
foo
"""Re: Python Best Practice Patterns
#5I never knew you could use __enter__ and __exit__ to code your own things that work with the 'with' statement. Well worth the read!
@contextlib.contextmanager
def manager(*args):
object = initialize(args)
try:
yield object
finally:
# cleanup
object.close()Re: Python Best Practice Patterns
#6Re: Python Best Practice Patterns
#7Re: Python Best Practice Patterns
#8I never knew you could use __enter__ and __exit__ to code your own things that work with the 'with' statement. Well worth the read!
Re: Python Best Practice Patterns
#9* if a method does not use the object's state (no `self` usage) make it a `class-` or `staticmethod`.
* Some magic methods are presented. There's more to them[0].
* one should not write `class MyClass:` but `class MyClass(object):` (new style class[1])
* the last one (`return None`) make me very dubious
* Cascading methods: that's a big no. The idiom is that if a method may change the state of the object then it should return None (eg `set.add`)
0: well-written and comprehensive guide: http://www.rafekettler.com/magicmethods.html
Re: Python Best Practice Patterns
#10Several of those patterns are incomplete or frowned upon: * if a method does not use the object's state (no `self` usage) make it a `class-` or `staticmethod`. * Some magic methods are presented. There's more to them[0]. * one should not write `class MyClass:` but `class MyClass(object):` (new style class[1]) * the last one (`return None`) make me very dubious * Cascading methods: that's a big no . The idiom is that…