Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
cowlicker12 opened this issue Oct 1, 2023 · 1 comment
Open

Comments

@cowlicker12
Copy link

cowlicker12 commented Oct 1, 2023

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
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants