5

I need to understand this concept wherein we can use the dot (.) in the variable name within a function definition. There's no class definition nor a module here and Python is not supposed accept a variable name that includes a dot.

def f(x):
    f.author = 'sunder'
    f.language = 'Python'
    print(x,f.author,f.language)

f(5)
`>>> 5 sunder Python`

Please explain how this is possible, and suggest related documentation for further exploration.

9
  • You are missing some code. f must have been defined earlier. Commented Apr 4, 2018 at 11:19
  • definitely not. These are the first lines I typed. Commented Apr 4, 2018 at 11:20
  • Well, I can't replicate. I get, predictably: AttributeError: 'function' object has no attribute 'name'. Commented Apr 4, 2018 at 11:21
  • 1
    What makes you think that the dot syntax can only be used on classes and modules? Commented Apr 4, 2018 at 11:21
  • @jpp apologies. edited the code part. replaced 'name' with 'author' Commented Apr 4, 2018 at 11:23

1 Answer 1

6

From official documentation:

Programmer’s note: Functions are first-class objects. A “def” statement executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def.

So, function is an object:

>>> f.__class__
<class 'function'>
>>> f.__class__.__mro__
(<class 'function'>, <class 'object'>)

... and it means that it can store attributes:

>>> f.__dict__
{'language': 'Python', 'author': 'sunder'}
 >>> dir(f)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'author', 'language']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.