简体   繁体   中英

How do I type hint a list of types for a composite class in python?

Due to some architectural reasons out of my control, an object I use frequently and would like full code completion for is a dynamic composite of several features on top of the static features already present in the source code.

import lgb.reqs.plan
# Various imports which dynamically extend the smallform
import lgb_extensions.water_extras
import lgb_extensions.toolkit_extras

d = c.req[0]  # type: lgb.reqs.plan.smallform 
d = d  # type: lgb_extensions.water_extras.common
d = d  # type: lgb_extensions.toolkit_extras.common

# Now I get the autocomplete on d as I type "d."
d.

I've found the re-assign d method to work great, but it feels wrong. Is there no way to type hint with a tuple or something? I tried and couldn't figure it out.

I've found jupyter notebook to be great for autocompletion, and I'll jump into either ipython or a notebook session if I really need to explore an unknown codebase, but in this case, I'm pretty familiar with the code base and just would like the autocompletions to be better as I can never remember quite what things are called. I'm mostly in pycharm or atom if that matters. The solution above already solves my problem if there are only a few extensions , but it doesn't work when I have 10 things extending the object. In my use usual case, I have about 20 things extending the object I'd like auto-complete on.

You might be able to use Union here. It's more for when a name can hold different types in different circumstances.

Eg.

from typing import Union

a = f() # type: Union[str, int]
d. # now get autocompletion for str and int from IDEs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM