1

My goal is to define a function that gets a relative path and returns an absolute path. The issue is that I want this function to be located in a specific module and that other modules will be able to use it.

If the function would be located in each module (and not being imported) it would have looked something like this:

import os

def get_absolute(relative):
    dir_path = os.path.dirname(os.path.realpath(__file__))
    return os.path.abspath(os.path.join(dir_path, relative_path))

absolute = get_absolute('../file.txt')

but if I want to define this function once (in one module) and be able to import it by other modules I will need to add another argument to the function for the directory path of the module that imported the function like so:

helper.py

import os

def get_absolute(relative, dir_path):
    return os.path.abspath(os.path.join(dir_path, relative_path))

importer.py

import os
from helper import get_absolute

DIR_PATH = os.path.dirname(os.path.realpath(__file__))
absolute = get_absolute('../file.txt', DIR_PATH)

I saw Get path of importing module but in my case the module is unknown (multiple modules can import this function).
Is there a way for the helper module to know the directory path of the importing module without passing it as an argument?

MaterialZ
  • 321
  • 1
  • 12

0 Answers0