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

2020-05-09 22:05发布

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.

2条回答
Fickle 薄情
2楼-- · 2020-05-09 22:47

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
查看更多
够拽才男人
3楼-- · 2020-05-09 22:56

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
查看更多
登录 后发表回答