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?
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.
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.
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.
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With