1

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')
drerD
  • 629
  • 1
  • 9
  • 24
  • 2
    If you **always** want some value for `param`, why not just get rid of default `None`? In that case, python will raise `TypeError` for you if `param` didn't get any value – Chris Aug 02 '19 at 06:02
  • 1
    Possible duplicate of [How to check if a class member exists without getting exception](https://stackoverflow.com/questions/17591498/how-to-check-if-a-class-member-exists-without-getting-exception) – sal Aug 02 '19 at 06:35
  • 1
    `hasattr` seems a good candidate for this. Check this out: https://stackoverflow.com/questions/17591498/how-to-check-if-a-class-member-exists-without-getting-exception – sal Aug 02 '19 at 06:38
  • @Chris it happens that I don't always need param. – drerD Aug 02 '19 at 20:51

2 Answers2

1

You can also use try except and gracefully fail

kederrac
  • 16,819
  • 6
  • 32
  • 55
1

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

Victor Ruiz
  • 1,192
  • 9
  • 9