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

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

Open
zaicruvoir1rominet opened this issue Aug 14, 2024 · 2 comments
Open

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

zaicruvoir1rominet opened this issue Aug 14, 2024 · 2 comments

Comments

@zaicruvoir1rominet
Copy link

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).

@zaicruvoir1rominet zaicruvoir1rominet changed the title Pythonic begin/end interface (adding "with" support) Pythonic open/close interface (adding "with" support) Aug 14, 2024
@astraw38
Copy link
Contributor

Hi @zaicruvoir1rominet , check out the classes here, which can be used:

with Session(slot) as session:
     c_generate_key_ex(session, ...)

@zaicruvoir1rominet
Copy link
Author

Nice !

Would you mind me updating the docs, to make these easier to find ?

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