5

I'm decently new to Python, and I have a question over the implementation of a certain exception methodology. This is the code (shortened):

class OurException(Exception): """User defined Exception""" .... def get_single_value(command: str, connect_string: str, logger: Logger = None, custom_exception: Exception = OurException) -> Tuple[int, str]: .... raise custom_exception("Errors in script\n\nexit .....") 

The exception parameter that I defaulted to OurException cannot be raised this way. However, when I change the custom_exception in the last line to either Exception or OurException, the problem disappears.

In an OOP context, I'd say that as I have defined the parameter to be an Exception, and an Exception is callable that way, it is guaranteed to work. However, my python interpreter and IDE disagree (Pycharm, Python 3.7).

Something is not working the way I think it is working, and I'm interested what that is.

6
  • Are you passing in an argument that's overriding the default parameter when you call it? Commented Sep 30, 2019 at 14:34
  • 2
    OurException doesn't have type Exception. Commented Sep 30, 2019 at 14:34
  • in the case of a class it is not a parameter per se. It is super class from which this class is inheriting Commented Sep 30, 2019 at 14:35
  • Exception is the (super)type of an instance of OurException, not of the class. Commented Sep 30, 2019 at 14:37
  • To add my 2 cents to it. Having the caller pass the exception as an argument is a very weird scenario you have. If the caller is passing the exception class he must be expecting it in same way, so its not exactly an exception in the literal meaning. Commented Sep 30, 2019 at 14:42

1 Answer 1

13

If custom_exception is supposed to be a subclass of Exception, you need to use the type hint Type[Exception], not Exception itself. Otherwise, the type hint specifies that an instance of Exception is expected, and in general an instance of Exception is not callable.

from typing import Type def get_single_value(command: str, connect_string: str, logger: Logger = None, custom_exception: Type[Exception] = OurException) -> Tuple[int, str]: .... raise custom_exception("Errors in script\n\nexit .....") 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the solution. That means that type hinting for Python differs from parameter type definitions of other languages, in that superclasses and subclasses are not checked for type hint validity.
I'm not aware of any language where a class would serve as the type for both an instance of the class and a subclass of the class.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.