Parametric modules in python? Importing functions from objects

I have a module that I would like to parameterize, or rather would like to import functions from an object.

That is, I would like to give it arguments that will change its behavior before I import things from it.

One way is to make my module an object and just use these functions. I am currently doing this:

class MyModule(object):
    def __init__(self, previous_sayings):
        self.sayings = previous_sayings
    __all__ = ['sayhi']
    def sayhi(self):
        self.sayings.append("hi!")

mod = MyModule(["oh no!"])
sayhi = mod.sayhi
sayhi()
sayhi()
print mod.sayings

      

This should print ["oh no!", "hi!", "hi!"]

.

However, this will work less well the more features you have.

I would like to do something like this:

mod = MyModule(["oh no!"])
from mod import * 
sayhi()
sayhi()

print mod.sayings

      

Is this possible? Can I inherit from a base module? How about if I add a constraint that should look obvious to users, what's going on?

+3


source to share


3 answers


There are several things to implement modules:

  • they are single point, which means that you will only have one of them, no matter how many locations you import it.

  • you cannot pass arguments

  • from <module> import *

    is dangerous, not a good habit, and should only be used with modules that have been designed this way.

  • all functions, classes, etc. that are defined in a module will always see that module as a global namespace.



You can end up with something similar to what you want:

8<--mod.py------------------------------------------------------
sayings = []
def sayhi():
    sayings.append("Hi!")
8<--------------------------------------------------------------

import mod
mod.sayings = ['oh no!']   # or mod.sayings.append('oh no')
from mod import sayhi
sayhi()
sayhi()
print mod.sayings

      

+2


source


You can create your module dynamically and then import it.

http://code.activestate.com/recipes/82234-importing-a-dynamically-generated-module/



Although, my suggestion would be to use the.

0


source


If the problem is only that:

sayhi=mod.sayhi()
saybye=mod.saybye()
# … 40 more functions

      

more verbose than:

from mod import sayhi, saybye, # … 40 more functions

      

The best solution is probably just for software implementation:

for name in mod.__all__:
    locals[name] = getattr(mod, name)

      

Or:

locals.update({name: getattr(mod, name) for name in mod.__all__})

      

0


source







All Articles