[Python] How to pickle closure?

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    Example:

    import pickle

    def function():
    def closure():
    pass
    return closure

    pickle.dumps(function())


    Which yields:

    AttributeError: Can't pickle local object 'function.<locals>.closure'


    There is this question How to refactor method returning closure to be pickleable? which has an answer that suggests import dill as pickle - but in my case that would require monkey patching.

    Since I also found some examples Can Python pickle lambda functions? on how to pickle lambda functions (which isn't support by pickle out of the box either), I have some hope that there is a way to actually pickle function() with stdlib pickle - only by refactoring above code example.

    Continue reading...

Compartilhe esta Página