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

后端 未结 2 625
悲哀的现实
悲哀的现实 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 14:58

    What I would do, creating a work-around...

    Including you have a file named some_file.py in the current directory, which is composed of...

    # some_file.py
    def rep_a():
        return 1
    
    def rep_b():
        return 2
    
    def rep_c():
        return 3
    

    When you import something, you create an object on which you call methods. These methods are the classes, variables, functions of your file.

    In order to get what you want, I thought It'd be a great idea to just add a new object, containing the original functions you wanted to rename. The function redirect_function() takes an object as first parameter, and will iterate through the methods (in short, which are the functions of your file) of this object : it will, then, create another object which will contain the pointer of the function you wanted to rename at first.

    tl;dr : this function will create another object which contains the original function, but the original name of the function will also remain.

    See example below. :)

    def redirect_function(file_import, suffixe = 'rep_'):
        #   Lists your functions and method of your file import.
        objects = dir(file_import)
    
        for index in range(len(objects)):
            #   If it begins with the suffixe, create another object that contains our original function.
            if objects[index][0:len(suffixe)] == suffixe:
                func = eval("file_import.{}".format(objects[index]))
                setattr(file_import, objects[index][len(suffixe):], func)
    
    if __name__ == '__main__':
        import some_file
        redirect_function(some_file)
        print some_file.rep_a(), some_file.rep_b(), some_file.rep_c()
        print some_file.a(), some_file.b(), some_file.c()
    

    This outputs...

    1 2 3
    1 2 3
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题