0

I have a base Python module basemodule.py with many functions and classes. Now I want to create many new modules, new1.py, new2.py, new3.py, etc.

Each of these modules will only add or change 1-2 functions in the base module. I am looking for a way to extend the base module, so that I don't need to repeat many codes.

Referring to this post, Rizwan has suggested a very interesting way to do this.

extmodule.py:

from basemodule import *
import basemodule

#code is in extended module
def makeBalls(a,b):
    foo = makeBall(a)
    bar = makeBall(b)
    print foo,bar

#function from extended module overwrites base module
def override():
    print "OVERRIDE TWO"

#function from extended module calls base module first
def dontoverride():
    basemodule.dontoverride()
    print "THIS WAS PRESERVED"

In this example, the base module has been imported twice, using import .. and from .. import ...

Is it ok to extend Python module like this? Will it cause any undefined behaviour?

Community
  • 1
  • 1
userpal
  • 1,483
  • 2
  • 22
  • 38

1 Answers1

1

While maybe not so common this is certainly a valid method of code reuse in Python and has it's uses, e.g. substituting real modules with mocked ones for testing or rolling a plugin system.

It's a form of object composition on the module level, which may be more flexible than the usual object inheritance, see composition over inheritance. Though you should take care not to lose code clarity by using this approach in some obscure ways. I'd say this is usually expected to be done on class level.

famousgarkin
  • 13,687
  • 5
  • 58
  • 74