In the general case, you cannot deduce the name from a value (there might be no name, there might be multiple ones, etc); when you call your hypothetical makedict(name)
, the value of name
is what makedict
receives, so (again, in the general case) it cannot discern what name (if any) the value came from. You could introspect your caller's namespaces to see if you're lucky enough to hit a special case where the value does let you infer the name (e.g., you receive 23
, and there's only one name throughout the namespaces of interest which happens to have a value of 23
!), but that's clearly a fragile and iffy architecture. Plus, in your first example case, it's absolutely guaranteed that the special case will not occur -- the value in name
is exactly the same as in either foo
or baz
, so it's 100% certain that the name for that value will be hopelessly ambiguous.
You could take a completely different tack, such as calling makedict('name type', locals())
(passing locals()
explicitly might be obviated with dark and deep introspection magic, but that's not the most solid choice in general) -- pass in the names (and namespaces, I suggest!) and have makedict
deduce the values, which is obviously a much more solid proposition (since each name has exactly one value, but not viceversa). I.e.:
def makedict(names, *namespaces):
d = {}
for n in names.split():
for ns in namespaces:
if n in ns:
d[n] = ns[n]
break
else:
d[n] = None # or, raise an exception
If you're keen on digging out the namespaces by introspection, rather than have them cleanly specified by the caller, look at inspect.getouterframes -- but I suggest you reconsider.
The second issue you raise is quite different (though you could use inspect
functions again to introspect the caller's name, or a function's own name -- what a peculiar idea!). What's in common in the two cases is that you're using extremely powerful and dangerous machinery to do a job that could be done much more simply (easier to ensure correctness, easier to debug any problems, easier to test, etc, etc) -- far from having decorators be "overkill", they're far simpler and more explicit than the introspection you propose. If you have a zillion methods all of the form:
def item_blah(self, item):
dispatch("blah", item)
the simplest way to create them might be:
class Item(object): pass
def _makedispcall(n):
def item_whatever(self, item):
dispatch(n, item)
item_whatever.__name__ = 'item_' + n
return item_whatever
for n in 'create delete blah but wait theres more'.split():
setattr(Item, 'item_' + n, _makedispcall(n))
Avoiding repetition is an excellent idea, but runtime introspection is not generally the best way to implement that idea, and Python offers many alternative ways to such implementation.