Zack Yoshyaro
Zack Yoshyaro

Reputation: 2124

Is there a way to get the name of the 'parent' module from an imported module?

I'm curious if it's possible to access the name of the parent module that some other module is imported into.

For instance, if I have a module (moduleA) and a parent is module, foo.py, into which it will be imported into, is it possible for moduleA to know where foo is located ?

ModuleA

def print_parent_module(): 
    os.path.asbpath(#somehow access filename of parent module) 

foo.py

import moduleA 

print moduleA.print_parent_module()
>>> "foo.py"

Upvotes: 12

Views: 18353

Answers (4)

jmcgrath207
jmcgrath207

Reputation: 2087

Here is something I came with to store a parent's method name and variables to be recalled later in the class with a decorator.

import inspect
from functools import wraps

def set_reuse_vars(method):
    @wraps(method)
    def _impl(self, *method_args, **method_kwargs):
        func_current = inspect.currentframe()
        self.recall_func = dict()
        self.recall_func['method_kwargs'] = func_current.f_locals['method_kwargs']
        self.recall_func['method_name'] = func_current.f_locals['method'].__name__
        return method(self, *method_args, **method_kwargs)
    return _impl

class APIData(object):

    def __init__(self):
        self.client = None
        self.response = None
        self.recall_func = None

    def get_next_page(self):
        # Takes a pageToken to return the next result
        get_func = getattr(self, self.recall_func['method_name'])
        self.recall_func['method_kwargs']['pageToken'] = self.response['nextPageToken']
        return get_func(**self.recall_func['method_kwargs'])

    @set_reuse_vars
    def search_list_by_keyword(self, **kwargs):

        self.response = self.client.search().list(
            **kwargs
        ).execute()

        return self.response

script to run it.

api_data = APIData()


results = api_data.search_list_by_keyword(
                       part='snippet',
                       maxResults=25,
                       order='date')


print(results)

resultsTwo = api_data.get_next_page()

print(resultsTwo)

Upvotes: 0

Dorian B.
Dorian B.

Reputation: 1299

I ran into a similar issue. You could make use of __name__:

parent_name = '.'.join(__name__.split('.')[:-1])

Or if you try to access the module directly (not the OP's question but related), see my answer in Is there a way to access parent modules in Python

Upvotes: 8

Zack Yoshyaro
Zack Yoshyaro

Reputation: 2124

Figured it out!

A little import statement inside of the function can give access to the module name.

moduleA

def print_module_name():
    import sys
    return sys.argv[0]

Then, inside the "parent" module

# foo.py
import os 
import moduleA

if __name__ == '__main__':
    print os.path.split(moduleA.print_module_name())[-1]

Gives:

>>> 'foo.py'

Upvotes: -3

Shashank
Shashank

Reputation: 13869

No. Imported modules do not hold any form of state which stores data related to how they are imported.

I think the better question is, why would you even want to do it this way? You're aware that if foo.py is indeed your __main__ then you can easily get the name foo.py out of it (by using sys.argv)? And if foo.py is an imported module instead, then you obviously already know the name of foo.py and its location, etc. at the time that you import it.

Upvotes: 1

Related Questions