Python Alternatives to Using Globals

Python Alternatives to Using Globals

What are the rules for local and global variables in Python? What are the “best practices” for using import in a module?

I am by no means an expert in Python, but after a few years of developing with it more or less exclusively (JavaScript, I still love you!), I’m starting to feel comfortable enough to write about it.

This short article is about global variables and how to use them (or not). But most importantly, it’s about alternatives to them — something that usually gets omitted.

What Is a Global?

A global variable is simply a variable that’s accessible from anywhere in your program. Consider these examples:

INIT = False
def run():
    global INIT
    print('Will Run')
    if INIT:
        print( 'Already initiated' )
    if not INIT:
        init()
def init():
    global INIT
    INIT = True
    print('Will Init')
run()
run()
OUTPUT:
Will Run
Will Init
Will Run
Already initiated

Both the run() and init() functions have access to the INIT variable via the globalkeyword. This allows for the following logic: run init() once, set the INIT variable to True, and then check if it has already ran (via the INIT variable). If so, don’t run it again.

There are plenty of instances where globals seem to be a perfect fit. Consider another example — where we simply have a color or some other variable we need to reference in various functions:

GUI_THEME = 'BabyBlue'
GUI_FONT = 'Lobster'
def makeGUI():
    global GUI_THEME,GUI_FONT
    print('making GUI in: ' + GUI_THEME)
    print('with FONT: ' + GUI_FONT)
def changeTheme():
    global GUI_THEME
    GUI_THEME = 'AwesomeOrange'
def changeFont():
    global GUI_FONT
    GUI_FONT = 'Merryweather'
makeGUI()
changeTheme()
changeFont()
makeGUI()
OUTPUT:
makig GUI in: BabyBlue
with FONT: Lobster
makig GUI in: AwesomeOrange
with FONT: Merryweather

Also note without declaring a variable as a global, you can still read it. So in this case, it can be treated like a constant:

GUI_THEME = 'constantGrey'
def makeGUI():
    print('making GUI in: ' + GUI_THEME)
    # Try to change it:
def changeGUI():
    GUI_THEME = 'variableGrey' # Local variable
    print('making GUI in: ' + GUI_THEME)
makeGUI()
changeGUI()
makeGUI()
making GUI in: constantGrey
making GUI in: variableGrey
making GUI in: constantGrey

But it fails when trying to change it, note how the second makeGUI() is still using the original theme and the changeGUI was only valid locally.
Why Not Use Them?

If someone has barked at you to not use globals, and you got no explanation (or a convoluted answer), this section is for you. Take for instance Google’s styleguide:

2.5 Global variables:
Avoid global variables.
WHY ?:
Has the potential to change module behavior during the import, because assignments to global variables are done when the module is first imported.
🤔🤔🤔
When to Use Them

I’m jumping ahead a bit because the previous style guide then goes on to say:


While they are technically variables, module-level constants are permitted and encouraged.
External access must be done through public module-level functions

Here is the rub: While prototyping, I don’t usually write modules initially beyond using those from other libraries. So it seems perfectly fine (and even more expedient) to use globals while starting your program or script.

And then as it becomes more complex, you can divide them into internal constants and project-wide variables … but we’re getting ahead. Let’s first exemplify why using a global in a module can be a bad idea — this is but one interpretation:

FILE: module_01.py
GLOBAL_MODULE_VAR = False
def changeGlobal(): #<< Public access
    global GLOBAL_MODULE_VAR
    GLOBAL_MODULE_VAR = True

Elsewhere in your code:

import module_01 as M1
print(M1.GLOBAL_MODULE_VAR)
# False, all good here.
M1.changeGlobal() #<< Public access
print(M1.GLOBAL_MODULE_VAR)
# True, still good, but...
import module_01 as M2
print(M2.GLOBAL_MODULE_VAR)
# Still True, Unless you wanted False !, and who is keeping track of these changes ?
M1.GLOBAL_MODULE_VAR = False
# Direct assignment, works, but can get messy.

Mind you, there’s nothing wrong with this behavior if that’s what you want, but most likely, you want your globals (and, more importantly, your state) to be a reference only a few functions can touch, rather than something more mutable and open.

There’s also the case for organizing your code according to convention to make it more readable. Direct assignment, for instance, makes code hard to follow.

What Should We Use Instead?

Classes:

The OOP approach: Here’s the first example in class form.

class Init:
    def __init__(self, init_: bool):
        self.init = init_
# Create class
class Init:
    def __init__(self, init_: bool):
        self.init = init_
# Create Instance of the class
init_ = Init(False)
def run():
    print('Will Run')
if init_.init:
        print( 'Already initiated' )
    if not init_.init:
        init()
def init():
    init_.init = True
    print('Will Init')
run()
run()

Output:
Will Run
Will Init
Will Run
Already initiated

And the second example:

class GUI:
    def __init__(self):
        self.GUI_THEME = 'BabyBlue'
        self.GUI_FONT = 'Lobster'
GUI_ = GUI() # Can also use initialization arguments
def makeGUI():
    print('making GUI in: ' + GUI_.GUI_THEME)
    print('with FONT: ' + GUI_.GUI_FONT)
def changeTheme():
    GUI_.GUI_THEME = 'AwesomeOrange'
def changeFont():
    GUI_.GUI_FONT = 'Merryweather'
makeGUI()
changeTheme()
changeFont()
makeGUI()
OUTPUT:
making GUI in: BabyBlue
with FONT: Lobster
making GUI in: AwesomeOrange
with FONT: Merryweather

The downside here is that there’s some code and complexity overhead, but this seems to be a popular choice.

Global mutables (dict, list, and set):

In short, mutables behave like globals without the global keyword — with the caveat they need to be wrapped in a list, set, or dict with different degrees of readability.

_G = {'INIT': False }
# Mutable Dict
def run():
    print('Will Run')
    if _G['INIT']:
        print("Already initiated")
    else:
        init()
def init():
    _G['INIT'] = True
    print('Will Init')
run()
run()
print(_G)
OUTPUT:
Will Run
Will Init
Will Run
Already initiated
{'INIT': True}

You could also use lists:

_INIT = [False]
# Mutable List:
def run():
    print('Will Run')
    if _INIT[0]:
        print("Already initiated")
    else:
        init()
def init():
    _INIT[0] = True
    print('Will Init')
run()
run()
print(_INIT)
OUTPUT:
Will Run
Will Init
Will Run
Already initiated
[True]

You could even use a set. Sets are unordered, so you’d need to come up with additional logic.

_INITSET = {'notInititated'}
# MUTABLE SET
def run():
    print('Will Run')
    if ("Inititated" in _INITSET):
        print("Already initiated")
    else:
        init()
def init():
    _INITSET.remove("notInititated")
    _INITSET.add("Inititated")
    print('Will Init')
run()
run()
print(_INITSET)
OUTPUT:
Will Run
Will Init
Will Run
Already initiated
{'Inititated'}

Dictionaries, though, seem to be the more readable, best bang-for-your-buck option :

_GUI = {'THEME_COLOR': 'BabyBlue', 'THEME_FONT': 'Lobster'}
def makeGUI():
    print('makig GUI in: ' + _GUI['THEME_COLOR'])
    print('with FONT: ' + _GUI['THEME_FONT'])
def changeThemeColor():
     _GUI['THEME_COLOR'] = 'AwesomeOrange'
def changeThemeFont():
    _GUI['THEME_FONT'] = 'Merryweather'
makeGUI()
changeThemeColor()
changeThemeFont()
makeGUI()
OUTPUT:
makig GUI in: BabyBlue
with FONT: Lobster
makig GUI in: AwesomeOrange
with FONT: Merryweather

As to which approach to use, classes or mutables, I think it depends on how complex the variable being represented is.

If it’s just a list of variables, a mutable will do. If some processing needs to be done (or your boss demands it), a class might work better.

External Access

Before wrapping up, we need to see how these two approaches work when importing modules:

FILE: module_02.py
class ModuleVARS:
    def __init__(self, init_: bool):
        self.GLOBAL_MODULE_VAR = init_
Add class methods to suit your needs...

Usage:

import module_02 as M2
# New Instance:
GLOBALMODULEVARS = M2.ModuleVARS(True)
print(GLOBALMODULEVARS.GLOBAL_MODULE_VAR)
#True
def changeGlobalVar():
    GLOBALMODULEVARS.GLOBAL_MODULE_VAR = False
    print(GLOBALMODULEVARS.GLOBAL_MODULE_VAR)
changeGlobalVar()
#False

And using mutables:

FILE: module_03.py
_GUI = {'THEME_COLOR': 'BabyBlue', 'THEME_FONT': 'Lobster'}
Add class methods to suit your needs...

Usage:

import module_03 as M3
print(M3._GUI['THEME_COLOR'])
print(M3._GUI['THEME_FONT'])
#BabyBlue
#Lobster
def changeTheme():
    M3._GUI['THEME_COLOR'] = 'AwesomeOrange'
    print(M3._GUI['THEME_COLOR'])
def changeFont():
    M3._GUI['THEME_FONT'] = 'Merryweather'
    print(M3._GUI['THEME_FONT'])
changeTheme() #AwesomeOrange
changeFont() #Merry-weather

Once more, what to use depends on what data structure your code is trying to emulate. If it’s a reference, mutables might work better, but if it has some internal logic, a class might be better suited.

Conclusion

There are many ways to do the same thing in code, and Python is no different. Some are better suited than others, but by knowing several paths, one can then choose the one that makes sense.

Having a mutable reference through your program or script can be accomplished in several ways. Here we’ve seen globals, classes .and mutables, scand each one comes with its pros and cons and might be better suited to certain projects.

You might use all three at different times during the evolution of your program or opt for one for consistency across your team and/or readability.

tl;dr: Use dictionaries (reference) or classes (reference+logic) instead. Use globals while prototyping for scaffolding.

Thanks for reading.

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Description
Learn Hands-On Python Programming By Creating Projects, GUIs and Graphics

Python is a dynamic modern object -oriented programming language
It is easy to learn and can be used to do a lot of things both big and small
Python is what is referred to as a high level language
Python is used in the industry for things like embedded software, web development, desktop applications, and even mobile apps!
SQL-Lite allows your applications to become even more powerful by storing, retrieving, and filtering through large data sets easily
If you want to learn to code, Python GUIs are the best way to start!

I designed this programming course to be easily understood by absolute beginners and young people. We start with basic Python programming concepts. Reinforce the same by developing Project and GUIs.

Why Python?

The Python coding language integrates well with other platforms – and runs on virtually all modern devices. If you’re new to coding, you can easily learn the basics in this fast and powerful coding environment. If you have experience with other computer languages, you’ll find Python simple and straightforward. This OSI-approved open-source language allows free use and distribution – even commercial distribution.

When and how do I start a career as a Python programmer?

In an independent third party survey, it has been revealed that the Python programming language is currently the most popular language for data scientists worldwide. This claim is substantiated by the Institute of Electrical and Electronic Engineers, which tracks programming languages by popularity. According to them, Python is the second most popular programming language this year for development on the web after Java.

Python Job Profiles
Software Engineer
Research Analyst
Data Analyst
Data Scientist
Software Developer
Python Salary

The median total pay for Python jobs in California, United States is $74,410, for a professional with one year of experience
Below are graphs depicting average Python salary by city
The first chart depicts average salary for a Python professional with one year of experience and the second chart depicts the average salaries by years of experience
Who Uses Python?

This course gives you a solid set of skills in one of today’s top programming languages. Today’s biggest companies (and smartest startups) use Python, including Google, Facebook, Instagram, Amazon, IBM, and NASA. Python is increasingly being used for scientific computations and data analysis
Take this course today and learn the skills you need to rub shoulders with today’s tech industry giants. Have fun, create and control intriguing and interactive Python GUIs, and enjoy a bright future! Best of Luck
Who is the target audience?

Anyone who wants to learn to code
For Complete Programming Beginners
For People New to Python
This course was designed for students with little to no programming experience
People interested in building Projects
Anyone looking to start with Python GUI development
Basic knowledge
Access to a computer
Download Python (FREE)
Should have an interest in programming
Interest in learning Python programming
Install Python 3.6 on your computer
What will you learn
Build Python Graphical User Interfaces(GUI) with Tkinter
Be able to use the in-built Python modules for their own projects
Use programming fundamentals to build a calculator
Use advanced Python concepts to code
Build Your GUI in Python programming
Use programming fundamentals to build a Project
Signup Login & Registration Programs
Quizzes
Assignments
Job Interview Preparation Questions
& Much More

Variables in Python – Global & Static Variables

Python is considered as the most sought after coding language by a lot of companies around the globe.Irrespective of any industry mankind has been gifted with,it is regarded as the heart and brain of the industry. The bottomline is an individual who knows python will be in demand. How did it happen? How come a person, out of the blue who knows Python is suddenly in demand? Variables In Python are also considered in order to make amends with the software companies. Let us dig deep and see what it needs to be in a guy to be the best developer.
Anyone having a tinge of experience and interest in software development can be a python developer. But,again a question arises that how to be one. The answer is simple, one needs to start from the basics. He/she needs to undergo some specific python courses which makes him/her industry ready. One of the brutal significance which the language provides for beginners is any person who hasn’t written a code in his entire life is qualified to take up the course and is in line to be one.

Top Python Development Companies | Hire Python Developers

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When you look for the developer in hurry you may forget to take note of review and ratings of the company's aspects, but we at TopDevelopers have done a clear analysis of these top reviewed Python development companies listed here and have picked the best ones for you.

List of Best Python Web Development Companies & Expert Python Programmers.