Programming languages allows programmers to keep their codes in different files and then use them in a program by importing them.
If you are from C / C++ background, you might be familiar with #include statements. These are import statements that import libraries consisting of methods that can be used in a program.
Similarly, python provides import statements for importing modules in Python. These can be used to import methods in the current program for usage.
Python allows you to import files in different ways,
- Importing the module (or file): A python module can be fully imported to a program for usage using import statements. To access the method of this imported file we need to use the dot " . "
- Importing the modules functions: You can alternately import the function of the module in case you need only some specific function and loading the rest might slow down the application. This is done by using the following statement.
from fileName import function(s)
- You can select all functions also using the above method by using ' * ' instead of the function names. Importing like this will eliminate the usage of dot while calling, you can call the function directly.
Program 1: Program to see importing by importing the whole file
Files to be imported
File: mycheck.py
File: mymath.py
Main file:
Output:
Program 2: Importing using from - import statement using *
Output:
Program 3: Importing files using from-import statement, importing specific functions only
need an explanation for this answer? contact us directly to get an explanation for this answer