Python Forum

Full Version: Checking for Validity of Variables
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm playing around with globals and managing variables, and I want to be able to check if a variable exists without the program stopping. If the variable exists, something happens, if the variable does not exist, something else happens.

Is this the right approach to use for that sort of task? Or should I be using other functions or techniques?

car_name = "Tesla Model S" 
car_year = 2022 

def delete_car_variables(): 
    global car_name, car_year 
    del car_name 
    del car_year 

print("Before deletion:") 

print("Car Name:", car_name) 
print("Car Year:", car_year) 

delete_car_variables() 

print("\n") 
print("After deletion:") 

try:
    print("Car Name:", car_name) 
except:
    print("Car Name is deleted") 

try:
    print("Car Year:", car_year) 
except:
    print("Car Year is deleted") 
Variables names are keys in a variable dictionary. Use locals() to look at variables in the local scope and globals() to look at variables in the global scope.
def set_variable(value):
    global variable
    variable = value

print(locals().get('variable'))  # local scope = global scope here
set_variable(42)
print(locals().get('variable'))
Output:
None 42
While you can use locals and globals to do what you want, I would be remiss if I didn't say that what you want to do is a bad idea. For your particular example, I would use Dataclasses.

https://docs.python.org/3/library/dataclasses.html

I would have an inventory list of cars, and add cars to or remove cars from the list.
from dataclasses import dataclass

@dataclass
class Car:
    make: str
    model: str
    year: int


inventory = [
    Car("Tesla", "S", 2022),
    Car("Tesla", "3", 2019),
    Car('Ford', 'Bronco', 2023)
]

inventory.append(Car("Toyota", "Camry", 2003))
print(*inventory, sep="\n")

print("\n\nIt's Tesla clearout time")
inventory = [car for car in inventory if car.make != "Tesla"]
print(*inventory, sep="\n")
Output:
Car(make='Tesla', model='S', year=2022) Car(make='Tesla', model='3', year=2019) Car(make='Ford', model='Bronco', year=2023) Car(make='Toyota', model='Camry', year=2003) It's Tesla clearout time Car(make='Ford', model='Bronco', year=2023) Car(make='Toyota', model='Camry', year=2003)
If I had a large inventory I would keep the inventory in a database.
(Dec-16-2023, 03:53 PM)RockBlok Wrote: [ -> ]Is this the right approach to use for that sort of task? Or should I be using other functions or techniques?
Normally we don't use global variables like this. Global variables are made for long lived objects and they don't need to be deleted.

The first thing you can do is to minimize the number of global variables through encapsulation. For example if you have only one car in the program, you could have a global variable for this car but it should encapsulate the name and the year of the car, for example
# create a class to encapsulate data such as name and year
class Car:
    def __init__(self, name, year):
        self.name = name
        self.year = year

    def __repr__(self):
        return f'{self.__class__.__name__}({self.name!r}, {self.year!r})'

# let us create a single variable
car = Car("Tesla Model S", 2022)

print(f'Car Name: {car.name}')
print(f'Car Year: {car.year}')

# let us delete the car variable, which destroys the name and year at the same time.
del car
Output:
Car Name: Tesla Model S Car Year: 2022
Suppose that the program now uses more than one car, which is likely. These Car instances won't be stored as global variables. For example you could have only one garage, then you can create a global instance of Garage and park several cars in the garage
class Garage:
    def __init__(self):
        self.cars = set()

    def park(self, car):
        self.cars.add(car)

# create a single global variable
garage = Garage()

garage.park(Car("Tesla Model S", 2022))
garage.park(Car("Chrysler 300C", 2015))

print(garage.cars)
Output:
{Car('Chrysler 300C', 2015), Car('Tesla Model S', 2022)}
The global philosophy is to have a small number of global variables which don't need to be deleted, and encapsulate the rest in classes or functions. By the way classes and functions are long lived global objects that don't need to be deleted.