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

implement KaitaiStruct as context manager #7

Merged
merged 1 commit into from
Oct 11, 2016

Conversation

dgladkov
Copy link
Collaborator

Followup to #6. KaitaiStruct now implements context manager interface, so you can use with keyword like with any other resource. Examples of context manager usage with automatically closed resource:

>>> with KaitaiStruct.from_file(filename) as ks:
...     print ks._io._io.closed
... 
False
>>> ks._io._io.closed
True
>>> myio = KaitaiStream(open(filename))
>>> myio._io.closed
False
>>> with KaitaiStruct(myio) as ks:
...     print ks._io._io.closed
... 
False
>>> ks._io._io.closed
True

This is generally accepted way to deal with resources that need to be closed in Python. However, you can create instance of KaitaiStream manually, but then you have to remember to close the resource.

>>> ks = KaitaiStruct.from_file('setup.py')
>>> ks._io._io.closed
False
>>> ks.close()
>>> ks._io._io.closed
True

@GreyCat GreyCat merged commit a78e0f8 into kaitai-io:master Oct 11, 2016
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

Successfully merging this pull request may close these issues.

2 participants