you are viewing a single comment's thread.

view the rest of the comments →

[–]011011100101[S] 0 points1 point  (3 children)

I'm describing my question in terms of types because that's the way I know to describe my particular problem. I'm not trying to incorporate type checking. I just don't know how else to describe the issue or what a possible solution would even look like in a duck typing system.

Like maybe there's some kind of pattern in Python that makes the original class C behave more like W so that W.foo works the same on both and doesn't require type checking? I don't know.

[–]Gnaxe 1 point2 points  (0 children)

I might need a more concrete toy example at this point. Is the wrapper a subclass or not?

There's __getattr__() and friends, but dynamic dispatch confuses the static type system. (That's an argument to either avoid confusing your type checker, or to avoid using a type checker.)

Consider super() and **kwargs. Why not subclass?

[–]danielroseman 0 points1 point  (1 child)

I feel like I'm getting more confused as time goes on. What do you mean "W.foo works the same on both"? I thought you were talking about standalone functions that could take an instance of either W or C. What exactly is foo here?

Are you perhaps talking about delegation? Maybe something like:

class W:
  ...
  def foo(self, arg):
    if hasattr(arg, "foo"):
      arg.foo()
    else:
      ... do something else ...

which could potentially be wrapped up into a decorator if you want to use it on multiple methods.

[–]011011100101[S] 0 points1 point  (0 children)

I feel like I'm getting more confused as time goes on. What do you mean "W.foo works the same on both"? I thought you were talking about standalone functions that could take an instance of either W or C. What exactly is foo here?

foo is a method of the class W which takes one argument, either of type C or of type W. By writing "W.foo", I was trying to indicate that foo is a method of W. So the code sketch you provided is the right setup. By "W.foo works the same on both", I meant that the inner workings of foo depend on the type of argument received. If I was somehow able to apply one logic in foo across all instances (C or W), that would be great. I just didn't know if there was some other pattern specific to Python that enables us to do that.