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.

Sunder
  • 85
  • 1
  • 9
  • You are missing some code. `f` must have been defined earlier. – jpp Apr 04 '18 at 11:19
  • definitely not. These are the first lines I typed. – Sunder Apr 04 '18 at 11:20
  • Well, I can't replicate. I get, predictably: `AttributeError: 'function' object has no attribute 'name'`. – jpp Apr 04 '18 at 11:21
  • 1
    What makes you think that the dot syntax can only be used on classes and modules? – Aran-Fey Apr 04 '18 at 11:21
  • @jpp apologies. edited the code part. replaced 'name' with 'author' – Sunder Apr 04 '18 at 11:23
  • Possible duplicate: [Python function attributes - uses and abuses](https://stackoverflow.com/questions/338101/python-function-attributes-uses-and-abuses) – jpp Apr 04 '18 at 11:25
  • @Aran-Fey can you please elaborate on other cases where dot is used? Where and how to use. If not, just provide a link/book I can refer to. Thanks in advance. – Sunder Apr 04 '18 at 11:26
  • You use `foo.bar` to get the `bar` attribute of `foo`. It doesn't matter what `foo` is. It doesn't have to be a class or a module. It can be used on anything that has attributes. – Aran-Fey Apr 04 '18 at 11:37
  • @jpp, thanks for the link to the 'function attributes' thread. It was useful. I didn't know these are also called function attributes. – Sunder Apr 04 '18 at 12:01

1 Answers1

5

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']
Ravindra S
  • 6,302
  • 12
  • 70
  • 108
JOHN_16
  • 616
  • 6
  • 12