How to have multiple bogus file writers per instruction with?

I read in this answer Is it possible to have an optional / as operator in python? what you might have a dummy file writer with contextmanager

. I want, however, to open several bogus file writers in context with an instruction.

Let's say I create two dummy files: touch a

and touch b

.

Given the first part of the script:

#!/usr/bin/python

from contextlib import contextmanager

# File names
fa="a"
fb="b"

# Dummy file handler
none_context = contextmanager(lambda: iter([None]))()

      

This addon works on a single file file (it prints 2

):

printing=False
with (open(fa) if printing else none_context) as writter:
    print 1 if printing else 2

      

This also works because we are actually reading the files (it prints 1

):

printing=True
with (open(fa, "r") if printing else none_context) as writter, \
    (open(fb, "r") if printing else none_context) as another_writter:
    print 1 if printing else 2

      

However, this doesn't work if we use two dummy files:

printing=False
with (open(fa, "r") if printing else none_context) as writter, \
    (open(fb, "r") if printing else none_context) as another_writter:
    print 1 if printing else 2

      

The error is displayed here:

Traceback (most recent call last):
  File "dummy_opener.py", line 23, in <module>
    with (open(fa, "r") if printing else none_context) as writter, \
  File "/usr/lib64/python2.7/contextlib.py", line 19, in __enter__
    raise RuntimeError("generator didn't yield")
RuntimeError: generator didn't yield

      

Why is this happening? And also: how can I get these multiple commands with open

to work with a bogus file author?

+3


source to share


1 answer


Your code will fail because you already used an iterator on the first call if you call none_context()

in your source block:

none_context = contextmanager(lambda: iter([None]))
printing=False

with open(fa, "r") if printing else none_context() as writter, \
    open(fb, "r") if printing else none_context() as another_writter:
    print 1 if printing else 2

      



You can see using your source code that if you add None

for each open source then the code will work as expected:

none_context = contextmanager(lambda: iter([None,None,None]))()
printing=False

with open(fa, "r") if printing else none_context as writter, \
    open(fb, "r") if printing else none_context as another_writter,\
    open(fb, "r") if printing else none_context as another_writer3:
    print 1 if printing else 2

      

+2


source







All Articles