Global variable declaration

Where should Global variables are declared?
The below code certainly doesn’t work

Thank you

class Form1(Form1Template):

  count = 0

  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    self.label_1.text = str(count)

that code won’t work in python fullstop…

class A:
  count = 0

>>> a = A()
>>> a.count
0

so instead do

class Form1(Form1Template):

  count = 0

  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    self.label_1.text = str(self.count)

Thank so much, I am quite new to Python
self is a really important keyword then

yeah - anvil makes a lot more sense as you get familiar with classes and methods in python. It’s a great way to learn them though…

the python docs are useful here about when/where to declare certain attributes of a class. This section might be useful.
https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables

Indeed, a very good way to learn. Thanks

1 Like

It is better t avoid global variables from your programs because they enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity, potentially leading to Spaghetti code.

However, sane use of global state is acceptable (as is local state and mutability) even in functional programming, either for algorithm optimization, reduced complexity, caching and memoization, or the practicality of porting structures originating in a predominantly imperative codebase.