astroid icon indicating copy to clipboard operation
astroid copied to clipboard

no inference for call whose containing module is imported relatively

Open ltcmelo opened this issue 3 years ago • 3 comments

version: 2.4.2

Consider this project structure:

project
    |__ app.py
    |__ lib.py

And lib.py is as follows:

def setup():
    pass

There appears to exist a bug in the inference with relative from … import of lib.py. Nothing is inferred for setup() in the snippet below.

from .lib import setup

def f():
    setup()  # bad

If the relative import is replaced by an absolute one (assume the directory is in sys path), the inference works as expected for setup().

from lib import setup

def f():
    setup()  # good

A possible cause of this error is the level not being taken into account here.

ltcmelo avatar Nov 03 '20 14:11 ltcmelo

@ltcmelo thanks for the report.

hippo91 avatar Nov 17 '20 18:11 hippo91

i got this to work in the latest astroid. just had to do this:

astroid.parse(open(fp, encoding="utf8").read(), module_name=derive_module_name(fp), path=fp)

as long as the derived module name is correct.... everything worked fine with relative imports

earonesty avatar Oct 29 '21 17:10 earonesty

for posterity, my crappy module name function was this:

def derive_module_name(fp):
    fp = os.path.splitext(fp)[0]
    fp = fp.replace("/", ".")
    fp = fp.replace("\\", ".")
    return fp

earonesty avatar Oct 29 '21 17:10 earonesty