Reputation: 59
I was just looking at the hasattr
method which takes in an object as a argument.
To check the "everything is an object" theory. I made a user defined function with an attribute "name"
, but it returns False
. The code which I wrote was:
def trial():
name = "james"
hasattr(trial, "name")
Does this mean that functions are not objects? I would appreciate it if someone can help we figure this out.
Upvotes: 0
Views: 2000
Reputation: 2274
A function in Python is indeed an object but local variables in a function are not a property of it.
Try adding this at the end of your code:
>>> trial.__dir__()
It will show you all the properties of the function you defined - and you're accessing a property of the function object.
You can even add properties to the function object if you want, though you have to be careful as to not overwrite an existing property. Try this:
>>> trial.foo = 'bar'
>>> dir(trial) # Equivalent to trial.__dir__(). 'foo' is now in the list.
>>> hasattr(trial, 'foo')
>>> print(trial.foo)
When your code is executing, the function becomes something tangible from the moment it is defined but the variables in it are ephemeral in the sense that they are values stored in memory only for the duration of the function execution (i.e. when you call it) and are gone after it finishes. It's actually a bit more complicated than that, with garbage collection in the mix, but from a simple perspective, that's pretty much what happens.
Upvotes: 1
Reputation: 3206
Functions are objects, but what you have created is a function with a local variable name
, which is not an attribute of that function. Let's inspect the function code:
>>> trial.__code__.co_varnames
('name',)
As you can see, name
is indeed a local variable of the function.
However, attributes can still be defined on functions:
>>> def trial():
... name = "james"
...
>>> trial.foo = 'bar'
>>> hasattr(trial, 'foo')
True
>>> getattr(trial, 'foo')
'bar'
The way to assign an attribute to a function is by saying <func>.<attr_name> = <attr_value>
, just like for any other other object that allows for it.
(not saying this is necessarily the best way of achieving the desired result, but just as a demo that it is possible)
Upvotes: 2