I have some function which uses outside variables. A (substantially) simplified example:
a = 2
b = 3
def f(x):
return x * a + b
While I need a
and b
in f
, I don't need them anywhere else. In particular, one can write a = 5
, and that will change the behavior of f
. How should I make a
and b
invisible to the outside?
Other languages allow me to write roughly the following code:
let f =
a = 2
b = 3
lambda x: x * a + b
What I want:
f
must work as intended and have the same signaturea
andb
must be computed only oncea
andb
must not exist in the scope outside off
- Assignments
a = ...
andb = ...
don't affectf
- The cleanest way to do this. E.g. the following solution formally works, but it introduces
g
and then deletes it, which I don't like (e.g. there is a risk of overriding an existingg
and I believe that it's simply ugly):
def g():
a = 2
b = 3
return lambda x: x * a + b
f = g()
del g