How can I change the name of a group of imports in Python?

后端 未结 2 663
悲哀的现实
悲哀的现实 2021-01-26 14:25

I would like to import all methods from a module with altered names.

For instance, instead of

from module import repetitive_methodA as methodA, \\
    re         


        
2条回答
  •  梦谈多话
    2021-01-26 15:19

    You can do it this way:

    import module
    import inspect
    for (k,v) in inspect.getmembers(module):
        if k.startswith('repetitive_'):
            globals()[k.partition("_")[2]] = v
    

    Edit in response to the comment "how is this answer intended to be used?"

    Suppose module looks like this:

    # module
    def repetitive_A():
        print ("This is repetitive_A")
    
    def repetitive_B():
        print ("This is repetitive_B")
    

    Then after running the rename loop, this code:

    A()
    B()
    

    produces this output:

    This is repetitive_A
    This is repetitive_B
    

提交回复
热议问题