Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parametric modules in python? Importing functions from objects

Tags:

python

import

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

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

One way would be to make my module an object and just use those functions. Currently I do 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 out ["oh no!", "hi!", "hi!"].

However, this will work less nicely the more functions you have.

I would like to be able to do something like this :

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

print mod.sayings

Is anything like this possible? Can I inherit from a base module? How about if I add the constraint that it should look obvious to users what is going on?

like image 598
John Salvatier Avatar asked Apr 28 '26 23:04

John Salvatier


1 Answers

There are a few things to realize about modules:

  • they are singletons, which means you will only ever have one of them, no matter how many places 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 that way

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

You can get 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
like image 65
Ethan Furman Avatar answered May 01 '26 11:05

Ethan Furman