vendredi 10 avril 2020

Templating and extending a python module a la functors/parametric modules

I'm not quite sure how to describe this exactly, but imagine that you have python module A, with many interconnected classes/objects and such that reference each other. I want to create a new module B that overrides certain methods/classes in A. And if B overwrites something, then the rest of B (an extension of A) should use the new version from B.

ie B is functionally a git fork of A. But I want to avoid the maintenance of maintaining forks in sync with A.

Are there any obvious design patterns or pythonic niceties that'll let me do this? Closest I've found on SO is this How do I extend a python module? Adding new functionality to the `python-twitter` package

But this fails in that if module A has interrelated classes then we're back in a situation then the "extended A" will still try to use other modules in A instead of defaulting to check if B has it first.

For example:

# Module A
def foo():
  return bar()

def bar():
  return 1
# Module B
from A import *

def bar():
  return 2
>>> import B
>>> B.foo()
1
>>> B.bar()
2
>>>

But I want B.foo() to return 1, i.e. calling B.foo() would execute A.foo() but I want A.foo() to instead execute in the B namespace before trying its own.

Like I want to write a functor from module A to module B

I have found this https://gist.github.com/jcrist/39db5994c71511572846 but it doesn't feel very "clean"

Aucun commentaire:

Enregistrer un commentaire