Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you have to 'import' Python Standard Library functions? [closed]

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?

like image 476
BoomShadow Avatar asked Nov 30 '13 22:11

BoomShadow


People also ask

Why do you have to import libraries in Python?

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.

What are standard library imports Python?

The Python Standard Library is a collection of script modules accessible to a Python program to simplify the programming process and removing the need to rewrite commonly used commands. They can be used by 'calling/importing' them at the beginning of a script.

Why do you need to import libraries?

The Python import statement actually executes the top-level code in the library file. This code defines the functions and classes in the library. So without the import statement, the types would simply not exist, so there would be no way for the language to find them.

Does import have to be at the top?

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.


1 Answers

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).

like image 50
joews Avatar answered Oct 10 '22 12:10

joews