drerD
drerD

Reputation: 699

Checking if a member variable is initialized by the constructor?

Hi I was just thinking how to design this, so I have a member function that relies on if the member function is initialized. What I am doing currently is as following

class Foo:
def __init__(self, param = None):
    if param :
        self.has_param = True
        self.param = some_value
    else:
        self.has_param = False

def bar(self): % function that uses param
    if not self.has_param:
        raise Exception('param not set')

def bar2(self): % function that doesn't use param
    pass

I googled and searched SO, but nothing seems ringing a bell. Is this Pythonic enough? Or is there any other way to check directly if self.param exists or not? Thanks.

EDIT: some new ideas from the comments

class Foo:
    def __init__(self, param = None):
        self.param = param

    def bar(self):
        if not hasattr(self, param):
            raise Exception('param not set')

Or I can just do this,

class Foo:
    def __init__(self, param = None):
        self.param = param

    def bar(self):
        if not self.param:
            raise Exception('param not set')

Upvotes: 1

Views: 652

Answers (2)

Victor Ruiz
Victor Ruiz

Reputation: 1252

Maybe you can try this:

class Foo:
    def __init__(self, param = None):
        self.param = param

    def __getattribute__(self, key):
        value = super().__getattribute__(key)
        if value is None:
            raise AttributeError(f'Attribute "{key}" not set')
        return value

    def bar(self):
        myparam = self.param

Foo(param='Hello world').bar() # OK
Foo().bar() # Error: Attribute "param" not set

Upvotes: 1

kederrac
kederrac

Reputation: 17322

You can also use try except and gracefully fail

Upvotes: 1

Related Questions