pythontypessyntax-errorglobal-variables

Can't define a global variable that has a type within a function


I'm trying to create a function that reloads a global bank:

import json

type Bank = dict[str, dict[str: int | float]]

def get_ball() -> None:
    """
    _summary_
    Reloads the bank dict from the bank.json file
    """
    global bank
    with open("bank.json", "r") as f:
        bank: Bank = json.load(f)  # Error
        # bank = json.load(f)      # Works fine
    print(bank)

get_ball()
print(bank)

But it raises a SyntaxError: annotated name 'bank' can't be global

When it doesn't have an assigned type it works just fine (see the commented out line). What do I have to do?


Solution

  • You should declare it outside function

    type Bank = dict[str, dict[str: int | float]]
    
    #bank:Bank
    bank:Bank = {}  # or with default value at start
    
    def get_ball() -> None:
        """
        _summary_
        Reloads the bank dict from the bank.json file
        """
        global bank
        
        with open("bank.json") as f:
            bank = json.load(f)
    
        print(bank)
    
    get_ball()
    print(bank)
    

    But it would be better if you wouldn't use global at all

    import json
    
    type Bank = dict[str, dict[str: int | float]]
    
    def get_ball() -> Bank:
        """
        _summary_
        Reloads the bank dict from the bank.json file
        """
        
        bank:Bank = {}  # default value at start
        
        with open("bank.json") as f:
            bank = json.load(f)
    
        return bank
    
    data:Bank = get_ball()
    print(data)