Skip to content

Functions defined inside if blocks don't do variable lookup correctly #263

Closed
@LeszekSwirski

Description

@LeszekSwirski

If I define an inner function inside an if block, it fails to look up values that it closes over, doing e.g. a global lookup instead:

value = 4
def make_func(value):
    if value == 0:
        def inner():
            log.info(f"value = {value}")
        return inner

make_func(0)()
---
value = 4

Interestingly, however, if there is an inner function defined outside the if block, the one inside the if block works as it should.

value = 4
def make_func(value):
    if value == 0:
        def inner():
            log.info(f"value = {value}")
        return inner
    
    def fix():
        pass

make_func(0)()
---
value = 0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions