To understand what generic imports means


Question about section 8. generic imports :
“There is a Python module named math that includes a number of useful variables and functions, and sqrt() is one of those functions. In order to access math, all you need is the import keyword. When you simply import a module this way, it’s called a generic import.”

I don’t understand how it works : Where is this module stored ? I import this module from where ?


Hey there.

When you have the Python interpreter installed on your computer, it comes with a lot of common functions already written so that you don’t have to do everything from scratch (unless you wanted to…). These functions are grouped together based on the things they have in common into “modules”.

All the import statement does is tell Python that you want to use some of this pre-built code, and which bits of it you want. There are a lot of “built-in” functions, like print, which Python can use without needing to specifically import them, but some more specialised functions - like a lot of the mathematical functions - need to be imported first before you can use them. (In this example, from the math module.)

A “generic import” just means that you’re importing the entire module. So, import math would import every function from the math module regardless of whether you need or have used it.

Generally, it’s better to only import the specific functions you need from the module(s) that defines them. So, if say you needed to do some trigonometry in your program, you could import the sine function by using from math import sin and this will only import the sin function into your program. If we are doing some serious trigonometry, we’re gonna need the other functions too - so we can import multiple functions with one statement, like this: from math import sinh, cosh, tanh.

Does that help?


Thanks a lot for your very clear answer :slight_smile:


Deleted a bunch of posts in here… was only confusing…

Some clarification:

importing a module executes all of it no matter what. names are then created in the importing module to refer to things in the imported module, or the imported module itself

as for where they come from, python looks in multiple places (see sys.path) in the file system, and they may also be defined differently (typically in either C or python), or even created by the program while it is running. the file where you put your code is also a module, not any different from the rest aside from being named __main__ instead of its file name

imports can get complicated, especially circular ones which is to be avoided if it can be helped.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.