nemo
nemo

Reputation: 1584

Python: Use Sister Parameters in Constructing Default Values

I know I can do this in scala, but is there a way to do something similar in python:

def validate_config(data_dir, config_file_dir = data_dir + '/config', json_schema = None):
    print(data_dir)
    print(config_file_dir)
    print(json_schema)

validate_config('data')

The output I'm expecting is:

data
data/config
None

Thanks!

Upvotes: 1

Views: 42

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55489

Not exactly, because Python's default args are evaluated when the function definition is compiled. But you can use None as the default arg and check it at run-time, like this:

def validate_config(data_dir, config_file_dir=None, json_schema=None):
    if config_file_dir is None:
       config_file_dir = data_dir + '/config'
    print(data_dir)
    print(config_file_dir)
    print(json_schema)

validate_config('data')

output

data
data/config
None

Upvotes: 2

Peter DeGlopper
Peter DeGlopper

Reputation: 37339

This is not directly supported. I would do this the same way Python avoids mutable default instances:

def validate_config(data_dir, config_file_dir=None, json_schema=None):
    if config_file_dir is None:
        config_file_dir = data_dir + '/config'
    # rest of code here

Upvotes: 5

Related Questions