mardi 21 septembre 2021

understanding python inner function .how does this works?

def prefix_factory(prefix):
    def prefix_printer(text):
        print(f"{prefix}: {text}")
    return prefix_printer

Now lets execute the below line.

# First time we are executing this
debug = prefix_factory('DEBUG') 

# Second time we are executing as
debug('Hello world')

First time we are executing this

1st execution or assignment of function to the variable debug is assigned the value "DEBUG". My understanding is this is how it has to be executed.

ideally inner function prefix_printer(text) - gets defined inside prefix_factory() 'return prefix_printer' should get an error, stating that text is not available or text is missing.

Second time we are executing as

debug('hello world ') - 2nd execution of the function reference. The question for the second execution is, I am assuming 'hello world' should be considered as a value for the prefix. and text should be blank as we don't call prefix_printer in the return statement with any value. Hence it has to be '' empty string. I am coming from c, C++ background.

My question is, it's the same piece of code 1st-time prefix is assigned, but during the 2nd execution debug('Hello world') it behaves differently. How is it possible, please clarify in detail how this works?

Aucun commentaire:

Enregistrer un commentaire