How can one use type comments in Python to change or narrow the type of an already declared variable, in such a way as to make pycharm
or other type-aware systems understand the new type.
For instance, I might have two classes:
class A:
is_b = False
...
class B(A):
is_b = True
def flummox(self):
return '?'
and another function elsewhere:
def do_something_to_A(a_in: A):
...
if a_in.is_b:
assert isinstance(a_in, B) # THIS IS THE LINE...
a_in.flummox()
As long as I have the assert
statement, PyCharm will understand that I've narrowed a_in
to be of class B, and not complain about .flummox()
. Without it, errors/warnings such as a_in has no method flummox
will appear.
The question I have is, is there a PEP 484 (or successor) way of showing that a_in
(which might have originally been of type A or B or something else) is now of type B without having the assert statement. The statement b_in : B = a_in
also gives type errors.
In TypeScript I could do something like this:
if a_in.is_b:
const b_in = <B><any> a_in;
b_in.flummox()
// or
if a_in.is_b:
(a_in as B).flummox()
There are two main reasons I don't want to use the assert line is (1) speed is very important to this part of code, and having an extra is_instance
call for every time the line is run slows it down too much, and (2) a project code style that forbids bare assert statements.