[python] Automaticky import v podmodulech

Radek Kanovsky rk na dat.cz
Čtvrtek Říjen 7 11:15:31 CEST 2004


On Wed, Oct 06, 2004 at 05:26:40PM +0000, Ales Teska wrote:

> Tady zatim docela tapu - zrejme bych dokazal pomoci 
> sys.modules zjistit 'jednoduche importy' nicmene s 'from foo import bar;' 
> si uz poradit nedokazi.
> Mate nekdo nejaky napad jak z toho ?
 
Pokud vam jde o to, jak nasimulovat konstrukci `from foo import bar' za
behu, tak by to mohlo jit nejak takto:


    import sys

    def importFromAs (fromModule, importName, toModule, asName=None) :
        smod = __import__(fromModule)
        dmod = sys.modules[toModule]

        obj  = smod
        path = ("%s.%s" % (fromModule, importName)).split(".")[1:]
        for p in path :
            obj = getattr(obj, p)

        if asName is None :
            setattr(dmod, importName, obj)
        else :
            setattr(dmod, asName, obj)

    # ``from os.path import join''  v modulu __main__
    importFromAs ('os.path', 'join', '__main__')

    # ``from os.path import join as pathjoin'' v modulu __main__
    importFromAs ('os.path', 'join', '__main__', 'pathjoin')

    # ``from os.path import join''  v modulu sys
    importFromAs ('os.path', 'join', 'sys')
    

    assert pathjoin is join is sys.join

    print pathjoin('/etc', 'profile')
    print join('/etc', 'profile')
    print sys.join('/etc', 'profile')
    

Radek Kaňovský



Další informace o konferenci Python