0

What's the most Pythonic way to write the below append statement:

class MyClass():
    my_list = None

    def __init__(self):
        self.attr_a = 'whatever_a_is'
        # NOTE below is commented out here because it's
        # NOT needed by most instances:
        # self.my_list = []


my_class_instance= MyClass()
# Append 'a_certain_value' to list attribute if it exists
# else create it:
if my_class_instance.my_list:
    my_class_instance.my_list.append('a_certain_value')
else:
    my_class_instance.my_list = ['a_cetain_value']

Thanks for the help.

2
  • It would probably be best just to tuck that away into an append method of MyClass so the caller doesn't need to worry about it, or just make my_list an empty list from the start. Commented Nov 17, 2018 at 17:08
  • Tks. making it an empty list creates the pitfall of a mutable class attribute when using methods like append (it's being appended to all instances). if it's when I init of a new instance, please refer to my commented code in the init function above. On the other hand, a custom-build append method is an option but I wanted to see if there's a simpler way to handle this in the standard library. Commented Nov 17, 2018 at 17:32

2 Answers 2

1

When the class is initialised, it sets my_list = None. It would be better to set my_list = [], so that the caller can simply append to the list without worrying if it exists or not. This is far more pythonic than what you currently have.



P.S.

A suggestion for future code to make it more "Pythonic" is to replace if my_class_instance.my_list with if my_class_instance.my_list is not None like so:

if my_class_instance.my_list is not None:
    my_class_instance.my_list.append("a_certain_value")
else:
    my_class_instance.my_list = ["a_certain_value"]
Sign up to request clarification or add additional context in comments.

Comments

0

If i get it write, you don't want to set my_list attribute at initialization but only at the first append use ?

A way to do it is to build a custom append method that do the job and are transparent for user :

class MyClass:

    def __init__(self):
        # do something here
        pass

    def custom_append(self, a_certain_value):
        if hasattr(self, 'my_list'):
            self.my_list.append(a_certain_value)
        else:
            self.my_list = [a_certain_value]


my_class_instance = MyClass()

my_class_instance.custom_append('a_certain_value')

But there is few cases where you do not want to initiate my_list to an empty list at instance creation.

4 Comments

Tks. First option isn't helping me avoid the verbose if / else statement. Second is already in my code (please check commented stuff in init)
certainly works. But, as mentioned in my comment in the above post, would prefer a method from standard library if one exists.....
hasattr is a python built-in function. You can do the same job with a try/except statement in your custom methods. Anyay, idid not heard of a special append method that create the atribute if not exist
I was hoping there's something like setdefault for dicts

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.