Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "import" a statement but "reload" a function?

Tags:

python

I know how to use both, but I'm curious why the decision was made to make one a statement and the other a function.

like image 495
user2229219 Avatar asked Apr 25 '16 13:04

user2229219


People also ask

What is the use reload () in Python?

The reload() is used to reload a previously imported module or loaded module. This comes handy in a situation where you repeatedly run a test script during an interactive session, it always uses the first version of the modules we are developing, even we have made changes to the code.

Why is the use of import all statement not recommended?

Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import.

What is the function of the import statement?

Import statement in Java is helpful to take a class or all classes visible for a program specified under a package, with the help of a single statement. It is pretty beneficial as the programmer do not require to write the entire class definition. Hence, it improves the readability of the program.

What happens when you import a function in Python?

Python code in one module gains access to the code in another module by the process of importing it. The import statement is the most common way of invoking the import machinery, but it is not the only way. Functions such as importlib.


1 Answers

First of all you can import using a function, from importlib's documentation:

The __import__() function
The import statement is syntactic sugar for this function.

for instance both of these statements are equivalent:

from random import randint as random_int

random_int = __import__("random").randint

However the import statement greatly benefits from alternate syntax where as reload does not really have any alternate meaning.

I can also imagine a lot of beginner programmers making this mistake if reload was it's own statement:

from random import *
reload random #does not affect the current namespace!

Since the reload function requires a module (which is not preduced with from _ import *) coders may wonder why the names imported are not reloaded. related to this answer

like image 125
Tadhg McDonald-Jensen Avatar answered Oct 21 '22 07:10

Tadhg McDonald-Jensen