ProgrammingIncluded / PyYugi

A basic Yu Gi Oh mechanics coded in Python.
GNU General Public License v3.0
8 stars 3 forks source link

Why are the functions defined using a private sub-function? #4

Open cowlicker12 opened 1 year ago

cowlicker12 commented 1 year ago

This might be an advanced python technique that I'm not aware of, but why is there a private version of a function inside of the function? For example:

# Summon a card from deck to hand. Does not check validity rules.
def normal_summon(pf, player, cardind, fpos, cardfaceind=FACE_UP_ATK):
    def _normal_summon():
        pf.FIELD[player][fpos].insert(0, pf.HAND[player].pop(cardind))
        pf.FIELD[player][fpos][0]["cardface"] = cardfaceind
        pf.PREV_NORM_SUMMON = pf.ROUND_CNT
        return pf.FIELD[player][fpos]

    pf.AS.append(_normal_summon)

Inside of normal_summon(), we have _normal_summon(). Why is this?

ProgrammingIncluded commented 7 months ago

Hi @cowlicker12, this is a bit on the architecture decision and a bit of a preference. In this case, the normal_summon() is appending to a stack of function pointers which will later be resolved.

So in this case, we want _normal_summon() to capture the variables player and other values passed to normal_summon() as part of callback. This is often called a closure and commonly used in functional programming-like architecture. Or very common in Javascript / NodeJS programming techniques where callbacks are required.

There could have been other ways to approach this implementation such as a class instance or an external function that returns a closure. However, this was the most succinct to write inlined, and no other function requires this _normal_summon definition so a private function was used.

Hope that helps. Feel free to close if this makes sense.