Skip to content

Pythonic open/close interface (adding "with" support) #54

@zaicruvoir1rominet

Description

@zaicruvoir1rominet

Hi there !

I'm wondering if you would be open to augmenting pycryptoki with context managers (with block ...) support. This would allow exceptions to propagate normally in pycryptoki code and make forgetting to close/logout/finalize/... functions or accidentally calling close/logout/finalize/... functions when you aren't supposed to impossible.

Current situation

import pycryptoki.session_management

pycryptoki.session_management.c_initialize_ex()

# ... some code ...
raise ValueError("There's a problem here !")
# ... some code ...

pycryptoki.session_management.c_finalize_ex()

The above code would prevent pycryptoki's c_finalize_ex to properly execute.

Potential solution

Make open/logout/initialize functions return context managers:

import pycryptoki.session_management

with pycryptoki.session_management.c_initialize_ex():
    # ... some code ...
    raise ValueError("There's a problem here !")
    # ... some code ...

There is no need to call c_finalize_ex, it is automatically executed in case of an exception or when leaving the with block.
(The context manager returned by c_initialize_ex would also be possible to be interpreted as a "normal" return value, in case user want to fetch this, and to avoid introducing breaking changes).

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