Default parameters in script module

Asking here because I’m approaching this for the first time. I have a function I want to take 2 parameters sometimes, 3 the other but I don’t ever want to have confusion for the end user.

In python we can do this simply:

def func(param1, param1, param3="default")

So far for Java I have discovered function overloading, but I wanted to check what everyone’s preferred method is, and if possible see some examples.

Thanks,

Nick

This is to be exposed to the user as a script function installed by the module? If so, I recommend using the fully keyword-compatible signature, like this one from my EtherNet/IP module:

import org.python.core.ArgParser;
.....
	@KeywordArgs(names = { "name", "slot", "id", "port" }, types = { String.class, Integer.class, Long.class,
			Integer.class })
	static public CipMsgProcessor getMsgPort(PyObject[] args, String[] keywords) {
		ArgParser ap = new ArgParser("getMsgPort", args, keywords, new String[] { "name", "slot", "id", "port" });
		String name = ap.getString(0, null);
		int slot = ap.getInt(1, -1);
		long id = (Long) Py.tojava(ap.getPyObject(2, new PyLong(-1L)), Long.class);
		int port = ap.getInt(3, 1);
		........
1 Like

Yeah, the critical piece is making your Java method accept PyObject[], String[] - that’s what Jython uses to allow keyword args invocation.

I’ll also plug PyArgParser over Jython’s ArgParser or the older PyArgumentMap in the Ignition codebase.

@PGriffith @pturmel

This might be a bit brute, but this is what I have done for now. Note that this is not used in the designer or client, we use it to parse SAML response, and it is called from the user attribute mapping of an ID provider:

    @Override
    protected ArrayList<String> assignRoles(List<String> samlResponse, String hostName) {
        return assignRoles(samlResponse, hostName, "US");
    }

    @Override
    protected ArrayList<String> assignRoles(List<String> samlResponse, String hostName, String country) 
    {

    }

Hard to argue with working code. :man_shrugging:

2 Likes

Ah, okay, so this is purely Java <-> Java. If so, then yeah, overloading is the way to go.

Or, switch to the superior JVM language, Kotlin :slight_smile: