Neil_UK Neil_UK - 1 month ago 7
Python Question

Can a python module determine its filename, or what it's been imported as?

I already know that a python program can determine its file name, the most straightforward I've seen being this

import sys
name = sys.argv[0]

My question is can the code in an imported module do the same sort of thing? I'm using python 3.5.

I'm writing a large program that, for convenience and extensibility, is split up into a main section, and 'add-ons', rather like Audacity is. I'm trying to get it simple to extend and DRY, whereby an add-on module is simply added to the program directory, and the main program can pick it up and use it. I'm using a naming standard where the module file names are given a program-specific prefix to identify them, and then implement some standard-named classes and data inside.

As the main program doesn't know the names of the add-ons ahead of time, I'm importing them like this, which seems to work OK

def get_available_modules(self, prefix=""):
""" import the files named in this folder """

files = os.listdir(os.getcwd())
self.modules = {}

for file_name in files:
# print('examining ', file_name)
if file_name.startswith(prefix):
# print('this one looks OK ', file_name)
# strip the .py off the end
mod_name = file_name[:-3]
# strip prefix off the front
mod_ID = mod_name[len(prefix):]

self.modules[mod_ID] = __import__(mod_name)

# print('loaded modules ')
# for name in self.modules:
# print(name)

Having got the modules, I can then access what they do, put their descriptions into listBoxes or menues, instantiate and show their control panels, and point them at the resources they need to work on. However, for debugging the self consistency, I'd like the module to be able to determine what it's called, what its filename is. I'm going to be creating new functions by editing previous ones, and know that I won't change everything consistently.

Obviously when fire up the objects, I can also pass the mod_ID in, but that's rather like the magician being spotted putting the rabbit into the hat.

If there any parameter inside a module that makes its filename accessible to itself?


(Posted on behalf of the OP).

Duh! It's ____name____ (that's dunder name dunder, a real dunder messes with formatting!