Call function from another file without import clause?

Viewed 2139

Is is possible to call a function from another file without placing from import clause? I'd like to write Python code shorter and cleaner here, so I'm curious if there is a way to do that.

For example, usually we write like this and this works:

from tmpapp.forms import KakikomiForm

def kakikomi(request):
    f = KakikomiForm()

I'd like to write something like this if possible, but this will be error:

# from tmpapp.forms import KakikomiForm

def kakikomi(request):
    f = tmpapp.forms.KakikomiForm()
4 Answers

Without any importing this is not possible, but what you can do is, import a module, and call a function of a submodule of that module. Like this:

import tmpapp
def kakikomi(request):
    f = tmpapp.forms.KakikomiForm()

Yes, you can, in some way... You can load the module using importlib, find the function and call it. Suppose we have following project structure:

your_project/
├── some_lib
│   └── some_module.py
└── test_dyn_import.py

where some_module.py contains the function print_args we want to call without "import":

# Somewhere in some_module.py
def print_args(*argv):
    for v in argv:
        print(v)

Then helping function call_func and caller's code will be:

# test_dyn_import.py
import importlib
from inspect import isfunction

def call_func(full_module_name, func_name, *argv):
    module = importlib.import_module(full_module_name)
    for attribute_name in dir(module):
        attribute = getattr(module, attribute_name)
        if isfunction(attribute) and attribute_name == func_name:
            attribute(*argv)


call_func('some_lib.some_module', 'print_args', 'foo', 'bar', 101)

And the output will be

your_project/venv/bin/python test_dyn_import.py
foo
bar
101

If you want to use a name fully qualified, you can use import rather than from ... import.

import tmpapp.forms

def kakikomi(request):
    f = tmpapp.forms.KakikomiForm()

But the import is still strictly necessary, as it tells Python to go and physically load the file.

You can't use classes/functions from another modules(files) without importing them.

Related