The same reason you need to give the name of the function to the def
statement, or the name of the class to class
; both can be created by other means too. Because that's how the syntax is designed, to make common actions possible with readable clear, concice syntax.
For the same reason you use object.attributename
when you already know the attribute name you want to access, but use getattr()
when you need to determine the name dynamically. The latter is more work for the programmer to understand.
Imagine having to wade through
modules_to_import = ['builtins', 'datetime']
for name in modules_to_import:
globals()[name] = __import__(name)
print_function_name = 'print'
current_time = getattr(getattr(globals()['datetime'], 'datetime'), 'now')()
getattr(globals()['builtins'], print_function_name).__call__('Hello world!, it is now', current_time)
That'd be totally unreadable. Compare that to
import datetime
current_time = datetime.datetime.now()
print('Hello world!, it is now', current_time)
Python is a highly dynamic programming language, however, so you are given tools to do many tasks dynamically. type()
lets you build classes dynamically, functions can be constructed without using def
or lambda
, and you can import modules based on a variable. You use those tools when you have a clear use-case for dynamic behaviour, rather than static (but more readable) syntax.