Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Adding function attributes in Python

📅 2012-May-03 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ attribute, function, python ⬩ 📚 Archive

A surprising feature in Python is that attributes can be added to functions at any point in the runtime. Both inside and outside the function the attribute is referred to as functionName.attribute. The attribute comes to life only when it is first set with a value. Trying to use an attribute that is not yet alive, results in AttributeError.

def foo():
    return foo.x

print( foo() ) # AttributeError: 'function' object has no attribute 'x'
foo.x = 10
print( foo.x ) # 10
print( foo() ) # 10

Tried with: Python 3.2