[Python] How can I get the name of an object?

Discussão em 'Python' iniciado por Stack, Fevereiro 7, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose I have code like:

    x = 0
    y = 1
    z = 2

    my_list = [x, y, z]

    for item in my_list:
    print("handling object ", name(item)) # <--- what would go instead of `name`?


    How can I get the name of each object in Python? That is to say: what could I write instead of name in this code, so that the loop will show handling object x and then handling object y and handling object z?


    In my actual code, I have a dict of functions that I will call later after looking them up with user input:

    def fun1():
    pass
    def fun2():
    pass
    def fun3():
    pass

    fun_dict = {'fun1': fun1,
    'fun2': fun2,
    'fun3': fun3}

    # suppose that we get the name 'fun3' from the user
    fun_dict['fun3']()


    How can I create fun_dict automatically, without writing the names of the functions twice? I would like to be able to write something like

    fun_list = [fun1, fun2, fun3] # and I'll add more as the need arises

    fun_dict = {}
    for t in fun_list:
    fun_dict[name(t)] = t


    to avoid duplicating the names.

    Continue reading...

Compartilhe esta Página