Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I detect if the caller passed any variables to my function in Python?
    primarykey
    data
    text
    <p>I guess the subject sounds pretty stupid, so I'll show some code:</p> <pre><code>def foo(**kwargs): # How can you detect the difference between (**{}) and ()? pass foo(**{}) foo() </code></pre> <p>Is there any way to detect inside of foo, how the method was called?</p> <h3>Update 1</h3> <p>Because there were some comments why you possible want to do something, I'll try to explain some background.</p> <p><code>super(MyClass, self).foo(*args, **kwargs)</code> sucks - a lot of wasteful duplication. I want to write 'self.super()'. In this case, just call the super class and hand over all parameters that the calling method got as well. Works like a charm.</p> <p>Now the problematic magic part:</p> <p>I want to say 'self.super(something)' and in this case, only 'something' is passed to the super method. Works for most cases.</p> <p>This is where it breaks:</p> <pre><code>def foo(self, fnord=42, *args, **kwargs): self.super(*args, **kwargs) </code></pre> <p>So the super method should get the arguments that the calling method - however if <code>*args</code>, <code>**kwargs</code> are empty, currently the library can not detect this condition and passed all arguments including 'fnord'...</p> <p>Of course I could use <code>self.super.foo(*args, **kwargs)</code> as an alternative syntax but that's lame :-)</p> <p>PS: Yes, I know p3k's super, but still not nice and it does not work with Python 2.x...</p> <h3>Update 2</h3> <p>Actually even Python's ast module removes the <code>**{}</code> (<code>ast.parse('foo(**{})')</code>) so it looks like this happens so early in the parsing process that you can not get this information later on...</p> <p>So in the end I have either to give up on that specific problem (raising an AmbiguousSyntaxError) or to use text parsing as proposed by ~unutbu. Re-thinking my approach, the latter might actually feasable because I only need to know if it is <code>self.super(\s*)</code>, <code>self.super(\S+)</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload