simplify verbose code

by using 'with' statement