I am trying to define a function my_del
with the following properties:
- it has only one parameter,
- if the parameter passed is a variable with global assignment, it deletes it using
del
, - otherwise it prints "Variable not assigned",
- no NameError exception should be issued.
My first trial:
def my_del(var):
try:
del var
except NameError:
print("Variable not assigned")
This does not work.
(i) For an assigned variable:
x = 1
my_del(x)
x
# outputs 1
the reference did not get deleted. Although not sure, I suppose this is because var
did not get bound to the global x
.
(ii) For an unassigned variable, an exception is issued:
my_del(y)
# NameError exception
The function my_del
did not get the chance to be called, as the exception happens before.
My second trial:
def my_del(var):
try:
var = var()
del var
except NameError:
print("Variable not assigned")
(i) For an unassigned variable:
my_del(lambda: y)
# prints the string
This works fine.
(ii) For an assigned variable:
x = 1
my_del(lambda: x)
x
# outputs 1
we still have x
referenced. Here var = var()
creates a local variable, which does not refer to the input parameter.
What would be a proper way to create this my_del
function?