How to write an importing function?

python import function from file
python functions
python-import all functions from file
how to import a function from a python script
python export function
create a module that will import the above functions and run those functions from within the file
import function from py
import python

I am working on a group project of mine and every part of the code is quite messy. I want to improve readability of the imports. In my opinion 20 lines of messy imports hurts the main structure of the code.

So here is a part of the imports:

import datetime
import os
import json
import re
import psycopg2 as dbapi2
from datetime import datetime
from datetime import date
from flask import Flask, jsonify
from flask import redirect

And I want to import all of these with something like:

import importLibs

And for this I tried the solution from How to make global imports from a function? and came up with this:

def importLibs():
    globals()['datetime'  ]       = __import__('datetime'         )
    globals()['os'        ]       = __import__('os'               )
    globals()['json'      ]       = __import__('json'             )
    globals()['re'        ]       = __import__('re'               )
    globals()['dbapi2'    ]       = __import__('psycopg2'         )
    globals()['date'      ]       = __import__('datetime'         )
    globals()['Flask'     ]       = __import__('flask.Flask'      )
    globals()['jsonify'   ]       = __import__('flask.jsonify'    )
    globals()['redirect'  ]       = __import__('flask.redirect'   )

But it fails with:

ModuleNotFoundError: No module named 'flask.Flask'

Warning: What you're doing is almost certainly a bad idea.

The reason for the error is that flask.Flask is a class, not a module.

If you really have to do this, you might try:


However, this seriously hurts your code's readability.

By having the imports laid out at the top of your module, you can immediately see what your code is using. By moving it into a separate file, you're hiding your code's dependencies and making it much harder to understand what's going on.

Putting imports at the top of a file is standard practice in every language I can think of. Consider what somebody is going to think when they see this. Why have they done it this way? That looks really complicated. Is there something I'm missing? Why didn't they just use import statements like everyone else?

By the time they've figured out what you're doing, they've wasted 5 minutes of their time. It's a distraction.

Finally, remember that the more complicated you make your code, the more space there is for bugs to creep in!

Export and Import, There is also a function-like dynamic import() , which does not require scripts of type="module" . Backward compatibility can be ensured  Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

First, the idiomatic Python ("pythonic") style is to use the 20 lines of explicit import statements. Static analysis tools tend to function better if you don't try to circumvent the normal import mechanisms. Some IDEs like PyCharm can keep them sorted for you.

Dynamic imports like that are much harder to understand without actually running the code.

That said, some libraries do use runtime imports like this. Sometimes what you need to import depends on runtime conditions, so and it's worth learning how dynamic imports work.

Second, the __import__ builtin is not generally recommended because it doesn't handle the . for you when modules are nested. Use importlib.import_module instead. But in the case of Flask, it's not a module, but a class, so use import_module('flask').Flask.

Third, modules are not callable. You can't simply import something and call it, like you suggest.

import importLibs

instead it should be something like

from my_imports import importLibs

It is possible to place arbitrary objects into the import cache by mutating sys.modules, so you could make a direct import callable that way. Modules have been known to replace themselves with other things on import like that. Please use responsibly, as this is again harder to reason about without actually running the code.

Fourth, the globals() function refers to the globals of the defining module. Not the module it was called in. So you can't just from my_imports import importLibs and then expect it to import things into the current module. They'll go inside the my_imports module instead. There are at least two ways to deal with this.

One is to add some kind of globals_dict parameter to the function and set the globals on that instead of globals(). Then you'd call it like importLibs(globals()). This way it will use the globals dict from the calling module instead of the defining (my_imports) module.

The other way is to use the inspect module to go up a stack frame and find the caller's module to get its globals. This way you won't have to pass it in explicitly and can just use importLibs(). But this kind of automagic is more brittle and can break if you somehow call it indirectly inside a different module.

Another option is to import everything into your third module my_imports, provide an __all__ there and then use

from my_imports import *

And if you manage your global namespace carefully, you don't even need the __all__. Star imports are discouraged, because explicit imports are easier to reason about statically, but some libraries do work this way.

And finally, you could make a module with a short name, import everything there and then just access things via . from that everywhere, like

import my


Again, some libraries work this way, like tk.

import, We can define this function in a module then import it into the various programs without having to copy its code each time. In this article, we will see how to create​  We use the import keyword to do this. To import our previously defined module example, we type the following in the Python prompt. >>> import example. This does not import the names of the functions defined in example directly in the current symbol table. It only imports the module name example there.

Don't solve a problem that doesn't exist.

Every Python programmer already knows exactly what to expect with imports. That hacky importLibs() function just adds an extra level of indirection and needless complexity.

You should follow the standard guidance for imports given in PEP8:

For the specific imports in question, you might want to alphabetize and separate external modules from standard library modules. Besides that, just leave them alone.

The following is a slight cleanup that looks perfectly readable (and standard):

import datetime
import json
import os
import re
from datetime import date

import psycopg2 as dbapi2
from flask import Flask, jsonify, redirect

Creating and Importing Modules in Python, In the example below, math module is imported into the program so that you can use sqrt() function defined in it. import math #You need to put this  Most often, you should include a header containing the function prototypes; it is possible to include code files, but not commonly needed or always safe. To do this, you should provide two files, a header and a source file, for your functions. The header will read something like: #pragma once void Function(int arg); and the source:

Working with Modules in Python, Call the functions defined in the imported file. The above approach has been used in the below examples: Example 1: A Python file is created and it  Java has an import statement that allows you to import an entire package (as in earlier examples), or use only certain classes and interfaces defined in the package. The general form of import statement is: import; // To import a certain class only import* // To import the whole package For example,

Python - Call function from another file, Import in python is similar to #include header_file in C/C++. The value returned by the function are then reflected in the output of the initial code. If you like GeeksforGeeks and would like to contribute, you can also write an article using  You can do this in 2 ways. First is just to import the specific function you want from To do this use. from file import function Another way is to import the entire file. import file as fl Then you can call any function inside using. fl.function(a,b)

Import module in Python, This does not import the names of the functions defined in example directly in the current symbol table. It only imports the  Importing data in MATLAB means loading data from an external file. The importdata function allows loading various data files of different formats. It has the following five forms −. Sr.No. Function & Description. 1. A = importdata (filename) Loads data into array A from the file denoted by filename. 2.