-2

I am reading https://stackoverflow.com/a/28231805/156458

Why can we give the module name as a variable to builtins.__import__ function, while we must give the module name directly to the import statement?

What difference between a statement and a function that leads to such a difference?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Tim
  • 1
  • 141
  • 372
  • 590
  • Thanks. Does the same thing happen to other languages, such as C, C++, C#, Java, ...? – Tim Jun 23 '17 at 13:27
  • Python is a highly dynamic language, giving you access to much of the syntax through dynamic means. The languages you just named are highly static, meaning that doing the same from the runtime is a lot harder, or often impossible. But for the most part, yes, syntax exists to express common constructs easily (within the language design constraints). – Martijn Pieters Jun 23 '17 at 13:33

1 Answers1

8

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343