Below is an example of my method my_createand an example of using this method.
@contextmanager
def my_create(**attributes):
obj = MyObject(**attributes)
yield obj
obj.save()
with my_create(a=10) as new_obj:
new_obj.b = 7
new_obj.a
new_obj.b
new_obj.is_saved()
To Ruby / Rails users this may seem familiar. It looks like a method ActiveRecord::create, with code inside a block withacting like, well, a block.
However:
with my_create(a=10) as new_obj:
pass
new_obj.a
new_obj.is_saved()
In the above example, I passed an empty "block" to my function my_create. Things work as expected ( my_objwas initialized and saved), but the formatting looks a bit uncomfortable, and the block withseems unnecessary.
I would prefer to call directly my_createwithout installing the passing block with. Unfortunately, this is not possible with my current implementation my_create.
my_obj = create(a=10)
my_obj
__enter__ __exit__ GeneratorContextManager, .
:
my_create, "" ""? my_create. my_create .
with contextmanager. , , , generator a for, .
, - , , .
:
:
@contextmanager
def header_file(path):
touch(path)
f = open(path, 'w')
f.write('This is the header')
yield f
f.close()
with header_file('some/path') as f:
f.write('some more stuff')
another_f = header_file('some/other/path')
__enter__ __exit__ . . pass ing with, .
Ruby. , Python, ( pass ing with). , ( ?), .