0

Is is possible to create multiple variables in an async with statement ?

I know that the equivalent synchronous version exists from here: Multiple variables in a 'with' statement?

so the synchronous version looks like this:

# some files
f1 = 'tests/test_csv.csv'
f2 = 'tests/some_file.txt'
f3 = ''


with open(f1) as a, open(f2) as b:
    contents_1 = a.readlines()
    contents_2 = b.readlines()

print('this is contents 1:')
print(contents_1)

print('this is contents 2:')
print(contents_2)

And this works nicely.

But will the same extend to the async version in a similar way ?

for example like this:

async with A() as a, B() as b:
    while True:
        result_1 = await a.A()
        result_2 = await b.B()
        if (result_1):
            print(result_1)
        if (result_2):
            print(result_2)

would the above work or, if not, how could one make this work?

D.L
  • 4,339
  • 5
  • 22
  • 45

1 Answers1

0

Yes, it's allowed. The documentation says that the syntax of async with is the same as with, but with the keyword async before it.

The specification of with says that listing multiple items is equivalent to nesting them. So your code would be equivalent to:

async with A() as a
    async with B() as b:
        while True:
            result_1 = await a.A()
            result_2 = await b.B()
            if (result_1):
                print(result_1)
            if (result_2):
                print(result_2)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks for that, i am just aware that `async` behaviour is specifically different from `sync` behaviour. So i am not just asking about **both** *syntactically* and also *behaviourally.*.. – D.L Nov 03 '22 at 19:04
  • Behaviorally it acts just like nested single-variable statements. – Barmar Nov 03 '22 at 19:31
  • If you want to know what `async with` does in general, that's a different question, since it has nothing to do with multiple variables. – Barmar Nov 03 '22 at 19:32
  • Minor point: OP uses `a.A()` and `b.B()`, which is confusing since it implies `A()` and `B()` return objects that themselves have methods `A` and `B`. Would be clearer if written as `a.method_1()` or similar. – craigb Nov 03 '22 at 22:51