-3

I have created a new class under UserList called UList that overrides the __add__ method - it does not allow duplicate items to be added to a list. But when I try to run it, I don't get the expected results:

from collections import UserList

class UList(UserList):
  def append(self,ap_item):
    for ap in ap_item:
        if ap in self:
          raise ValueError(repr(ap) + " already exists in list")
        else:
          return UserList.append(self, ap_item)
  def __add__(self,ad_item):
    for ad in ad_item:
        if ad in self:
          raise ValueError(repr(ad) + " already exists in list")
        else:
          return UserList.__add__(self,ad_item)
  def extend(self, ex_item):
    for ex in ex_item:
        if ex in self:
          raise ValueError(repr(i) + " already exists in list")
        else:
          return UserList.extend(self,ex_item)

How can I get this method to execute correctly?

Jeremy Smyth
  • 23,270
  • 2
  • 52
  • 65
kflaw
  • 424
  • 1
  • 10
  • 26

1 Answers1

1

Your __add__ function lacks a return statement. Any function so lacking implicitly returns None. That explains why your function returns None.

Try this:

return UserList.__add__(self,ad_item)
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • thank you. in the same class i am also overrriding the extend and append methods in the same way, i'll edit my code above to show it, why do those methods work without using a return statement? – kflaw Sep 13 '13 at 19:00
  • I added in return statements after the extend and append methods, but when I tested on extend, I still got None. – kflaw Sep 13 '13 at 19:03
  • `None` is the correct return value from `.extend()` and `.append()`. Try this, for example, `print ([1].append([2]))`. Those functions modify their object in place. – Robᵩ Sep 13 '13 at 19:33