Why do you have to 'import' Python Standar

2020-04-11 08:20发布

问题:

Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 6 years ago.

I'm new to Python coding and I'm coming from a PHP background. I'm curious why you have to 'import' functions at the top of you python script. In PHP you can simply use the function such as:

sleep(10);

The above would cause the script to sleep for 10 seconds. However, to do the same thing in python, it seems I have to import the 'time' functionality:

import time
time.sleep(10)

My question is: why is this necessary? If these extra functions are part of python already, why does python have to specifically load them? In PHP, if a module is missing, the script fails. I have to install the module globally and then it's usable like normal.

Is there an advantage to python's approach?

回答1:

Yes, several. It means that there is less to compile and run by default. Your program will load faster, because it only knows about the parts of Python that it actually needs.

It keeps the global namespace clean, and allows functionality to be grouped logically into modules. Different modules can have identically-named functions without clashes (a file and socket class would probably both have open and close functions, for example).



回答2:

Well, what if you want to use both library A and library B with a function called f? In Python this is super easy: you import both of these modules, and then you qualify correct fs name with it's module, e.g. A.f()

This leads to the first advantage: namespaces (as a solution for name-clashing problem) and non-polluting global scope.

The second advantage is more flexible module system.



回答3:

But you don't need to import functions like "print()" or "input()". These functions are provided for you already. The others are not necessarily needed so they're located elsewhere, that's why you import modules containing functions that are not provided by default