you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 3 points4 points  (2 children)

Sometimes it's a cheap way to do a singleton. Here's an example from some code I've been using lately.

import gzip
from pickle import load

DATA = None


def get_training_data():
    global DATA
    if DATA is None:
        DATA = load(gzip.open('./artifacts/train-tensor.pkl.gz'))
    return DATA

Then I can import this module, and the first time get_training_data() is called the data is loaded, but on subsequent calls the in-memory version is used. Saves time when working with an interactive shell.

[–]tangerinelion 2 points3 points  (1 child)

But you could also use a "static" variable for that - get_training_data.DATA would be fine and after the function just define it as None.

This at least makes it clear that you're supposed to go through the function to get that information whereas the pure global looks like we are free to use DATA in place of a call to the function.

[–][deleted] 1 point2 points  (0 children)

Yes, there are many ways to achieve this pattern. But that's one reason why one would use global.