3

If someone uses a python builtin as a variable, deleting the variable seems to revert the definition of the term to the original definition. For example:

set = 1
print(set)
del set
a = set([1,2,3])
print(a)

Result:

1
{1, 2, 3}

However, when you delete a builtin from the start, it is no longer defined:

del set
a = set([1,2,3])
print(a)

Result: NameError: name 'set' is not defined

I understand that it is bad practice to use builtins as variables, but I'm curious about this design decision:

If the python source code can intelligently restore deleted variables by assigning them to their original builtin value, why does the code allow the deletion of builtins in my second example? What possible utility could there be in allowing the deletion of builtins?

No I don't have a real world use case for this; I just want to understand the design decision.

JacobIRR
  • 8,545
  • 8
  • 39
  • 68

1 Answers1

5

The NameError you're getting in the second example isn't from trying to use set after deleting it; the NameError is from trying to delete set.

del some_variable tries to unbind some_variable in the current namespace. Outside a function or class, that means the current module's module globals. The built-in binding for set lives in the built-in namespace, accessible through the builtins module; del set won't delete that.

Since del set can't find a set variable to unbind, it throws a NameError.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • To clarify: looking up a global variable will check the global namespace first, then the builtin namespace (where `set` resides by default). However, using `del` on a global variable will **only** attempt to remove the name from the global namespace. That's why and how the first code example works. Note that this does [**not** work for locals](https://stackoverflow.com/questions/31175666), because local variable lookup will only check the local namespace - same as `del` on a local. – Karl Knechtel Aug 09 '22 at 06:44