Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable scope and Try Catch in python

import Image import os for dirname, dirs, files in os.walk("."):     for filename in files:         try:             im = Image.open(os.path.join(dirname,filename))         except IOError:             print "error opening file :: "  + os.path.join(dirname,filename)         print im.size 

Here I'm trying to print the size of all the files in a directory (and sub). But I know im is outside the scope when in the line im.size. But how else do I do it without using else or finally blocks.

The following error is shown:

Traceback (most recent call last):   File "batch.py", line 13, in <module>     print im.size NameError: name 'im' is not defined 
like image 904
shahalpk Avatar asked Jun 25 '12 08:06

shahalpk


People also ask

What are variable scopes in Python?

What is Variable Scope in Python? In programming languages, variables need to be defined before using them. These variables can only be accessed in the area where they are defined, this is called scope. You can think of this as a block where you can access variables.

Does Try create scope in Python?

The built-in try function does not create its own scope. Modules, classes, and functions create scope. A complete description of Python scopes and namespaces in the docs.

Does try except have scope?

In the except case text is never assigned. You could set text = None in that block or before the try . This isn't a scope problem.

How do you make a variable inside a try except block public?

Solution 1 What you need to do is declare your variable outside of the try scope. Before the try scope so it the variable still exists in your except block. This will raise the exception but x will still have scope (lifetime) and will print out in the 2nd exception case.


1 Answers

What's wrong with the "else" clause ?

for filename in files:     try:         im = Image.open(os.path.join(dirname,filename))     except IOError, e:         print "error opening file :: %s : %s" % (os.path.join(dirname,filename), e)     else:         print im.size 

Now since you're in a loop, you can also use a "continue" statement:

for filename in files:     try:         im = Image.open(os.path.join(dirname,filename))     except IOError, e:         print "error opening file :: %s : %s" % (os.path.join(dirname,filename), e)         continue      print im.size 
like image 141
bruno desthuilliers Avatar answered Sep 27 '22 21:09

bruno desthuilliers