fish2000
fish2000

Reputation: 4435

How to inspect Python file/module information without using `__file__` — perhaps in a module-level `__getattr__(…)` function?

I have a utility package for Python projects I maintain and use. It’s a bundle of lightweight, common, junk-drawer tools (e.g. command parsing, app lifecycle management, document generation, &c &c). Currently, using this stuff is all very simple in one’s own project, but most modules written to work with it require this very irritating bit of boilerplate, like so:


from myproject.exporting import Exporter

# This is the irritating part:
exporter = Exporter(path=__file__)
export = exporter.decorator()

@export
def public_function(…):
    """ This function has been exported, and is public. """
    ...

def private_function(…):
    """ This function is private. """
    ...

# This bit does not really bother me:
__all__, __dir__ = exporter.all_and_dir()

This exporter interface lets one label classes, functions (even lambdas!) as public. These get added to generated module __all__ and __dir__(…) values, but the whole thing assists with documentation generation and other introspective things. This is besides the point, though, which is: having to do this hacky instatiation with a __file__ value is an eyesore. Linters hate __file__, so do most human Python programmers (including myself) and in general it feels like an unstable and antiquated way of doing things.

Is there a way of getting the value of __file__ in another manner? I am looking for a way to surface this datum via some other (hopefully less fragile) route.

My immediate thought is to have a module-level __getattr__(…) function, as I have had good results using these to provide instances of things on import – but, regardless of whether module __getattr__(…) is the best tool or not in this case, I am not sure about which Python introspection facilities would be warranted in their use.

Also, this answer has the basic info on the __file__ value, for those who are curious.

Upvotes: 0

Views: 140

Answers (0)

Related Questions