patrick
patrick

Reputation: 115

Python: Cancel object creation during initialization

I'm creating a list of objects, and if any have some undesirable data while they're being initialized, I'd like to immediately cancel their initialization, and move on to the next object. Is there a best practice for something like this in Python?

data = [good, bad]
theList = [myObject(some_data) for some_data in data]

# I'd like myObject to determine if it should create itself, after some data parsing.

Should I just return nothing from __new__ ? Or do I just need to separate out the data validation logic from myObject..? Or..?

Thanks!

Context: Given a folder path, I'm checking a bunch of stuff in sequence (is the basename formatted correctly, if so, does a certain file exist, if so, parse it...etc)

Upvotes: 2

Views: 4251

Answers (4)

AMacK
AMacK

Reputation: 1396

You can use a generator. This will create the object whether or not the data is valid, but retain it based on a flag set during the init. e.g.,

data = [good, bad]
theList = [obj for obj in (MyObject(some_data) for some_data in data) if obj.data_is_valid]

Upvotes: 1

Marcin
Marcin

Reputation: 49886

You can raise an exception inside the class' __init__. Note, however, that you can no longer use a list comprehension (which is no huge loss).

Upvotes: 2

user2963623
user2963623

Reputation: 2295

Like the other answer said, validate the data before creating objects. Somewhat like this:

def validate(data):
    if data_is_good: return True
    else: return False

data = [good, bad]
theList = [myObject(some_data) for some_data in data if validate(some_data)]

Upvotes: 4

Mariatta
Mariatta

Reputation: 708

You should check / validate if you have correct data, prior to feeding the data to your object constructor. If data is invalid you should raise an error, eg raise ValueError or your own custom exception. Only when the data is valid should you can with creating the object. in addition you can also raise the exception from your class object's init method too.

Upvotes: 1

Related Questions