3

Reading the CherryPy tutorial I run into this

class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

So was does it mean? is exposed a variable in the local scope of the method index? If so, can I the value of expose change? I think it has something to do with python's MetaObject protocol to expose a class definition as an object itself.

PuercoPop
  • 6,707
  • 4
  • 30
  • 40

2 Answers2

4

Functions are first-class objects in Python. A function definition creates a function object and binds it to the function's name. Function objects can have attributes, and that's what you are seeing here. The life time of a function attribute is bound the the life time of the function object, while the life time of a local variable inside the function is bound to a single execution of the function. They are completely separate.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
2

No it's not a local variable of function index, rather it's a attribute of that function . And yes you can modify it outside the function too.

Read the PEP 232 on function attributes.

example:

In [2]: def foo():pass
   ...: 

In [3]: foo.bar="text"

In [4]: foo.bar
Out[4]: 'text'
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504