Conditional typing for mapping input to correct method in Protocol-Based Implementation #1404
Unanswered
BrandonNav
asked this question in
Q&A
Replies: 1 comment 1 reply
-
Progress update: I can manually use type narrowing to specialise the types but it requires duplicating every derived Impl def do(registry_entry: Registry):
match (impl:= registry_entry.value()):
case Impl1():
input = impl.input_type("input")
impl.run(input)
impl.template.render(input)
case Impl2():
input = impl.input_type("input")
impl.run(input)
impl.template.render(input) I think TypeGuards might help here (so long as this approach is still valid) |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello everyone,
I'm currently working on a Python project where I have various implementations (Impl1 and Impl2) of a base class that uses Protocols for type hinting. The base class has a 'run' method which should accept an input and process it accordingly based on the specific implementation (Impl1 or Impl2).
Here's my challenge: I've stored the classes in a registry as Enums, and I'm trying to use the Enum to create an instance and run the associated method. The line
impl.run(input)
is causing an error:What I am trying to do is to have conditional typing such that the 'run' method can correctly map my input to the appropriate 'run' method based on the instance's class. However, I'm not sure how to achieve this, or if I'm going about this the correct way.
Is there a way in Python to do conditional typing to solve this issue? Or is there a better design pattern or strategy to achieve the same effect? Any help or pointers would be greatly appreciated!
Thanks in advance.
Below is the code to reproduce the issue:
Beta Was this translation helpful? Give feedback.
All reactions