Skip to content

Commit 858cf50

Browse files
committed
only infer Optional for func
1 parent 266040f commit 858cf50

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

mypy/stubgen.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ def visit_func_def(self, o: FuncDef) -> None:
254254
if init_stmt:
255255
if kind == ARG_NAMED and '*' not in args:
256256
args.append('*')
257-
typename = self.get_str_type_of_node(init_stmt.rvalue)
257+
typename = self.get_str_type_of_node(init_stmt.rvalue, True)
258258
arg = '{}: {} = ...'.format(name, typename)
259259
elif kind == ARG_STAR:
260260
arg = '*%s' % name
@@ -500,7 +500,8 @@ def is_private_name(self, name: str) -> bool:
500500
'__setstate__',
501501
'__slots__'))
502502

503-
def get_str_type_of_node(self, rvalue: Node) -> str:
503+
def get_str_type_of_node(self, rvalue: Node,
504+
can_infer_optional: bool = False) -> str:
504505
if isinstance(rvalue, IntExpr):
505506
return 'int'
506507
if isinstance(rvalue, StrExpr):
@@ -513,7 +514,8 @@ def get_str_type_of_node(self, rvalue: Node) -> str:
513514
return 'int'
514515
if isinstance(rvalue, NameExpr) and rvalue.name in ('True', 'False'):
515516
return 'bool'
516-
if isinstance(rvalue, NameExpr) and rvalue.name == 'None':
517+
if can_infer_optional and \
518+
isinstance(rvalue, NameExpr) and rvalue.name == 'None':
517519
self.add_typing_import('Optional')
518520
self.add_typing_import('Any')
519521
return 'Optional[Any]'

test-data/unit/stubgen.test

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -543,5 +543,17 @@ def syslog(a): pass
543543
[out]
544544
def syslog(a): ...
545545

546+
[case testInferOptionalOnlyFunc]
547+
class A:
548+
x = None
549+
def __init__(self, a=None) -> None:
550+
self.x = []
551+
[out]
552+
from typing import Any, Optional
553+
554+
class A:
555+
x = ... # type: Any
556+
def __init__(self, a: Optional[Any] = ...) -> None: ...
557+
546558
-- More features/fixes:
547559
-- do not export deleted names

0 commit comments

Comments
 (0)