Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not creating an object when conditions are not met in python?

Is it possible to not create an object if certain conditions are not met in the constructor of a class?

E.g.:

class ABC:
    def __init__(self, a):
        if a > 5:
            self.a = a
        else:
            return None

a = ABC(3)
print(a)

This should print None (since it should not create an Object but return None in this case) but currently prints the Object...

like image 913
mrCarnivore Avatar asked Dec 14 '22 19:12

mrCarnivore


2 Answers

you can use a classmethod as an alternate constructor and return what you want:

class ABC:
    def __init__(self, a):
        self.a = a

    @classmethod
    def with_validation(cls, a):
        if a > 5:
            return cls(a)
        return None


a = ABC.with_validation(10)

a
<__main__.ABC at 0x10ceec288>

a = ABC.with_validation(4)

a

type(a)
NoneType
like image 180
salparadise Avatar answered Dec 17 '22 22:12

salparadise


This code seems to show that an exception raised in an __init__() gives you the effect you want:

class Obj:
    def __init__(self):
        raise Exception("invalid condition")

class E:
    def __call__(self):
        raise Exception("raise")

def create(aType):
    return aType()

def catchEx():
    e = E()
    funcs=[Obj, int, e]

    for func in funcs:
        try:
            func()
            print('No exception:', func)
        except Exception as e:
            print(e)

catchEx()

Output:

invalid condition
No exception: <class 'int'>
raise
like image 29
quamrana Avatar answered Dec 17 '22 22:12

quamrana