0

A temporary exception class is defined dynamically using 'type' in a python script meant to be used as module. When an instance of this class is caught in importing script it doesn't recognize the class. Below is code snippet

# the throwing module, defines dynamically
def bad_function():
    ExceptionClass = type( "FooBar", (Exception,),
        { "__init__": lambda self, msg: Exception.__init__(self, msg) })
    raise ExceptionClass("ExceptionClass")

the using code

import libt0

try:
    libt0.bad_function()
#except libt0.FooBar as e:
#print e
except Exception as e:
    print e
    print e.__class__

can it be explained why libt0.FooBase is not visible to this script? observer output of last line.

2 Answers 2

2

It's not clear how you expect FooBar to exist without doing something like this

def bad_function():
    ExceptionClass = type( "FooBar", (Exception,),
        { "__init__": lambda self, msg: Exception.__init__(self, msg) })
    globals()['FooBar'] = ExceptionClass
    raise ExceptionClass("ExceptionClass")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works. I must admit, my python knowledge is quite shallow. All I have learned in python is syntax and some libraries for survival. I am mostly C/C++ guy. Help really appreciated @gnibbler.
2

You created the class inside a function, so it doesn't exist as a name in the module's global namespace. In fact, it doesn't exist at all except while bad_function is executing. It's the same reason why this fails:

# file1.py
def good_function():
   x = 2

# file2.py
import file1
print file1.x

Your exception class is just a local variable inside bad_function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.