What is the Correct Time to Name a Variable after a Builtin?

Viewed 61

So I see this a lot. People call their dictionaries dict, their lists list, and so on. I know this is frowned upon because it overwrites the built-in value in Python.

The question is, why doesn't this raise an exception? I see a lot of people say to never do this, but why isn't it an error? The only conclusion I can come to is that there is a time when this sort of thing needs to happen.

So, in what situation could someone gain a programming advantage by overwriting a builtin? Or, if my conclusion is wrong, why aren't there protections against such overwriting?

2 Answers

Let's say we do that. You'll then need to consider what happens when I redefine my own functions:

from mymodule import func

def func(): # is this allowed?
    pass

func() # should this now fail?

So then there would be a difference in how Python treats overwriting built-ins from your own functions. I think it's fair to redefine your own functions so why would it be different for built-ins?

It's probably better to allow people to redefine built-ins and your own functions alike. This keep Python simple and it gives the developer flexibility in writing code.

Builtins are just names in the global namespace, so the same rule applies to any other non-builtin imported into the namespace. Now consider what happens if a new name is added to the imported module, or a new builtin is added, that has a name that is already in use in your code.

With the current rule, your code still works, but if you want to modify it to use the new names, you are forced to explicitly write module.name or __builtin__.name.

If the rule was that it raised an exception, your code would immediately stop working until you changed all references to the name.

I think the first scenario is preferable.

And of course, it's not always a mistake. Being able to inject your own functions or objects into other parts of code is part of the design of dynamic languages like python.

Related