[Python-ideas] Give nonlocal the same creating power as global

João Matos jcrmatos at gmail.com
Mon Sep 11 10:03:12 EDT 2017


Hello,

I would like to suggest that nonlocal should be given the same creating 
power as global.
If I do
global a_var
it creates the global a_var if it doesn't exist.

I think it would be great that nonlocal maintained that power.

This way when I do
nonlocal a_var
it would create a_var in the imediate parent environment, if it didn't 
exist.

Without nonlocal creation powers I have to create global variables or 
local variables after master=Tk() (in the following example):

from tkinter import StringVar, Tk
from tkinter.ttk import Label


def start_gui():
     def change_label():
         _label_sv.set('Bye Bye')

     def create_vars():
         global _label_sv

         _label_sv = StringVar(value='Hello World')

     def create_layout():
         Label(master, textvariable=_label_sv).grid()

     def create_bindings():
         master.bind('<Escape>', lambda _: master.destroy())
         master.bind('<Return>', lambda _: change_label())

     master = Tk()

     create_vars()
     create_layout()
     create_bindings()

     master.mainloop()


if __name__ == '__main__':
     start_gui()


With nonlocal creation powers it would become a start_gui local variable 
(no global) but I could have a function to create the vars instead of 
having to add them after master=Tk():

from tkinter import StringVar, Tk
from tkinter.ttk import Label


def start_gui():
     def change_label():
         label_sv.set('Bye Bye')

     def create_vars():
         nonlocal label_sv

         label_sv = StringVar(value='Hello World')

     def create_layout():
         Label(master, textvariable=label_sv).grid()

     def create_bindings():
         master.bind('<Escape>', lambda _: master.destroy())
         master.bind('<Return>', lambda _: change_label())

     master = Tk()

     create_vars()
     create_layout()
     create_bindings()

     master.mainloop()


if __name__ == '__main__':
     start_gui()



I know that I could also do it with OOP, but this way is more concise 
(OOP would add more lines and increase the lines length, which I 
personally dislike)


This example is very simple, but if you imagine a GUI with several 
widgets, then the separation between vars, layout and bindings becomes 
useful for code organization.


Best regards,

João Matos



More information about the Python-ideas mailing list