[Python-ideas] Explicitly shared objects with sub modules vs import

Ron Adam ron3200 at gmail.com
Mon Jun 1 05:55:43 CEST 2015



On 05/30/2015 11:45 AM, Ron Adam wrote:
>
> The solution I found was to call a function to explicitly set the shared
> items in the imported module.


A bit of an improvement...

     def export_to(module, **d):
         """ Explitely share objects with imported module.

             Use this_module.item in the sub-module
             after item is exported to it.
         """
         from collections import namedtuple
         namespace = namedtuple("exported", d.keys())
         for k, v in d.items():
             setattr(namespace, k, v)
         # Not sure about this.  Possibly sys.get_frame would be better.
         setattr(module, __loader__.name, namespace)


And used like this.

     import sub_mod
     export_to(sub_mod, foo=foo,
                        bar=bar)

Then functions in sub-mod can access the objects as if the sub-module 
imported the parent module, but only the exported items are visible to the 
sub module.

Again, this is for closely dependent modules that can't easily be split by 
moving common objects into a mutually imported file, or if it is desired to 
split a larger module by functionality rather than dependency.

There are some limitations, but I think they are actually desirable 
features.  The sub-module can't use exported objects at the top level, and 
it can't alter the parent modules name space directly.

Of course, it could just be my own preferences.  I like the pattern of 
control (the specifying of what gets imported/shared) flowing from the top 
down.

Cheers,
    Ron



More information about the Python-ideas mailing list