Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top