简体   繁体   中英

Python: trying to create a two variable context manager

I'm new to Python so my guess I'm doing something "syntactically" incorrect. I'm trying to iterate over a grid using row and col as a coordinate system. This my code so far:

from contextlib import contextmanager

# this is the behavior I want
for row in range(10):
    for col in range(10):
        print("row: {}, col: {}".format(row, col))

@contextmanager
def grid_iter():
    for row in range(10):
        for col in range(10):
            yield row, col

# this is my attempt at a context manager so I can reuse this.
with grid_iter() as row, col:
    print("row: {}, col: {}".format(row, col))

This is the output I'm getting:

row: 0, col: 0
row: 0, col: 1
row: 0, col: 2
....
row: 9, col: 7
row: 9, col: 8
row: 9, col: 9
Traceback (most recent call last):
  File "grid_iterator.py", line 17, in <module>
    with grid_iter() as row, col:
AttributeError: __exit__

you should be able to just do:

def grid_iter():
    for row in range(10):
        for col in range(10):
            yield row, col

for row, col in grid_iter():
    print("row: {}, col: {}".format(row, col))

the usage of yield itself makes grid_iter return a generator (you can check this by running print(type(grid_iter())) and then you use it like a normal for-in loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM