Python list, search object name, performance recommendations

Suppose I have the following object:

class Foo(object):
  def __init__(self, name=None):
    self.name = name

  def __repr__(self):
    return self.name

And a list containing multiple instances, for example:

list = [Foo(name='alice'), Foo(name='bob'), Foo(name='charlie')]

If I want to find an object with the given name, I could use the following:

def get_by_name(name, list):
  return [foo for foo in list if foo.name == name][-1]

This obviously means:

print get_by_name('alice', list)
>> alice

However, is there a more efficient data structure or method for retrieving such objects? In fact, the names of objects are known only at runtime and can theoretically change throughout the entire life cycle of an object.

Any tips?

UPDATE:

Thanks Matt Joiners answer, I updated it to support multiple Foo with the same name:

class Foo(object):
    _all_names = {}    
    def __init__(self, name=None):
        self._name = None
        self.name = name        
    @property
    def name(self):
        return self._name        
    @name.setter
    def name(self, name):
        if self._name is not None:
            self._all_names[self._name].remove(self)
        self._name = name
        if name is not None:
            self._all_names.setdefault(name, []).append(self)
    @classmethod
    def get_by_name(cls, name):
        return cls._all_names[name]        
    def __repr__(self):
        return "{0}".format(self.name)

l = [Foo("alice"), Foo("bob"), Foo('alice'), Foo('charlie')]
print Foo.get_by_name("alice")
print Foo.get_by_name("charlie")

Any comments on this approach?

+3
2

:

class Foo(object):
    _all_names = {}
    def __init__(self, name=None):
        self.name = name
    @property
    def name(self):
        return self._name
    @name.setter
    def name(self, name):
        self._name = name
        self._all_names[name] = self
    @classmethod
    def get_by_name(cls, name):
        return cls._all_names[name]
    def __str__(self):
        return "Foo({0})".format(self.name)

a = Foo("alice")
b = Foo("bob")
print Foo.get_by_name("alice")

, , , , .

+8

.

, . - - . , . .

, - , ( name). , . . , . "" , , , .

+1

Source: https://habr.com/ru/post/1756340/


All Articles