2

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)

2
  • how are you checking for undesirable data? Commented Jul 10, 2014 at 20:37
  • did you find a way to do it ? Commented Apr 2, 2019 at 10:27

4 Answers 4

4

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)]
Sign up to request clarification or add additional context in comments.

Comments

2

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).

Comments

1

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]

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.