Skip to content

Enable local partial types by default #10169

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
104 changes: 65 additions & 39 deletions mypy/checker.py

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions mypy/dmypy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ def process_start_options(flags: List[str], allow_sources: bool) -> Options:
sys.exit("dmypy: start/restart should not disable incremental mode")
if options.follow_imports not in ('skip', 'error', 'normal'):
sys.exit("dmypy: follow-imports=silent not supported")
if not options.local_partial_types:
sys.exit("dmypy: disabling local-partial-types not supported")
return options


Expand Down
2 changes: 1 addition & 1 deletion mypy/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -778,7 +778,7 @@ def add_invertible_flag(flag: str,
parser.add_argument('--semantic-analysis-only', action='store_true', help=argparse.SUPPRESS)
# --local-partial-types disallows partial types spanning module top level and a function
# (implicitly defined in fine-grained incremental mode)
parser.add_argument('--local-partial-types', action='store_true', help=argparse.SUPPRESS)
add_invertible_flag('--local-partial-types', default=False, help=argparse.SUPPRESS)
# --logical-deps adds some more dependencies that are not semantically needed, but
# may be helpful to determine relative importance of classes and functions for overall
# type precision in a code base. It also _removes_ some deps, so this flag should be never
Expand Down
2 changes: 1 addition & 1 deletion mypy/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ def __init__(self) -> None:
self.dump_deps = False
self.logical_deps = False
# If True, partial types can't span a module top level and a function
self.local_partial_types = False
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True

self.local_partial_types = True
# Some behaviors are changed when using Bazel (https://bazel.build).
self.bazel = False
# If True, export inferred types for all expressions as BuildResult.types
Expand Down
2 changes: 1 addition & 1 deletion test-data/stdlib-samples/3.2/shutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class RegistryError(Exception):
if sys.platform == "win32":
_WindowsError = WindowsError
else:
_WindowsError = None
_WindowsError = None # type: None


# Function aliases to be patched in test cases
Expand Down
2 changes: 1 addition & 1 deletion test-data/unit/check-basic.test
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ def foo(
pass

[case testNoneHasBool]
none = None
none: None = None
b = none.__bool__()
reveal_type(b) # N: Revealed type is 'builtins.bool'
[builtins fixtures/bool.pyi]
Expand Down
11 changes: 4 additions & 7 deletions test-data/unit/check-callable.test
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,6 @@ def g(o: int) -> None:
[builtins fixtures/callable.pyi]

[case testCallableTuple]

from typing import NamedTuple

Thing = NamedTuple('Thing', [('s', str), ('n', int)])
Expand All @@ -440,26 +439,24 @@ def g(o: Thing) -> None:
i, s = o
i + s # E: Unsupported operand types for + ("str" and "int")
o(1,2,3)

[builtins fixtures/callable.pyi]

[case testCallableNoArgs]

if callable(): # E: Missing positional argument "x" in call to "callable"
pass

[builtins fixtures/callable.pyi]

[case testCallableWithNoneArgs]

fn = None
fn = None # E: Need type annotation for "fn"
if callable(fn):
fn()

fn2: None = None
if callable(fn2):
fn2()
[builtins fixtures/callable.pyi]

[case testCallableUnionOfNoneAndCallable]

from typing import Union, Callable

def f() -> int:
Expand Down
1 change: 1 addition & 0 deletions test-data/unit/check-columns.test
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ y: Dict[int, int] = {
[builtins fixtures/dict.pyi]

[case testColumnCannotDetermineType]
# flags: --no-local-partial-types
(x) # E:2: Cannot determine type of 'x'
x = None

Expand Down
2 changes: 1 addition & 1 deletion test-data/unit/check-errorcodes.test
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ c = {} # E: Expected TypedDict key 'x' but found no keys [typeddict-item]
[case testErrorCodeCannotDetermineType]
y = x # E: Cannot determine type of 'x' [has-type]
reveal_type(y) # N: Revealed type is 'Any'
x = None
x = None # E: Need type annotation for "x" [var-annotated]

[case testErrorCodeRedundantCast]
# flags: --warn-redundant-casts
Expand Down
6 changes: 3 additions & 3 deletions test-data/unit/check-functions.test
Original file line number Diff line number Diff line change
Expand Up @@ -2201,7 +2201,7 @@ from typing import Callable
class A:
def f(self) -> None:
# In particular, test that the error message contains "g" of "A".
self.g() # E: Too few arguments for "g" of "A"
self.g() # E: Too few arguments for "g" of "A"
self.g(1)
@dec
def g(self, x: str) -> None: pass
Expand Down Expand Up @@ -2525,7 +2525,7 @@ reveal_type(bar(None)) # N: Revealed type is 'None'
[out]

[case testNoComplainInferredNone]
# flags: --no-strict-optional
# flags: --no-strict-optional --no-local-partial-types
from typing import TypeVar, Optional
T = TypeVar('T')
def X(val: T) -> T: ...
Expand All @@ -2540,7 +2540,7 @@ xx: Optional[int] = X(x_in)
from typing import TypeVar, Optional
T = TypeVar('T')
def X(val: T) -> T: ...
x_in = None
x_in = X(None)
def Y(x: Optional[str] = X(x_in)): ...

xx: Optional[int] = X(x_in)
Expand Down
39 changes: 18 additions & 21 deletions test-data/unit/check-inference.test
Original file line number Diff line number Diff line change
Expand Up @@ -979,7 +979,6 @@ class B: pass
[builtins fixtures/for.pyi]

[case testInferenceOfFor2]

a, b, c = None, None, None # type: (A, B, C)
for x, (y, z) in [(A(), (B(), C()))]:
b = x # Fail
Expand All @@ -1000,11 +999,11 @@ class B: pass
class C: pass
[builtins fixtures/for.pyi]
[out]
main:4: error: Incompatible types in assignment (expression has type "A", variable has type "B")
main:5: error: Incompatible types in assignment (expression has type "B", variable has type "C")
main:6: error: Incompatible types in assignment (expression has type "C", variable has type "A")
main:10: error: Need more than 2 values to unpack (3 expected)
main:12: error: '__main__.B' object is not iterable
main:3: error: Incompatible types in assignment (expression has type "A", variable has type "B")
main:4: error: Incompatible types in assignment (expression has type "B", variable has type "C")
main:5: error: Incompatible types in assignment (expression has type "C", variable has type "A")
main:9: error: Need more than 2 values to unpack (3 expected)
main:11: error: '__main__.B' object is not iterable

[case testInferenceOfFor3]

Expand Down Expand Up @@ -1525,12 +1524,14 @@ b[{}] = 1
[builtins fixtures/dict.pyi]

[case testInferDictInitializedToEmptyAndUpdatedFromMethod]
# flags: --no-local-partial-types
map = {}
def add() -> None:
map[1] = 2
[builtins fixtures/dict.pyi]

[case testInferDictInitializedToEmptyAndUpdatedFromMethodUnannotated]
# flags: --no-local-partial-types
map = {}
def add():
map[1] = 2
Expand Down Expand Up @@ -1720,7 +1721,7 @@ reveal_type(C().a) # N: Revealed type is 'builtins.dict[Any, Any]'
[builtins fixtures/dict.pyi]

[case testInferAttributeInitializedToNoneAndAssignedClassBody]
# flags: --strict-optional
# flags: --strict-optional --no-local-partial-types
class C:
a = None
def __init__(self) -> None:
Expand Down Expand Up @@ -1755,7 +1756,7 @@ reveal_type(dd) # N: Revealed type is 'builtins.dict[builtins.str, builtins.int
[builtins fixtures/dict.pyi]

[case testInferFromEmptyDictWhenUsingInSpecialCase]
d = None
d = None # E: Need type annotation for "d"
if 'x' in d: # E: "None" has no attribute "__iter__" (not iterable)
pass
reveal_type(d) # N: Revealed type is 'None'
Expand Down Expand Up @@ -1864,7 +1865,7 @@ x = 1
[out]

[case testPartiallyInitializedVariableDoesNotEscapeScope2]
x = None
x = None # E: Need type annotation for "x"
def f() -> None:
x = None
x = 1
Expand All @@ -1891,33 +1892,31 @@ main:6: error: Incompatible types in assignment (expression has type "int", vari
main:7: error: "None" not callable

[case testGlobalInitializedToNoneSetFromFunction]
# flags: --no-local-partial-types
a = None
def f():
global a
a = 42
[out]

[case testGlobalInitializedToNoneSetFromMethod]
# flags: --no-local-partial-types
a = None
class C:
def m(self):
global a
a = 42
[out]

-- More partial type errors
-- ------------------------

[case testPartialTypeErrorSpecialCase1]
# This used to crash.
class A:
x = None
x = None # E: Need type annotation for "x"
def f(self) -> None:
for a in self.x:
pass
[builtins fixtures/for.pyi]
[out]
main:5: error: "None" has no attribute "__iter__" (not iterable)

[case testPartialTypeErrorSpecialCase2]
# This used to crash.
Expand All @@ -1932,13 +1931,11 @@ main:3: error: Need type annotation for "x" (hint: "x: List[<type>] = ...")

[case testPartialTypeErrorSpecialCase3]
class A:
x = None
x = None # E: Need type annotation for "x"
def f(self) -> None:
for a in A.x:
pass
[builtins fixtures/for.pyi]
[out]
main:4: error: "None" has no attribute "__iter__" (not iterable)


-- Multipass
Expand Down Expand Up @@ -1975,7 +1972,7 @@ T = TypeVar('T')

class A:
def f(self) -> None:
self.g() # E: Too few arguments for "g" of "A"
self.g() # E: Too few arguments for "g" of "A"
self.g(1)
@dec
def g(self, x: str) -> None: pass
Expand Down Expand Up @@ -2281,9 +2278,9 @@ main:4: error: Invalid type: try using Literal[0] instead?

[case testNoCrashOnPartialMember]
class C:
x = None
x = None # E: Need type annotation for "x"
def __init__(self) -> None:
self.x = [] # E: Need type annotation for "x" (hint: "x: List[<type>] = ...")
self.x = []
[builtins fixtures/list.pyi]
[out]

Expand All @@ -2305,7 +2302,7 @@ T = TypeVar('T', bound=str)

def f() -> Tuple[T]:
...
x = None
x = None # E: Need type annotation for "x"
if int():
(x,) = f()
[builtins fixtures/tuple.pyi]
Expand Down
12 changes: 6 additions & 6 deletions test-data/unit/check-literal.test
Original file line number Diff line number Diff line change
Expand Up @@ -1326,7 +1326,7 @@ bool2 = True
bool3: bool = True

none1: Literal[None] = None
none2 = None
none2 = None # E: Need type annotation for "none2"
none3: None = None

reveal_type(int1) # N: Revealed type is 'Literal[1]'
Expand Down Expand Up @@ -1356,7 +1356,7 @@ combined: Literal[1, "foo", True, None]
a = 1
b = "foo"
c = True
d = None
d = None # E: Need type annotation for "d"

w = a # E: Incompatible types in assignment (expression has type "int", variable has type "Literal[1]")
x = b # E: Incompatible types in assignment (expression has type "str", variable has type "Literal['foo']")
Expand Down Expand Up @@ -2456,13 +2456,13 @@ from typing_extensions import Final, Literal
var1: Final = 1
var2: Final = "foo"
var3: Final = True
var4: Final = None
var4: Final = None # E: Need type annotation for "var4"

class Foo:
classvar1: Final = 1
classvar2: Final = "foo"
classvar3: Final = True
classvar4: Final = None
classvar4: Final = None # E: Need type annotation for "classvar4"

def __init__(self) -> None:
self.instancevar1: Final = 1
Expand All @@ -2487,11 +2487,11 @@ force4(reveal_type(var4)) # N: Revealed type is 'None'
reveal_type(Foo.classvar1) # N: Revealed type is 'Literal[1]?'
reveal_type(Foo.classvar2) # N: Revealed type is 'Literal['foo']?'
reveal_type(Foo.classvar3) # N: Revealed type is 'Literal[True]?'
reveal_type(Foo.classvar4) # N: Revealed type is 'None'
reveal_type(Foo.classvar4) # N: Revealed type is 'Any'
force1(reveal_type(Foo.classvar1)) # N: Revealed type is 'Literal[1]'
force2(reveal_type(Foo.classvar2)) # N: Revealed type is 'Literal['foo']'
force3(reveal_type(Foo.classvar3)) # N: Revealed type is 'Literal[True]'
force4(reveal_type(Foo.classvar4)) # N: Revealed type is 'None'
force4(reveal_type(Foo.classvar4)) # N: Revealed type is 'Any'

f = Foo()
reveal_type(f.instancevar1) # N: Revealed type is 'Literal[1]?'
Expand Down
6 changes: 3 additions & 3 deletions test-data/unit/check-optional.test
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
-- Tests for strict Optional behavior

[case testImplicitNoneType]
x = None
x = None # E: Need type annotation for "x"
x() # E: "None" not callable

[case testImplicitNoneTypeInNestedFunction]
Expand Down Expand Up @@ -315,7 +315,7 @@ def f() -> Generator[None, None, None]:
[out]

[case testNoneAndStringIsNone]
a = None
a: None = None
b = "foo"
reveal_type(a and b) # N: Revealed type is 'None'

Expand Down Expand Up @@ -627,7 +627,7 @@ x is not None and x + '42' # E: Unsupported operand types for + ("int" and "str
[case testInvalidBooleanBranchIgnored]
from typing import Optional

x = None
x: None = None
x is not None and x + 42
[builtins fixtures/isinstance.pyi]

Expand Down
7 changes: 4 additions & 3 deletions test-data/unit/check-protocols.test
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ class MyHashable(Protocol):
return 0

class C:
__my_hash__ = None
__my_hash__: None = None

var: MyHashable = C() # E: Incompatible types in assignment (expression has type "C", variable has type "MyHashable")

Expand All @@ -289,7 +289,7 @@ class P(Protocol):
x = 0 # type: int

class C:
x = None
x: None = None

x: P = C() # Error!
def f(x: P) -> None: pass
Expand Down Expand Up @@ -2083,7 +2083,7 @@ class B(Protocol):
def execute(self, stmt: Any, *args: Any, **kwargs: Any) -> None: ...
def cool(self) -> None: ...

def func1(arg: A) -> None: ...
def func1(arg: A) -> None: ...
def func2(arg: Optional[A]) -> None: ...

x: B
Expand Down Expand Up @@ -2571,6 +2571,7 @@ hh(None)


[case testPartialTypeProtocol]
# flags: --no-local-partial-types
from typing import Protocol

class Flapper(Protocol):
Expand Down
2 changes: 1 addition & 1 deletion test-data/unit/check-python2.test
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ def foo(
pass

[case testNoneHasNoBoolInPython2]
none = None
none = None # type: None
b = none.__bool__() # E: "None" has no attribute "__bool__"

[case testDictWithoutTypeCommentInPython2]
Expand Down
Loading