Search code examples
pythonclasspython-3.xconstructorinitializer

Is it pythonic to call methods from inside class initializer?


I feel it is a more general question, but here is an example I am considering: I have a python class which during its initialization goes through a zip archive and extracts some data.

Should the code-chunk below be written explicitly inside the "def init" or should it be made as a method outside which will be called inside the "def init"? Which approach is the most 'Pythonic' one?

with ZipFile(filename, "r") as archive:
    for item in archive.namelist():
        match = self.pattern.match(item)
        if match:
            uid = match.group(2)
            time = match.group(3)
        else:
            raise BadZipFile("bad archive")

Solution

  • If you want to execute the statements you are showing in more then one place, then there's really no discussion. Without a method or a function for this task, you will be violating the DRY principle.

    Otherwise... well I'd write a method regardless. The task you are showing is nicely self contained and should be abstracted under a descriptive name. It will make your __init__ method easier to maintain and easier to read.

    You should also consider writing the code you are showing as a module level function accepting a pattern as an argument, because besides the self.pattern attribute the task does not seem to have a strong connection to the data and methods of your class instances (from what we now).