honey-team / ufpy

Ufpy (Useful Python) - package for Python with some useful features
https://honey-team.github.io/ufpy-website
MIT License
3 stars 3 forks source link

Fix sourcery's suggestions #21

Closed bleudev closed 5 months ago

bleudev commented 5 months ago

UDict

  1. suggestion (performance): Inefficient length calculation.

The __len__ method calculates the length by converting self.items to a list, which might be inefficient. Consider directly returning len(self.__dict) instead.

    def __len__(self) -> int:
        return len(self.__dict)
  1. suggestion (performance): Inefficient iteration.

The __iter__ method returns an iterator over self.items, which might be inefficient. Consider directly iterating over self.__dict.items() instead.

    def __iter__(self) -> Iterator[tuple[KT, VT]]:
        return iter(self.__dict__.items())
  1. issue: Deprecated method name.

The nonzero method is deprecated in Python 3. Consider using bool instead.

  1. suggestion (testing): Missing edge case tests for UDict initialization

Consider adding tests for initializing UDict with an empty dictionary, with a dictionary containing various data types, and with a dictionary containing nested dictionaries. This will ensure that the UDict initialization handles all potential edge cases.

  1. suggestion (testing): Test for UDict get item with non-existent key

Consider adding a test case for getting an item with a non-existent key to ensure that the default value is returned correctly.

    def test_get_item(self):
        d = UDict(hello=1, hi=2)
        self.assertEqual(d['hello'], 1)
        self.assertEqual(d.get('non_existent_key', 'default'), 'default')
  1. suggestion (testing): Test for UDict get method with invalid parameters

Consider adding a test case for the get method with invalid parameters (e.g., both key and index provided) to ensure that the appropriate exceptions are raised.

    def test_get(self):
        d = UDict({2: 1, 4: 91, 1: 12}, default=None)
        self.assertEqual(d.get(index=1), d.get(key=2))
        with self.assertRaises(ValueError):
            d.get(key=2, index=1)
  1. suggestion (code-quality): Replace if-expression with or (or-if-exp-identity)
        self.__dict = dictionary or kwargs

(UDict.__init__)

  1. __setitem__: suggestion (code-quality): Swap if/else branches of if expression to remove negation (swap-if-expression)
        values = value if isinstance(value, (list, tuple)) else [value]