Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
finish auditing errors in docs
- Adds an actual error to code samples where appropriate
- Fixes some grammatical issues
- Fixes some whitespace
- Removes some inconsistencies in formatting
- Fixes some illegal Python samples (ie forgetting `pass`)
  • Loading branch information
vilmibm committed May 23, 2017
commit 208ced4d34d17b89778e6eb7bfd42f4cf8cc83b5
5 changes: 3 additions & 2 deletions docs/source/basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ context results in a type check error:
def p() -> None:
print('hello')

a = p() # Type check error: p has None return value
a = p() # error: "p" does not return a value

Arguments with default values can be annotated as follows:

Expand All @@ -63,7 +63,8 @@ more stable.
1 + 'x' # No static type error (dynamically typed)

def g() -> None:
1 + 'x' # Type check error (statically typed)
1 + 'x' # Statically typed, resulting in
# error: Unsupported operand types for + ("int" and "str")

.. note::

Expand Down
2 changes: 1 addition & 1 deletion docs/source/casts.rst
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@ any operations on the result. For example:
from typing import cast, Any

x = 1
x + 'x' # Type check error
x + 'x' # error: Unsupported operand types for + ("int" and "str")
y = cast(Any, x)
y + 'x' # Type check OK (runtime error)
10 changes: 5 additions & 5 deletions docs/source/cheat_sheet.rst
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ Functions
# type: (int) -> None
pass
quux(3) # Fine
quux(__x=3) # Error
quux(__x=3) # error: Unexpected keyword argument "__x" for "quux"

# This is how you annotate a function value.
x = f # type: Callable[[int, float], float]
Expand All @@ -106,7 +106,7 @@ Functions
body=None # type: List[str]
):
# type: (...) -> bool
<code>
pass
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think it might be better to keep <code> here because if you put pass it technically doesn't typecheck. Or, perhaps, we can make the return type of the function None instead of bool.

Copy link
Collaborator

@ilinum ilinum Jul 7, 2017

Choose a reason for hiding this comment

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

Whoops, just tested it and pass does typecheck :)
I think it's okay to leave pass there then.



When you're puzzled or when things are complicated
Expand All @@ -119,7 +119,7 @@ When you're puzzled or when things are complicated
# To find out what type mypy infers for an expression anywhere in
# your program, wrap it in reveal_type. Mypy will print an error
# message with the type; remove it again before running the code.
reveal_type(1) # -> error: Revealed type is 'builtins.int'
reveal_type(1) # error: Revealed type is 'builtins.int'

# Use Union when something could be one of a few types.
x = [3, 5, "test", "fun"] # type: List[Union[int, str]]
Expand All @@ -146,8 +146,8 @@ When you're puzzled or when things are complicated
a = [4]
b = cast(List[int], a) # passes fine
c = cast(List[str], a) # passes fine (no runtime check)
reveal_type(c) # -> error: Revealed type is 'builtins.list[builtins.str]'
print(c) # -> [4] the object is not cast
reveal_type(c) # error: Revealed type is 'builtins.list[builtins.str]'
print(c) # [4] the object is not cast
Copy link
Collaborator

Choose a reason for hiding this comment

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

Perhaps, it would be good to give an indication that [4] is the output of the print statement.
Something like

print(c)  # prints [4] because the cast did not change the object's type at runtime


# TODO: explain "Need type annotation for variable" when
# initializing with None or an empty container
Expand Down
14 changes: 6 additions & 8 deletions docs/source/cheat_sheet_py3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ Python 3 introduces an annotation syntax for function declarations in `PEP 3107
def quux(__x: int) -> None:
pass
quux(3) # Fine
quux(__x=3) # Error
quux(__x=3) # error: Unexpected keyword argument "__x" for "quux"

# This is how you annotate a function value.
x = f # type: Callable[[int, float], float]
Expand Down Expand Up @@ -113,7 +113,7 @@ When you're puzzled or when things are complicated
# To find out what type mypy infers for an expression anywhere in
# your program, wrap it in reveal_type. Mypy will print an error
# message with the type; remove it again before running the code.
reveal_type(1) # -> error: Revealed type is 'builtins.int'
reveal_type(1) # error: Revealed type is 'builtins.int'

# Use Union when something could be one of a few types.
x = [3, 5, "test", "fun"] # type: List[Union[int, str]]
Expand All @@ -139,8 +139,8 @@ When you're puzzled or when things are complicated
a = [4]
b = cast(List[int], a) # passes fine
c = cast(List[str], a) # passes fine (no runtime check)
reveal_type(c) # -> error: Revealed type is 'builtins.list[builtins.str]'
print(c) # -> [4] the object is not cast
reveal_type(c) # error: Revealed type is 'builtins.list[builtins.str]'
print(c) # [4] the object is not cast
Copy link
Collaborator

Choose a reason for hiding this comment

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

See comment for py2 cheatsheet.


# TODO: explain "Need type annotation for variable" when
# initializing with None or an empty container
Expand Down Expand Up @@ -190,8 +190,6 @@ Classes
def my_method(self, num: int, str1: str) -> str:
return num * str1



# User-defined classes are written with just their own names.
x = MyClass() # type: MyClass

Expand Down Expand Up @@ -228,7 +226,7 @@ Other stuff

# forward references are useful if you want to referemce a class before it is designed

def f(foo: A) -> int: # this will fail
def f(foo: A) -> int: # this will fail at runtime
...

class A:
Expand All @@ -253,7 +251,7 @@ Mypy brings limited support for PEP 526 annotations.
name: str = "Eric Idle"

# class instances can be annotated as follows
mc : MyClass = MyClass()
mc: MyClass = MyClass()

# tuple packing can be done as follows
tu: Tuple[str, ...] = ('a', 'b', 'c')
Expand Down
17 changes: 10 additions & 7 deletions docs/source/class_basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,19 @@ initialized within the class. Mypy infers the types of attributes:

a = A(1)
a.x = 2 # OK
a.y = 3 # Error: A has no attribute y
a.y = 3 # error: "A" has no attribute "y"

This is a bit like each class having an implicitly defined
``__slots__`` attribute. This is only enforced during type
checking and not when your program is running.

You can declare types of variables in the class body explicitly using
a type comment:
You can declare types of variables in the class body explicitly in the same way
as variables outside of a class body by using a type comment:

.. code-block:: python

class A:
x = None # type: List[int] # Declare attribute x of type List[int]
x = None # type: List[int]

a = A()
a.x = [1] # OK
Expand Down Expand Up @@ -58,7 +58,7 @@ to it explicitly using ``self``:
def __init__(self) -> None:
self.y = 1 # Define y
a = self
a.x = 1 # Error: x not defined
a.x = 1 # error: "A" has no attribute "x"

Overriding statically typed methods
***********************************
Expand All @@ -68,16 +68,19 @@ override has a compatible signature:

.. code-block:: python




class A:
def f(self, x: int) -> None:
...

class B(A):
def f(self, x: str) -> None: # Error: type of x incompatible
def f(self, x: str) -> None: # error: Argument 1 of "f" incompatible with supertype "A"
...

class C(A):
def f(self, x: int, y: int) -> None: # Error: too many arguments
def f(self, x: int, y: int) -> None: # error: Signature of "f" incompatible with supertype "A"
...

class D(A):
Expand Down
15 changes: 9 additions & 6 deletions docs/source/dynamic_typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ dynamically typed by defining it explicitly with the type ``Any``:

s = 1 # Statically typed (type int)
d = 1 # type: Any # Dynamically typed (type Any)
s = 'x' # Type check error
s = 'x' # error: Incompatible types in assignment
# (expression has type "str", variable has type "int")
d = 'x' # OK

Operations on Any values
Expand Down Expand Up @@ -74,11 +75,13 @@ operations:
.. code-block:: python

def f(o: object) -> None:
o.foo() # Error!
o + 2 # Error!
open(o) # Error!
n = 1 # type: int
n = o # Error!
o.foo() # error: "object" has no attribute "foo"
o + 2 # error: Unsupported operand types for + ("object" and "int")
open(o) # error: Argument 1 to "open" has incompatible type "object";
# expected "Union[str, bytes, int, _PathLike[Any]]"
n = 1 # type: int
n = o # error: Incompatible types in assignment
# (expression has type "object", variable has type "int")

You can use ``cast()`` (see chapter :ref:`casts`) or ``isinstance`` to
go from a general type such as ``object`` to a more specific
Expand Down
18 changes: 10 additions & 8 deletions docs/source/generics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Using ``Stack`` is similar to built-in container types:
stack = Stack[int]()
stack.push(2)
stack.pop()
stack.push('x') # Type error
stack.push('x') # error: Argument 1 to "push" of "Stack" has incompatible type "str"; expected "int"

Type inference works for user-defined generic types as well:

Expand Down Expand Up @@ -335,7 +335,8 @@ Let us illustrate this by few simple examples:
.. code-block:: python

class Shape:
pass
...

class Circle(Shape):
def rotate(self):
...
Expand All @@ -345,7 +346,7 @@ Let us illustrate this by few simple examples:

my_things: List[Circle] = []
add_one(my_things) # This may appear safe, but...
my_things[0].rotate() # ...this will fail
my_things[0].rotate() # error: Argument 1 to "add_one" has incompatible type List[Circle]; expected List[Shape]

Another example of invariant type is ``Dict``, most mutable containers
are invariant.
Expand Down Expand Up @@ -402,14 +403,14 @@ argument types:

concat('a', 'b') # Okay
concat(b'a', b'b') # Okay
concat(1, 2) # Error!
concat(1, 2) # error: Type argument 1 of "concat" has incompatible value "int"

Note that this is different from a union type, since combinations
of ``str`` and ``bytes`` are not accepted:

.. code-block:: python

concat('string', b'bytes') # Error!
concat('string', b'bytes') # error: Type argument 1 of "concat" has incompatible value "object"

In this case, this is exactly what we want, since it's not possible
to concatenate a string and a bytes object! The type checker
Expand All @@ -418,7 +419,7 @@ will reject this function:
.. code-block:: python

def union_concat(x: Union[str, bytes], y: Union[str, bytes]) -> Union[str, bytes]:
return x + y # Error: can't concatenate str and bytes
return x + y # error: Unsupported operand types for + (likely involving Union)

Another interesting special case is calling ``concat()`` with a
subtype of ``str``:
Expand Down Expand Up @@ -481,7 +482,8 @@ above,

largest_in_absolute_value(-3.5, 2) # Okay, has type float.
largest_in_absolute_value(5+6j, 7) # Okay, has type complex.
largest_in_absolute_value('a', 'b') # Error: 'str' is not a subtype of SupportsAbs[float].
largest_in_absolute_value('a', 'b') # error: Type argument 1 of "largest_in_absolute_value" has
# incompatible value "str"

Type parameters of generic classes may also have upper bounds, which
restrict the valid values for the type parameter in the same way.
Expand Down Expand Up @@ -526,7 +528,7 @@ regardless of that signature. Here's a complete example:
reveal_type(a) # str
b = bar(3.14, 0)
reveal_type(b) # Tuple[float, float, bool]
foo('x') # Type check error: incompatible type "str"; expected "int"
foo('x') # error: Argument 1 to "foo" has incompatible type "str"; expected "int"

From the final block we see that the signatures of the decorated
functions ``foo()`` and ``bar()`` are the same as those of the original
Expand Down
Loading