How to make sure a class function wont be called until another class function has been called first?

python, python-2.7

Solution

I think the most pythonic way would be to throw an exception:

def get_datalength(self):
    try:
        return self.data_length
    except AttributeError:
        raise AttributeError("No length call create_fields first")

Simple reason: There is no way to prevent the user to call this function on the object. Either the user would get a `AttributeError` and would not understand what is going on, or you provide an own Error class or at least error message.

BTW: It is not pythonic creating getter methods(there are no such things as 'private members') If you need to do smaller operation on the value returning it have a look at the `@property` decorator

@property
def datalength(self):
   return do_some_stuff(self.data_length)

Problem

I have a class object that creates some data fields: ``` class DataFields(object): _fields_ = ['field_1', 'field_2', 'data_length'] def __init__(self, data=None): if data != None: self.create_fields(data) def create_fields(self, data): i = 0 for field in self._fields_: setattr(self, field, data[i]) i += 1 def get_datalength(self): return self.data_length ``` What is the best way to make sure that the `get_datalength()` function cannot be called unless the `data_length` field has been created (that is, unless the `create_fields()` function has been called once). I've thought about either using a variable that gets initialized in the `create_fields` and is checked in `get_datalength()` or `try-except` inside the `get_datalength()` function. What is the most Pythonic (or the best) way?

Original source