Use of # type : in mypy

I just came across this code:

class Batch:
    def __init__(self, ref: str, sku: str, qty: int, eta: Optional[date]):
        self.reference = ref
        self.sku = sku
        self.eta = eta
        self._purchased_quantity = qty
        self._allocations = set()  # type: Set[OrderLine]

I take it that last line is to do with mypy, but I’m not sure how it works. Could it not simply be this?

class Batch:
    def __init__(self, ref: str, sku: str, qty: int, eta: Optional[date]):
        ...
        self._allocations: Set[OrderLine] = set()

Yes, it could be that!

The most common reason you’ll see a # type: comment is because when it was written the code needed to support Python 3.5. The syntax for variable annotations was only introduced in Python 3.6, by PEP 526 – Syntax for Variable Annotations | peps.python.org

2 Likes

I thought it might be a historical thing. Thanks for letting me know.