Skip to content

Commit a110905

Browse files
Add __main__ as inferred value for __name__ (#2345)
1 parent 7ac9cdb commit a110905

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

ChangeLog

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ Release date: TBA
1212

1313
Refs pylint-dev/pylint#9193
1414

15+
* Add ``__main__`` as a possible inferred value for ``__name__`` to improve
16+
control flow inference around ``if __name__ == "__main__":`` guards.
17+
18+
Closes #2071
19+
1520

1621
What's New in astroid 3.0.3?
1722
============================

astroid/nodes/scoped_nodes/scoped_nodes.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,15 @@
4141
from astroid.interpreter.dunder_lookup import lookup
4242
from astroid.interpreter.objectmodel import ClassModel, FunctionModel, ModuleModel
4343
from astroid.manager import AstroidManager
44-
from astroid.nodes import Arguments, Const, NodeNG, Unknown, _base_nodes, node_classes
44+
from astroid.nodes import (
45+
Arguments,
46+
Const,
47+
NodeNG,
48+
Unknown,
49+
_base_nodes,
50+
const_factory,
51+
node_classes,
52+
)
4553
from astroid.nodes.scoped_nodes.mixin import ComprehensionScope, LocalsDictNodeNG
4654
from astroid.nodes.scoped_nodes.utils import builtin_lookup
4755
from astroid.nodes.utils import Position
@@ -346,6 +354,8 @@ def getattr(
346354

347355
if name in self.special_attributes and not ignore_locals and not name_in_locals:
348356
result = [self.special_attributes.lookup(name)]
357+
if name == "__name__":
358+
result.append(const_factory("__main__"))
349359
elif not ignore_locals and name_in_locals:
350360
result = self.locals[name]
351361
elif self.package:

tests/test_scoped_nodes.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,11 @@ def setUp(self) -> None:
7979

8080
class ModuleNodeTest(ModuleLoader, unittest.TestCase):
8181
def test_special_attributes(self) -> None:
82-
self.assertEqual(len(self.module.getattr("__name__")), 1)
82+
self.assertEqual(len(self.module.getattr("__name__")), 2)
8383
self.assertIsInstance(self.module.getattr("__name__")[0], nodes.Const)
8484
self.assertEqual(self.module.getattr("__name__")[0].value, "data.module")
85+
self.assertIsInstance(self.module.getattr("__name__")[1], nodes.Const)
86+
self.assertEqual(self.module.getattr("__name__")[1].value, "__main__")
8587
self.assertEqual(len(self.module.getattr("__doc__")), 1)
8688
self.assertIsInstance(self.module.getattr("__doc__")[0], nodes.Const)
8789
self.assertEqual(

0 commit comments

Comments
 (0)