Conditionally subclassing based on Import

Gary Herron gherron at islandtraining.com
Fri Oct 3 09:02:08 CEST 2008


David Pratt wrote:
> Hi, just want to conditionally base a class on another if it can be
> imported,  otherwise base it on object. Does the following look ok 
> for this?
>
> try:
>      import foo.bar
> except ImportError:
>     MyBase = foo.bar.Baz
> else:
>     MyBase = object
>
> class Something(MyBase):
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list

Ahhh...   I believe you've got that backwards.

try:
    import foo.bar
    MyBase = foo.bar.Baz
except ImportError:
    MyBase = object

or
   
try:
    import foo.bar
except ImportError:
    MyBase = object
else:
    MyBase = foo.bar.Baz


Gary Herron




More information about the Python-list mailing list