[Python] Why is fromkeys a method rather than a built-in function?

Discussão em 'Python' iniciado por Stack, Julho 23, 2025.

  1. Stack

    Stack Membro Participativo

    Why is the fromkeys method of the dict class a method of the class rather than a stand alone built-in function?

    As much as I'm aware, it only returns a new dictionary based on the parameters passed to the method, and is not impacted by the class instance (dictionary) it is called from. The usual implementation just uses the class name dict directly rather than specifying a class instance in the first place.

    I've tried the following statements but they all have consistently ignored the class instance as I mentioned.


    >>> dict.fromkeys((1,2))

    {1: None, 2: None}

    >>> {1: "Hey"}.fromkeys((1,2))

    {1: None, 2: None}

    >>> {1: "Hey"}.fromkeys((2,))

    {2: None}


    The Python documentation also doesn't mention anything more than what the parameters do. It does not mention any use of the class instance but does not declare its purposelessness either.

    I believe the reason is probably related to the namespace management. A function fromkeys created by the user will not affect the built-in class method this way, right?

    I just wanna make sure I've not missed out any purpose the class instance could have, to avoid future bugs in my codes

    Continue reading...

Compartilhe esta Página