Skip to content

mypy: Use "|" operator instead of Union/Optional #1345

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

Merged
merged 1 commit into from
Jun 4, 2022
Merged
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
8 changes: 6 additions & 2 deletions mesa/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@
Core Objects: Agent

"""
# Mypy; for the `|` operator purpose
# Remove this __future__ import once the oldest supported Python is 3.10
from __future__ import annotations

# mypy
from typing import Optional, TYPE_CHECKING
from typing import TYPE_CHECKING
from random import Random

if TYPE_CHECKING:
Expand All @@ -27,7 +31,7 @@ def __init__(self, unique_id: int, model: "Model") -> None:
"""
self.unique_id = unique_id
self.model = model
self.pos: Optional[Position] = None
self.pos: Position | None = None

def step(self) -> None:
"""A single step of the agent."""
Expand Down
8 changes: 6 additions & 2 deletions mesa/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@
Core Objects: Model

"""
# Mypy; for the `|` operator purpose
# Remove this __future__ import once the oldest supported Python is 3.10
from __future__ import annotations

import random

from mesa.datacollection import DataCollector

# mypy
from typing import Any, Optional
from typing import Any


class Model:
Expand Down Expand Up @@ -52,7 +56,7 @@ def next_id(self) -> int:
self.current_id += 1
return self.current_id

def reset_randomizer(self, seed: Optional[int] = None) -> None:
def reset_randomizer(self, seed: int | None = None) -> None:
"""Reset the model random number generator.

Args:
Expand Down
27 changes: 13 additions & 14 deletions mesa/space.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
# good reason to use one-character variable names for x and y.
# pylint: disable=invalid-name

# Mypy; for the `|` operator purpose
# Remove this __future__ import once the oldest supported Python is 3.10
from __future__ import annotations

import itertools
import math
from warnings import warn
Expand All @@ -26,7 +30,6 @@
Iterable,
Iterator,
List,
Optional,
Set,
Sequence,
Tuple,
Expand All @@ -48,7 +51,7 @@

Position = Union[Coordinate, FloatCoordinate, NetworkCoordinate]

GridContent = Optional[Agent]
GridContent = Union[Agent, None]
MultiGridContent = List[Agent]

F = TypeVar("F", bound=Callable[..., Any])
Expand Down Expand Up @@ -128,8 +131,8 @@ def __getitem__(self, index: int) -> List[GridContent]:

@overload
def __getitem__(
self, index: Tuple[Union[int, slice], Union[int, slice]]
) -> Union[GridContent, List[GridContent]]:
self, index: Tuple[int | slice, int | slice]
) -> GridContent | List[GridContent]:
...

@overload
Expand All @@ -138,12 +141,8 @@ def __getitem__(self, index: Sequence[Coordinate]) -> List[GridContent]:

def __getitem__(
self,
index: Union[
int,
Sequence[Coordinate],
Tuple[Union[int, slice], Union[int, slice]],
],
) -> Union[GridContent, List[GridContent]]:
index: int | Sequence[Coordinate] | Tuple[int | slice, int | slice],
) -> GridContent | List[GridContent]:
"""Access contents from the grid."""

if isinstance(index, int):
Expand Down Expand Up @@ -436,7 +435,7 @@ def is_cell_empty(self, pos: Coordinate) -> bool:
return self.grid[x][y] == self.default_val()

def move_to_empty(
self, agent: Agent, cutoff: float = 0.998, num_agents: Optional[int] = None
self, agent: Agent, cutoff: float = 0.998, num_agents: int | None = None
) -> None:
"""Moves agent to a random empty cell, vacating agent's old cell."""
if len(self.empties) == 0:
Expand Down Expand Up @@ -478,7 +477,7 @@ def move_to_empty(
self._place_agent(agent, new_pos)
agent.pos = new_pos

def find_empty(self) -> Optional[Coordinate]:
def find_empty(self) -> Coordinate | None:
"""Pick a random empty cell."""
import random

Expand Down Expand Up @@ -509,7 +508,7 @@ class SingleGrid(Grid):
empties: Set[Coordinate] = set()

def position_agent(
self, agent: Agent, x: Union[int, str] = "random", y: Union[int, str] = "random"
self, agent: Agent, x: int | str = "random", y: int | str = "random"
) -> None:
"""Position an agent on the grid.
This is used when first placing agents! Use 'move_to_empty()'
Expand Down Expand Up @@ -781,7 +780,7 @@ def __init__(
self.size = np.array((self.width, self.height))
self.torus = torus

self._agent_points: Optional[npt.NDArray[FloatCoordinate]] = None
self._agent_points: npt.NDArray[FloatCoordinate] | None = None
self._index_to_agent: Dict[int, Agent] = {}
self._agent_to_index: Dict[Agent, int] = {}

Expand Down
8 changes: 6 additions & 2 deletions mesa/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,14 @@
model has taken.
"""

# Mypy; for the `|` operator purpose
# Remove this __future__ import once the oldest supported Python is 3.10
from __future__ import annotations

from collections import OrderedDict, defaultdict

# mypy
from typing import Dict, Iterator, List, Optional, Union, Type
from typing import Dict, Iterator, List, Type, Union
from mesa.agent import Agent
from mesa.model import Model

Expand Down Expand Up @@ -163,7 +167,7 @@ class StagedActivation(BaseScheduler):
def __init__(
self,
model: Model,
stage_list: Optional[List[str]] = None,
stage_list: List[str] | None = None,
shuffle: bool = False,
shuffle_between_stages: bool = False,
) -> None:
Expand Down