Created
May 18, 2018 15:59
-
-
Save marz619/7d78f005f28e4f756026d594e234a73a to your computer and use it in GitHub Desktop.
Context Manager's in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2 | |
# -*- coding: utf-8 -*- | |
""" | |
Learning me some context managers | |
""" | |
# NOTE: see also: contextlib.contextmanager | |
class Context(object): | |
""" | |
Context to learn | |
""" | |
def __init__(self): | |
self.param = "init" | |
def set_param(self, param): | |
""" | |
sets this object's param | |
""" | |
self.param = param | |
def get_param(self): | |
""" | |
returns this object's param | |
""" | |
return self.param | |
def __enter__(self): | |
self.param = "enter" | |
return self | |
def __exit__(self, *args, **kwargs): | |
self.param = "exit" | |
def __str__(self): | |
return "Context(param={})".format(self.param) | |
def __repr__(self): | |
return self.__str__() | |
def main(): | |
""" | |
main func | |
""" | |
ctx = Context() | |
print("init:", ctx) | |
print() | |
ctx2 = Context | |
print("class:", ctx2) | |
with Context() as ctx2: | |
print("init context:", ctx2) | |
print("post init context:", ctx2) | |
print() | |
ctx3 = Context() | |
print("pre-init:", ctx3) | |
with ctx3 as ctx3: | |
print("pre-init context:", ctx3) | |
print("post pre-init context:", ctx3) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment