Is there anything like Python export?

后端 未结 1 1603
长情又很酷
长情又很酷 2021-01-05 08:08

We use all the time python\'s import mechanism to import modules and variables and other stuff..but, is there anything that works as export? like:

we import stuff fr

相关标签:
1条回答
  • 2021-01-05 08:47

    First, import the module you want to export stuff into, so you have a reference to it. Then assign the things you want to export as attributes of the module:

    # to xyz export a, b, c
    import xyz
    xyz.a = a
    xyz.b = b
    xyz.c = c
    

    To do a wildcard export, you can use a loop:

    # to xyz export *
    exports = [(k, v) for (k, v) in globals().iteritems() if not k.startswith("_")]
    import xyz
    for k, v in exports: setattr(xyz, k, v)
    

    (Note that we gather the list of objects to be exported before importing the module, so that we can avoid exporting a reference to the module we've just imported into itself.)

    This is basically a form of monkey-patching. It has its time and place. Of course, for it to work, the module that does the "exporting" must itself be executed; simply importing the module that will be patched won't magically realize that some other code somewhere is going to patch it.

    0 讨论(0)
提交回复
热议问题