Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get args passed to a function

Is there a way in python to get the arguments that were passed by the caller to a function? Here is what I'm trying to do:

# function
def repeat(self, min=None, max=None, optional=False):
    do_something()

I need to do something differently based upon whether one or more args were passed to it. For example:

r.repeat('hello').repeat(2,None)

Needs to be differentiated between:

r.repeat('hello').repeat(2) # only one arg passed

I thought locals might be a good place to start, but it picks up the default arg from the function so doesn't work for my purposes:

{'_max': None, '_min': 2, 'discrete': [], 'optional': False, 'max': None, 'min': 2, 'self': r'(hello)'}

In other words, max should not show up as one of the args. Is this possible to do in python? I've also tried using inspect, but that seems to show the defaults as well:

(Pdb) inspect.getargvalues(f)
ArgInfo(args=['self', 'min', 'max', 'optional', 'discrete'], varargs=None, keywords=None, locals={'pdb': <module 'pdb' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pdb.py'>,
 '_max': None, '_min': 2, 'discrete': [], 'optional': False, 'max': None, 'min': 2, 'self': r'(hello)', 'f': <frame object at 0x101e2de68>})
like image 706
David542 Avatar asked Apr 25 '26 02:04

David542


1 Answers

I think there are simpler solutions to your problem. The simplest way I know is to have a default value which could not possibly be passed in as an actual argument. Create a dummy object and use that as the default:

dummy_default = object()

def my_function(x=dummy_default):
    actual_x = None if x is dummy_default else x
    # ...

This way, actual_x will be None either if no argument is passed, or None is passed explicitly, but you can distinguish between these cases by testing x is dummy_default.


You could also use *vargs:

def my_function(*vargs):
    if len(vargs) > 1:
        raise TypeError('Too many arguments')
    x = vargs[0] if len(vargs) >= 1 else None
    # ...

The expression len(vargs) == 0 will tell you whether no argument was passed.

This way is a bit worse because making keyword-arguments work too is more complicated, you won't get a useful argument hint if you use an IDE, and you need to do your own error-handling for wrong numbers of arguments.

like image 90
kaya3 Avatar answered Apr 27 '26 15:04

kaya3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!