Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix complex __import__ statements failing to parse with Python 2.7 - 3.7 #14232

Merged
merged 2 commits into from Jan 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -353,6 +353,7 @@ def test_works_with_python2(rule_runner: RuleRunner) -> None:

__import__(u"pkg_resources")
__import__(b"treat.as.a.regular.import.not.a.string.import")
__import__(u"{}".format("interpolation"))

importlib.import_module(b"dep.from.bytes")
importlib.import_module(u"dep.from.str")
Expand All @@ -375,13 +376,13 @@ def test_works_with_python2(rule_runner: RuleRunner) -> None:
"project.demo.Demo": ImpInfo(lineno=5, weak=False),
"pkg_resources": ImpInfo(lineno=7, weak=False),
"treat.as.a.regular.import.not.a.string.import": ImpInfo(lineno=8, weak=False),
"dep.from.bytes": ImpInfo(lineno=10, weak=True),
"dep.from.str": ImpInfo(lineno=11, weak=True),
"dep.from.str_狗": ImpInfo(lineno=12, weak=True),
"weak1": ImpInfo(lineno=16, weak=True),
"strong1": ImpInfo(lineno=17, weak=False),
"strong2": ImpInfo(lineno=18, weak=False),
"strong3": ImpInfo(lineno=19, weak=False),
"dep.from.bytes": ImpInfo(lineno=11, weak=True),
"dep.from.str": ImpInfo(lineno=12, weak=True),
"dep.from.str_狗": ImpInfo(lineno=13, weak=True),
"weak1": ImpInfo(lineno=17, weak=True),
"strong1": ImpInfo(lineno=18, weak=False),
"strong2": ImpInfo(lineno=19, weak=False),
"strong3": ImpInfo(lineno=20, weak=False),
},
)

Expand Down
Expand Up @@ -132,11 +132,10 @@ def visit_Call(self, node):
# to explicitly mark namespace packages. Note that we don't handle more complex
# uses, such as those that set `level`.
if isinstance(node.func, ast.Name) and node.func.id == "__import__" and len(node.args) == 1:
name = None
if sys.version_info[0:2] < (3, 8) and isinstance(node.args[0], ast.Str):
name = node.args[0].s
elif isinstance(node.args[0], ast.Constant):
name = str(node.args[0].value)
if sys.version_info[0:2] < (3, 8):
name = node.args[0].s if isinstance(node.args[0], ast.Str) else None
else:
name = node.args[0].value if isinstance(node.args[0], ast.Constant) else None

if name is not None:
lineno = node.args[0].lineno
Expand Down