Skip to content

Commit

Permalink
Add __main__ as inferred value for __name__ (#2345)
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobtylerwalls authored Dec 12, 2023
1 parent 7ac9cdb commit a110905
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
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.3?
============================
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

0 comments on commit a110905

Please # to comment.