Skip to content

Commit

Permalink
Update type hint readme for return any cases (#1211)
Browse files Browse the repository at this point in the history
  • Loading branch information
petechd authored Sep 25, 2023
1 parent 7c8e9d9 commit 9d76ffe
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion doc/python-type-hinting.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ of a file, it silences all errors in the file:
# type: ignore
```

`# type: ignore` should only be used when unavoidable. Ensure that a comment is added to explain why it has been used and have a prefix of `Type ignore:`
`# type: ignore` should only be used when unavoidable (or in the return `Any` case detailed below). Ensure that a comment is added to explain why it has been used and have a prefix of `Type ignore:`

```python
def format_number(number: int) -> str:
Expand All @@ -147,6 +147,45 @@ def format_number(number: int) -> str:
return formatted_number
```

The `warn_return_any` flag is turned on to force type hinting the return types for third party libraries and increase the safety of the code base.

Where type hints aren’t specific enough to identify the return type (e.g. objects like blocks where some keys correspond to strings, others to lists, others to dicts) mypy will complain if you assume the type of any attribute:

```python
def get_id_from_block(block: dict) -> str:
return block["id"] # Returning Any from function declared to return "str"
```

A type ignore can be avoided here, by changing the code to this...

```python
def get_id_from_block(block: dict) -> str:
block_id: str = block["id"]
return block_id
```

...but as this is a common pattern in a number of places, it results in a lot of duplicating the return type, and extra lines of code for the sake of type hinting. In this scenario, it is ok to type ignore it.

If the value was needed for any other checks e.g.

```python
def get_first_answer_from_block(block: dict) -> str:
answer = ...
if answer["id"] ... :
...
return answer
```

This would not be suitable to type ignore, and it should use the existing convention of typing the unknown variable:

```python
def get_first_answer_from_block(block: dict) -> str:
answer: Answer = ...
if answer["id"] ... :
...
return answer
```

## ParamSpec

Use to forward the parameter types of one callable to another callable.
Expand Down

0 comments on commit 9d76ffe

Please sign in to comment.