Skip to content Skip to sidebar Skip to footer

Load Module To Invoke Its Decorators

I have a program consistring of several modules specifying the respective web application handlers and one, specifying the respective router. The library I use can be found here. E

Solution 1:

As stated in the comments fot the question, you simply have to import the modules. As for linter complaints, those are the lesser of your problems. Linters are there to help - if they get into the way, just don't listen to them.

So, the simple way just to get your things working is, at the end of your __main__.py or __init__.py, depending on your app structure, to import explicitly all the modules that make use of the view decorator.

If you have a linter, check how to silence it on the import lines - that is usually accomplished with a special comment on the import line.

Python's introspection is fantastic, but it can't find instances of a class, or subclasses, if those are defined in modules that are not imported: such a module is just a text file sitting on the disk, like any data file.

What some frameworks offer as an approach is to have a "discovery" utility that will silently import all "py" files in the project folders. That way your views can "come into existence" without explicit imports.

You could use a function like:

import os

def discover(caller_file):
    caller_folder = os.path.dirname(caller_file)
    for current, folders, files inos.walk(caller_folder):
        if current == "__pycache__":
            continue
        for file in files:
            if file.endswith(".py"):
                __import__(os.path.join(current, file))

And call it on your main module with discover(__file__)

Post a Comment for "Load Module To Invoke Its Decorators"