decorators question

Soni Bergraj sonibergraj at youjoy.org
Mon Dec 4 14:28:38 EST 2006


> Hmmm...ok...it calls the decorator but when ?? It (the runtime) loads
> the .py file and start to call every decorator
> it finds on it, regardless of the existance of code that actually calls
> the decorated functions ??
> I understand thet Python does not call the decoratated functiond but it
> ends up this way...
Python simply executes the module body when you import a module. class
and def statements result in binding of class and function objects to
the corresponding names. It's really that simple. Try the following to
get a deeper insight:

# file foobar.py

def bar(f):
   return 'some text'

@def bar
def foo():
    print "foo"


When you import this module module in an interactive python session you
will get he following.

>>> from foobar import *
called foo
>>> bar() # this will fail because bar is not a function
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable
>>> bar
'some text'

Hope that helps;)
-- 
Soni Bergraj
http://www.YouJoy.org/



More information about the Python-list mailing list