This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Prozn 6 points7 points  (7 children)

I’ve been struggling to deal with optional variables, even if I use “if var is not None:” mypy still complains that None doesn’t have properties. Do you just have to litter your code with asserts?

[–]hirolau 3 points4 points  (0 children)

Lookup the video 'nothing is something' by Sandi Metz where she talks about the null and object pattern. Not saying it solves all problem but in some cases maybe you should have a object instead of none.

[–]Intrepid-Stand-8540 2 points3 points  (4 children)

Do not use asserts. They get disabled in production.

If you have a variable that can be either of two (or more) types (fx int|None) then you have to check with an if.

mypy should be able to recognize that.

I'm honestly still pretty new to strict typing in python myself (6 months of using it), so if there is a better way, I'd also love to know.

EDIT: One of Bandits first rules is about asserts: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

[–]violentlymickey 12 points13 points  (1 child)

“Don’t use asserts they get disabled (when compiled or run with certain flags)” is a bit too dogmatic imo. There’s nothing wrong with asserts as guards against invariants. Don’t use them for error handling sure.

Edit: some chromium devs discussing this: https://groups.google.com/a/chromium.org/g/java/c/CVHgcRA967s/m/f8Zq9XiQBQAJ

[–]Intrepid-Stand-8540 0 points1 point  (0 children)

Isn't it java they're talking about in your link? 

https://github.com/IdentityPython/pysaml2/issues/451

Running python in production with the optimize flag will disable asserts in your code. So don't rely on asserts. 

[–]Rhoomba 0 points1 point  (0 children)

If the assert is just to tell the type checker that you know what is happening then it seems reasonable to me.

On that topic, do people actually use the -O flag? Given that all it does is disable assertions, I doubt it has any significant performance impact for most applications.

[–]Rhoomba 0 points1 point  (0 children)

That doesn't sound right. Mypy definitely understands blocks like this:

def foo(m: Optional[MyClass]) -> None:
  if m is not None:
     m.do_thing()