Live data from Hacker News

Python Best Practice Patterns

stevenloria.com

1–10 of 97 posts

Re: Python Best Practice Patterns

#4
post #2

I never knew you could use __enter__ and __exit__ to code your own things that work with the 'with' statement. Well worth the read!

For simple context managers, an easier method is to use contextlib.contextmanager (http://docs.python.org/library/contextlib.html).

  from contextlib import contextmanager
  
  @contextmanager
  def tag(name):
      print "" % name
      yield
      print "" % name
  
  with tag("h1"):
      print "foo"
  """
  
  foo
  
  """

Re: Python Best Practice Patterns

#5
post #2

I never knew you could use __enter__ and __exit__ to code your own things that work with the 'with' statement. Well worth the read!

You don't even have to create a full object if there's no need to:

    @contextlib.contextmanager
    def manager(*args):
        object = initialize(args)
        try:
            yield object
        finally:
            # cleanup
            object.close()

Re: Python Best Practice Patterns

#8
post #2

I never knew you could use __enter__ and __exit__ to code your own things that work with the 'with' statement. Well worth the read!

You might be interested in the docs on the Data Model [0] to learn more about the various "dunder" (__foo__) methods. There are a ton of cool things you can do with python objects.

[0] http://docs.python.org/2/reference/datamodel.html

Re: Python Best Practice Patterns

#9
Several 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 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

1: http://www.python.org/doc/newstyle/

Re: Python Best Practice Patterns

#10
post #9

Several 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…

It seems he's using Python 3 (using print as a function), so no need to inherit object.
Post reply on HN