Typing Annotation Question

20 views
Skip to first unread message

Thomas Passin

unread,
Sep 19, 2022, 2:50:34 PM9/19/22
to leo-editor
In Leo's code base, there are many method calls like this:

c.config = leoConfig.LocalConfigManager(c, previousSettings)

However, mypy doesn't know that c (known to be a leo.core.leoCommands.Commands)
has an attribute config (which we actually know is a leo.core.leoConfig.LocalConfigManager).  mypy issues an error for the line:


I've just started learning to annotate code - I started with the Freewin plugin - and I haven't worked out how to solve this problem  And I noticed that it's not handled in LeoPyRef, either - mypy just emits error messages for all similar cases I looked at.

I'm sure there are many other similar cases besides c.config.  Is there a way to make mypy understand, or do we just have to live with it?  I don't think I want to get into trying to annotate LeoPyRef, if possible.

Jacob MacDonald

unread,
Sep 19, 2022, 4:10:55 PM9/19/22
to leo-e...@googlegroups.com
I'm not very familiar with the Leo codebase and don't have a working
version downloaded at the moment, but like mypy and can maybe offer a
suggestion. Browsing the code, it looks like c.config is set in
initSettings (https://github.com/leo-editor/leo-editor/blob/master/leo/core/leoCommands.py#L432).
mypy indeed does not understand that c.config will always be a member
variable of a given type. Even if you notate the variable in that
section, I suspect that the typechecker won't pick it up properly. I
believe the solution would be to annotate the existence of c.config
while leaving that assignment alone. Something like:

config: LocalConfigManager

inside the class but before any method definitions should do the
trick. That is, a type annotation without any kind of assignment
involved.

Thomas Passin

unread,
Sep 19, 2022, 6:30:51 PM9/19/22
to leo-editor
I thought something like that would work;  I was hoping for a way that doesn't involve that area of the codebase.  Thanks for your help.

Jacob MacDonald

unread,
Sep 19, 2022, 6:41:56 PM9/19/22
to leo-e...@googlegroups.com
You can also manually annotate at the call site with no runtime cost
(https://docs.python.org/3/library/typing.html#typing.cast). That
doesn't give any guarantees, though, and will fail neither during
typechecking nor runtime.
Reply all
Reply to author
Forward
0 new messages