The issue is that you're calling keys
right in your __init__
method, and saving the result. What you want to do instead is to call keys
only when you want to access it.
Now, depending on the requirements of your class, you may be able to do this in a few different ways.
If you don't mind exposing changing the calling code quite a bit, you could make it very simple, just use foo.database.keys()
rather than foo.addresses
. The latter doesn't need to exist, since all the information it contains is already available via the methods of the databases
attribute.
Another approach is to save the bound instance method database.keys
to an instance variable of your DATA
object (without calling it):
class DATA(object)
def __init__(self, database=None):
if database is None:
database = {}
self.database = database
self.addresses = database.keys # don't call keys here!
In the calling code, instead of foo.addresses
you'd use foo.addresses()
(a function call, rather than just an attribute lookup). This looks like a method call on the DATA instance, though it isn't really. It's calling the already bound method on the database dictionary. This might break if other code might replace the database
dictionary completely (rather than just mutating it in place).
A final approach is to use a property
to request the keys
from the database dict when a user tries to access the addresses
attribute of a DATA
instance:
class DATA(object)
def __init__(self, database=None):
if database is None:
database = {}
self.database = database
# don't save anything as "addresses" here
@property
def addresses(self):
return self.database.keys()
This may be best, since it lets the calling code treat addresses
just like an attribute. It will also work properly if you completely replace the database
object in some other code (e.g. foo.database = {"foo":"bar"}
). It may be a bit slower though, since there'll be an extra function call that the other approaches don't need.