Search code examples
pythonmypypython-typingpython-polars

How to avoid Mypy Incompatible type warnings in Chained when/then assignments?


I have the following code

expr = pl.when(False).then(None)

for pattern, replacement in replacement_rules.items():
    expr = expr.when(pl.col("data").str.contains(pattern))
    expr = expr.then(pl.lit(replacement))
   
expr = expr.when(pl.col("ISO_codes").str.len_chars() > 0)
expr = expr.then(            
    pl.col("ISO_codes")
      .replace(iso_translation, default="Unknown ISO Code")
)

The code works as intended, but Mypy is not too happy about it: enter image description here

I cannot understand how get rid of the warnings without losing all "Incompatible type" warnings,or rewrite the code to make it go away.


Solution

  • Explicitly type-hint expr as Any:

    expr: Any = pl.when(False).then(None)
    

    ...or a union, whichever suits you:

    expr: ChainedWhen | Then = pl.when(False).then(None)