Ge0Pyth0n
Ge0Pyth0n

Reputation: 91

How to efficiently try if variables don't exist in Python

I have a .yaml file (params) which contains a dictionary of names

country_names:
    country_1: Wales
    country_2: England
    country_3: Scotland
    country_4: 

As you can see, country_4 is left empty. This is intentional. In the interest of scalability and user friendliness, I want to be able to run the script with a known maximum number of country_names (i.e. 4) but an unknown number of country values. I also don't want to have to hardcode the script every time someone makes a change to the yaml.

import dictor
import geopandas as gpd
import pandas as pd
import yaml

country_1 = dictor(params, 'country_names.country_1')
if country_1 is None:
    del country_1
else: 
    country_1_path = path_to_dir + '/' + country_1 + '.geojson'
    country_1 = gpd.read_file(country_1)

country_2 = dictor(params, 'country_names.country_2')
if country_2 is None:
    del country_2
else: 
    country_2_path = path_to_dir + '/' + country_2 + '.geojson'
    country_2 = gpd.read_file(country_2)

country_3 = dictor(params, 'country_names.country_3')
if country_3 is None:
    del country_3
else: 
    country_3_path = path_to_dir + '/' + country_3 + '.geojson'
    country_3 = gpd.read_file(country_3)

country_4 = dictor(params, 'country_names.country_4')
if country_4 is None:
    del country_4
else: 
    country_4_path = path_to_dir + '/' + country_4 + '.geojson'
    country_4 = gpd.read_file(country_4)          

and then I concatenate the country variables that are produced above...

try:
   countries = pd.concat([country_1, country_2, country_3, country_4])
except:
    pass
        try:
            countries = pd.concat([country_1, country_2, country_3])
        except:
            pass 
            try:
                countries = pd.concat([country_1, country_2])
            except:
                pass

The script does exactly what I want it do and doesn't fall over. However, as you can see, the LOC count is quite high and it's quite messy. Is there a more efficient or Pythonic way of doing this whilst keeping things explicit rather than implicit? Also I am happy for other suggestions, for example, if I am using except and pass incorrectly.

*I'm also happy to change the question title if anyone has suggestions.

Upvotes: 1

Views: 43

Answers (1)

Thomas Schillaci
Thomas Schillaci

Reputation: 2453

You can do it this way, for example:

# The variables that exist, country_2 and country_4 were not initialized
country_1 = 0
country_3 = 1

countries = []
for i in range(1, 5):
    if f'country_{i}' in globals():
        countries.append(globals()[f'country_{i}'])
print(countries)

[0, 1]

Upvotes: 2

Related Questions