Will getattr() create a missing attribute with the default value provided?

Question

If a call is made to getattr() for an attribute which is not present and a default value is provided, will the function create the missing attribute and assign it the default value?

Answer

NO, the getattr() function will not create an attribute which is not present. If a default value is provided, it will return that value at the time getattr() is called, otherwise an AttributeError error will be raised if no default value is provided.

5 Likes

Could you provide an example of the purpose of the 3rd argument that can be entered? Would that be only to avoid generating an error?

1 Like

Precisely.

Python getattr()

Scroll down to example 2.

Note that the default is a value not a key, as though there is a gender attribute.

2 Likes

I don’t understand the given solution here.


#Task:
#In script.py we have a list of different data types, some strings, some lists, and some dictionaries, all saved in the variable how_many_s .

#For every element in the list, check if the element has the attribute count . If so, count the number of times the string "s" appears in the element. Print this number.


#Solution
how_many_s = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]

for element in how_many_s: if hasattr(element, "count"): print(element.count("s"))


#How does the "count" attribute in the hasattr() function make it work? Given that it’s just a string and isn’t defined previously…

Follow-up question - why can’t I call the "count" string attribute anything else, like "test" or "apple" ?

Thanks.

count is a method for the list object type
if you do the following for the different object types, you will see all the methods available for those types:

help([“a”, “b”]) # or can use help(list)
help(18) # or can use help(int)
help(str) # must use this for a string object type
help({}) # or can use help(dict)

if there is an existing object class attribute such as count for the object type, which you can check for using the hasattr() method, then you can call it against that object.

4 Likes