0

I am working on a Project where I want to raise a error and I have been creating class each time I need a new Exception. I am staying away from generic / builtin errors as they are less descriptive for the purpose I need them for. I came up with a solution but I am not sure if it is a pythonic way to create an instance.

def CustomError(name: str, message: str):
    def constructor(self, msg=message):
        self.message = msg
        return

    def repr_method(self):
        return self.message

    error = type(name,
                 (Exception, object),
                 {'__init__': constructor,
                  '__str__': repr_method})
    return error(msg=message)

This does the trick as I can raise this error with a custom name and message instead of creating a new class every time. Please can someone let me know if this actually is a pythonic way if not then what is the recommended way?

I am expecting someone to confirm that this is actually a valid way of using higher order functions for creating a class instance or point me to a recommended way of doing it.

1
  • 1
    You are raising errors that can't be caught. Exceptions tend to be more generic. Or if fine grained, inherit from some a more generic type. if you have more than a dozen exception types in a package, doesn't it start being a burden to the user? And a dozen are easy to enter manually. Commented Nov 29, 2022 at 15:21

1 Answer 1

3

I wouldn't say it's a pythonic way to be honest. Python has initializers, not "constructors", the constructor would be the magic method __new__ if you really needed that (which is rare). For customizable initializers the decorator @classmethod (multiple factory methods) is the way to go. Also __str__ and __repr__ are not the same (neither is their purpose).

Also most often you actually should define a new class for each type of custom exception (and inherit from the Exception class).

class MyCustomException(Exception):
    def __init__(self, name:str, message:str)->None:
        super().__init__(message) 
        self.name = name
Sign up to request clarification or add additional context in comments.

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.