Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

defaultlist implementation #58

Closed
sbordeyne opened this issue Dec 27, 2019 · 2 comments
Closed

defaultlist implementation #58

sbordeyne opened this issue Dec 27, 2019 · 2 comments

Comments

@sbordeyne
Copy link
Contributor

The collections module already has a defaultdict implementation, but no defaultlist. It's sometimes useful to have a list with a default factory, so that it never throws an IndexError

Here's such an implementation :

class defaultlist(list):
    def __init__(self, *args, factory=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.factory = factory

    def __getitem__(self, index):
        if index >= len(self):
            diff = index - len(self) + 1
            for i in range(diff):
                self.append(self.factory())
        return super().__getitem__(index)

With the accompanying test :

#! /usr/bin/env python
# -*- coding: UTF-8 -*-

import reusables

from .common_test_data import *


class TestDefaultList(BaseTestClass):

    def test_defaultlist_init(self):
        test = reusables.defaultlist(factory=int)

    def test_defaultlist_length(self):
        test = reusables.defaultlist(factory=int)
        self.assertEqual(len(test), 0)
        x = test[5]
        self.assertEqual(x, 0)
        self.assertIsInstance(x, int)
        self.assertEqual(len(test), 6)

    def test_defaultlist_list_factory(self):
        test = reusables.defaultlist(factory=list)
        test[2].append(10)
        self.assertEqual(test, [[], [], [10]])
@cdgriffith
Copy link
Owner

Great idea, I have run into these cases and usually code around them, so having it handy would be cool!

I may even add this to the Box project as well.

Self-note: check that factory is callable before calling.

cdgriffith added a commit that referenced this issue Sep 26, 2020
- Adding #58 defaultlist (Thanks to Dogeek)
- Adding LoggerIOWrapper (Thanks to Dogeek)
- Adding log_it (Thanks to Dogeek) 
- Adding #57 singleton implementation (Thanks to Dogeek)
- Changing line length to 120 and using `black` standard formatter

Co-authored-by: Dogeek <dogeek@users.noreply.github.com>
@cdgriffith
Copy link
Owner

Added in 0.9.6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants