Skip to content
New issue

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

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

Already on GitHub? # to your account

Add "__main__" as inferred value for __name__ #2345

Merged
merged 1 commit into from
Dec 12, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ Release date: TBA

Refs pylint-dev/pylint#9193

* Add ``__main__`` as a possible inferred value for ``__name__`` to improve
control flow inference around ``if __name__ == "__main__":`` guards.

Closes #2071


What's New in astroid 3.0.2?
============================
Expand Down
12 changes: 11 additions & 1 deletion astroid/nodes/scoped_nodes/scoped_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,15 @@
from astroid.interpreter.dunder_lookup import lookup
from astroid.interpreter.objectmodel import ClassModel, FunctionModel, ModuleModel
from astroid.manager import AstroidManager
from astroid.nodes import Arguments, Const, NodeNG, Unknown, _base_nodes, node_classes
from astroid.nodes import (
Arguments,
Const,
NodeNG,
Unknown,
_base_nodes,
const_factory,
node_classes,
)
from astroid.nodes.scoped_nodes.mixin import ComprehensionScope, LocalsDictNodeNG
from astroid.nodes.scoped_nodes.utils import builtin_lookup
from astroid.nodes.utils import Position
Expand Down Expand Up @@ -346,6 +354,8 @@ def getattr(

if name in self.special_attributes and not ignore_locals and not name_in_locals:
result = [self.special_attributes.lookup(name)]
if name == "__name__":
result.append(const_factory("__main__"))
elif not ignore_locals and name_in_locals:
result = self.locals[name]
elif self.package:
Expand Down
4 changes: 3 additions & 1 deletion tests/test_scoped_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,11 @@ def setUp(self) -> None:

class ModuleNodeTest(ModuleLoader, unittest.TestCase):
def test_special_attributes(self) -> None:
self.assertEqual(len(self.module.getattr("__name__")), 1)
self.assertEqual(len(self.module.getattr("__name__")), 2)
self.assertIsInstance(self.module.getattr("__name__")[0], nodes.Const)
self.assertEqual(self.module.getattr("__name__")[0].value, "data.module")
self.assertIsInstance(self.module.getattr("__name__")[1], nodes.Const)
self.assertEqual(self.module.getattr("__name__")[1].value, "__main__")
self.assertEqual(len(self.module.getattr("__doc__")), 1)
self.assertIsInstance(self.module.getattr("__doc__")[0], nodes.Const)
self.assertEqual(
Expand Down