Search code examples
pythondictionaryobjectkeyword-argument

how to give object to keyword argument as key


what I want to do is like this

class Foo:
    def __init__(self):
        self.name = "james"

def foo(**kwargs):
    for obj, new_name in kwargs.items():
        obj.name = new_name

f = Foo()
foo(f="Tom")  # f have to be recognized as an object not a string "f"

as my knowledge, kwargs is a dictionary.

I tested giving an object as key in dictionary. and dictionary can have an object as key.

dd = {f: 12}
print(dd)

>>>
{<__main__.Foo object at 0x00D685D0>: 12}

but when I give an object to function's parameter as key, it becomes just string "f".

Is there the way that doesnt' ruin the original syntax

function(obj=value, obj2=value2, ...)

not like this

function((obj, value), (obj2, value2), ...)
    proper process to tuple

EDIT: use this code inside the function

    obj = getattr(sys.modules[__name__], f"{obj_name}")

Solution

  • Apparently we cannot have anything else other than strings as key type.

    Check detailed answer here : Are the keys of a kwargs argument to Python function guaranteed to be type string?

    Check source code here: https://github.com/python/cpython/blob/2ec70102066fe5534f1a62e8f496d2005e1697db/Python/getargs.c#L1604