[Python-ideas] Internal function idea

Stephen J. Turnbull turnbull.stephen.fw at u.tsukuba.ac.jp
Fri Dec 29 05:09:57 EST 2017


On Sat, Dec 23, 2017, 09:23 William Rose, <william27.07.02 at gmail.com> wrote:

 > I had an idea that it could be helpful to have local functions as
 > well as normal ones. They would be called the same way as normal
 > ones but def would be replaced by internal and inside they could
 > only access variables they have defined and inputs to them so no
 > global variables or class variables. I think this could be used
 > to save people accidentally changing variables you dont' want to
 > change when updating your code. Let me know what you think!

I suspect you misunderstand how variables (actually, name bindings)
work in Python.  If you do understand, I don't understand what you're
guarding against.  With current semantics, code inside a function
cannot change a global binding, although it can refer to one:

>>> def f():
...  x=3
...  return x
... 
>>> def g():
...  return x
... 
>>> x = 0
>>> y = f()                # Changes x?
>>> z = g()
>>> print("x =", x, "y =", y, "z =", z)
x = 0 y = 3 z = 0          # Nope.
>>> def h():
...  y = x + 5
...  x = y                 # Changes x?
...  return x
... 
>>> w = h()                # Nope, it crashes your program instead!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in h
UnboundLocalError: local variable 'x' referenced before assignment

You *can* use the global and nonlocal declarations to override the
normal automatic assumption that names are local to the scope in
which they are bound:

>>> def a():
...  global x
...  x = 42
...  return x
... 
>>> a()
42
>>> x
42

Prohibiting this last would be un-Pythonic, IMO (violates the
"consenting adults" principle).  Similarly for class variables, which
can only be accessed using attribute notation.  There are also
conventions, prefixing "_" or "__", which indicate "this is private,
mess with it at your own risk", and actually munge the name internally
to make it impossible to access accidentally (including in derived
classes).




More information about the Python-ideas mailing list