IanHacker
IanHacker

Reputation: 581

Counting the real number of arguments in python

Is there any way to count the real number of arguments passed to a function in python, even when some defaults values are set? I'm trying to write a function, which replaces a certain range of a text file with 0 (or an offset value), but it doesn't work because python returns the number of arguments including the arguments which are not passed.

The input file is like this:

foo.txt

0
1
2
3
4
5
6
7
8
9
10
11

Here is the code:

import os
import numpy as np
from inspect import signature

def substitute_with(FILE, start, end=10, offset=0):

    sig = signature(substitute_with)
    params = sig.parameters
    print('len(params): %d' % len(params))

    filename, file_extension = os.path.splitext(FILE)  
    file_i = FILE
    file_o = filename + '_0' + file_extension

    Z = np.loadtxt(file_i)

    with open(file_o, "w") as fid:
        length_Z = len(Z)
        print('length_Z: %d' % length_Z)

        if(len(params) < 3): # gives me 4, but actually, I need 2 here!
            end=length_Z

        X = np.concatenate([np.ones((start)), np.zeros((end-start)), np.ones((length_Z-end))])
        Y = np.concatenate([np.zeros((start)), np.ones((end-start)), np.zeros((length_Z-end))])*offset

        A=Z.T*X+Y

        for i in range(0, length_Z):
            fid.write('%d\n' % (A[i]))

#substitute_with('foo.txt',4,8)
#substitute_with('foo.txt',4,8,2)
substitute_with('foo.txt',4)

... This works only when the 3rd argument 'end' is passed. Without the 3rd argument, from 4 through the end (11) are supposed to be replaced with 0. But, in reality, from 4 through 9 are replaced with 0.

I reluctantly set a default value (=10) to end, otherwise the compiler gives me the following error:

TypeError: substitute_with() missing 1 required positional argument: 'end'

So, how would you guys solve this? Please don't tell me to check the length of the file first and then give it to the function. It should be done inside the function. In MATLAB, 'nargin' returns the real number of arguments, so this kind of logic would work easily. If python cannot do this, it's gonna be a shame.

Upvotes: 1

Views: 805

Answers (1)

NPE
NPE

Reputation: 500495

Just use None as the default for end:

def substitute_with(FILE, start, end=None, offset=0):
   ...
   if end is None:
        end = length_Z
   ...

Upvotes: 2

Related Questions