Jamie Dunbar
Jamie Dunbar

Reputation: 109

Is there a more pythonic way to return instantiated classes on demand?

I wondered if there was a more Pythonic way of doing this. I have a bunch of dataclasses that havce attributes that I have set already, however, I won't always need each one, or, I may need to re-use them. At the moment they are all being instantiated and set to variables then imported when needed. I feel like that there must be a better way to do this.

For example, this is what I have now

The main class - truncated, it has methods etc too.

@dataclass
class Raster():
    name: str
    s3_path: str
    file_name: str

Then below I have this.

land = Raster(s3_path=xxxx,file_name=xxx)
sea = Raster(s3_path=xxxx,file_name=xxx)

Would it make more sense to have

def getLand():
    return Raster(s3_path=xxxx,file_name=xxx)

It all feels a little clunky. Within the class I have used the @cache decorator too so that when I call land.raw it loads the data the first time and then all other times it just returns from cache.

Upvotes: 0

Views: 40

Answers (1)

chepner
chepner

Reputation: 532153

Such functions, acting as alternative constructors, are generally defined as class methods.

@dataclass
class Raster:
    name: str
    s3_path: str
    file_name: str

    @classmethod
    def make_land(cls):
        return cls(s3_path=xxxx, filename=xxx)


land = Raster.make_land()
sea = Raster.make_land()

The name used is mostly a matter of opinion and personal preference, but anything with get in the name suggests access to portion of an existing object, rather than something that creates a new object.

Upvotes: 1

Related Questions