2

Let's say I have the following code:

def function(k):
    # do something here

d = { 0: 'a', 1: 'b', 2: 'c' }

function(d[0])

Is it possible for the function to find out what are the other keys in the d? For example is there such a thing:

def function(k):
    print k.__parent__.keys()

I don't think there is such a feature (as it would be a significant security issue). However I don't know much about the technical implementation to know that for sure.

EDIT: The motivation was if everything in Python is an object, is it possible to find other objects that are bound to it, in this case the parent dictionary.

1 Answer 1

5

No, there isn't. Values in Python do not track where they originated from, nor are they 'bound' to one another. Containers can refer to other values, but since any value can be referenced from multiple locations there is no point in tracking back-references.

From function()s point of view, there is absolutely no difference between the following two invocations:

function(d[0])
function('a')

In both cases, k in the function is bound to a python string value, 'a'.

If you need more context in a function, you need to pass it in explicitly:

def function(key, mapping):
    k = mapping[key]

function(0, d)

Now you have the dictionary itself too.

1
  • Thanks. The first part answers my question. I edited my question to be more clear.
    – user31208
    Commented May 15, 2013 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.