HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythonMinor

Raising an error if a variable is not created during class initalization

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
variableerrorclassraisingcreatedduringnotinitalization

Problem

I would like to properly raise an error if self._header was not created when I initialize a NewFile object.

This is working now, but perhaps there is more formal way of catching the error below:

class NewFile(object):
    """ Docstring """

    def __init__(self, filename):
        self.localdir = 'C:\\Users\\User\\Documents'
        self.filename = filename
        self.filepath = os.path.join(self.localdir, self.filename)
        self._data = []

        try:
            with open(self.filepath, 'rU') as c:
                rows = csv.reader(c)
                for row in rows:
                    row[:] = [r.lower().strip() for r in row]

                    if row[0].startswith('name'):
                        self._header = row     # Create Header Variable

                    self._data.append(row)

        except IOError:
            raise IOError(
                '"{}" not found in "{}"'.format(self.filename, self.localdir))

        # I would like to raise error if "self._header" was not created
        try:
            self._header
        except AttributeError:
            raise AttributeError(
                'No Header not found in "{}"'.format(self.filename))

def main():
    f = 'samplefile.csv'    
    new = NewFile(f)

if __name__ == '__main__':
    main()

Solution

You got the arrow anti-pattern:

try:
        with open(self.filepath, 'rU') as c:
            rows = csv.reader(c)
            for row in rows:
                row[:] = [r.lower().strip() for r in row]

                if row[0].startswith('name'):
                    self._header = row     # Create Header Variable

                self._data.append(row)

    except IOError:
        raise IOError(
            '"{}" not found in "{}"'.format(self.filename, self.localdir))


4 levels of nesting..., instead, perform exception handling before:

try:
    with open(self.filepath, 'rU') as c:
        rows = csv.reader(c)
except IOError:
    raise IOError(
       '"{}" not found in "{}"'.format(self.filename, self.localdir))


Data processing comes later, so now you have 2 levels of nesting before and 2 levels of nesting after, that is much better than 4 levels of nesting in one place.

Code Snippets

try:
        with open(self.filepath, 'rU') as c:
            rows = csv.reader(c)
            for row in rows:
                row[:] = [r.lower().strip() for r in row]

                if row[0].startswith('name'):
                    self._header = row     # Create Header Variable

                self._data.append(row)

    except IOError:
        raise IOError(
            '"{}" not found in "{}"'.format(self.filename, self.localdir))
try:
    with open(self.filepath, 'rU') as c:
        rows = csv.reader(c)
except IOError:
    raise IOError(
       '"{}" not found in "{}"'.format(self.filename, self.localdir))

Context

StackExchange Code Review Q#105405, answer score: 2

Revisions (0)

No revisions yet.