Q:

Is there a way to define a dictionary only on function creation time?

I want to define a dictionary inside a function. How I can define that dictionary only one time and on the function creation time. I'm trying to prevent dictionary creation on each function call.
currently I define a global dictionary and use that inside the function, but is there another solution?
media_types = {
    1: 'New Video',
    2: 'New Image',
    3: 'New File',
}

def get_media_type(t):
    return media_types.get(t, None)

A:

You can do this by using closures in python
def get_media_type():
    media_types = {
        1: 'New Video',
        2: 'New Image',
        3: 'New File',
    }
    def media_type_wrapper(t):
        return media_types.get(t, None)
    return media_type_wrapper

get_media_type = get_media_type()

For more info on closures in python https://www.programiz.com/python-programming/closure

