3

Suppose a function spam has signature spam(ham=None). The following three calls will all cause the local variable ham in spam's namespace to have value None:

spam()
spam(None)
spam(ham=None)

How can spam find out which of these three alternatives was actually used?

kjo
  • 33,683
  • 52
  • 148
  • 265
  • 2
    Why do you need to know? – Daniel Roseman Sep 11 '12 at 20:35
  • 1
    Why do you need to know why I need to know? – kjo Sep 11 '12 at 20:53
  • 1
    Because it's a wicked thing to do, for the reasons explained by @BrenBarn. – Lukas Graf Sep 11 '12 at 21:11
  • The answer is you don't need to know. – martineau Sep 11 '12 at 22:03
  • 1
    @kjo: when people ask "why do you need to know," they mean, "that's difficult or impossible, or there are multiple ways to do it, and if you give us more context, we can help you find a good solution." – Ned Batchelder Sep 12 '12 at 01:41
  • @NedBatchelder: If I know that what someone wants to do is impossible, then I will post just that. If what they want to do is difficult, and I'm up to writing it out, I do so, otherwise I pass over the question. Similarly, if there are many ways to do it, I give it my best shot, pointing out it is one of many possibilities, or pass up the question. IOW, I choose to treat the poster as an adult who knows what he/she wants, and who knows how to express it clearly. Replies like "Why do you need to know?" imply exactly the opposite attitude. – kjo Sep 12 '12 at 02:53
  • @kjo: I think purely textual media like stack overflow are difficult because they encourage terseness, and don't carry enough social cues to accurately interpret intent. I believe Daniel was not maligning you, but I can see how it came off that way. – Ned Batchelder Sep 12 '12 at 14:28
  • deserves the `[spam]` tag ;P (after +1) – n611x007 Jun 10 '15 at 14:35

1 Answers1

7

It can't. This question describes a way to use a decorator to wrap the function and set the passed arguments as attributes on it. But there is no way to find out from within spam without help from outside. You have to intercept the call with a function that accepts **kwargs and use that to store the information.

However, you should be cautious of doing this. The different ways of passing in arguments are supposed to work the same. If you do something that makes them work differently, you will confuse many people who try to use your function.

Community
  • 1
  • 1
BrenBarn
  • 242,874
  • 37
  • 412
  • 384