Finding the instance reference of an object

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Oct 16 12:04:10 EDT 2008


On Thu, 16 Oct 2008 08:04:23 -0700, Astley Le Jasper wrote:

> I'm creating mulitple instances, putting them in a list, iterating
> through the list to send them to some functions where process them with
> some instance specific parameters. Something along the lines of:
> 
> bob = someobject()
> harry = someobject()
> fred = someobject()
> 
> parameterdict = {'bob': (0,1,2), 'harry': (3,4,5), 'fred': (6,7,8)}
> people_list = (bob, harry, fred)
> 
> for person in people_list:
>   add_parameters(person)
> 
> def add_parameters(person)
>   mytuple = parameterdict[??????instance.name????] 
>   person.x = mytuple[0]
>   person.y = mytuple[1]
>   person.z = mytuple[2]
> 
> ... alternatively there is probably a very much easier way of doing it.


Assuming that someobject() objects are hashable, you can do this:

# use the objects themselves as keys, not their names
parameterdict = {bob: (0,1,2), harry: (3,4,5), fred: (6,7,8)}
people_list = [bob, harry, fred]

but of course that doesn't work if someobject() items aren't hashable 
(say, lists or dicts).

But in my opinion, this is probably the best way (untested):

def add_parameters(person, x, y, z):
    # note we don't use any global variables
    person.x = x
    person.y = y
    person.z = z

parameters = [(0,1,2), (3,4,5), (6,7,8)]
people = [bob, harry, fred]
for person, args in zip(people, parameters):
    add_parameters(person, *args)



-- 
Steven



More information about the Python-list mailing list