Search code examples
pythonpython-3.ximportpython-import

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


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

For instance, instead of

from module import repetitive_methodA as methodA, \
    repetitive_Class1 as Class1, \
    repetitive_instance4 as instance4

I'd prefer something along the lines of

from module import * as *-without-"repetitive_"

this is a rephrasing of this clumsy unanswered question, I have not been able to find a solution or similar questions yet.


Solution

  • 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