What would be the most pythonic way to pass an object type as an agrgument in a function?
Let me give you an example. Let's say I was trying to get a configuration from an environment variable. Because all environment variables are strings I need to cast the value to the correct type.
To do this I need to tell the function the desired type. This is the purpose of the coerce argument. My first instinct is to pass in the desired type as the value for coerce. However, I am not sure if there are any implications or problems in doings so.
import os
# The Function
def get_config(config: str, coerce: type, default: any, delimiter: str = ","):
value = os.getenv(config, None) # Get config from environment
if value is None:
return default # Return default if config is None
if coerce is bool:
value = str2bool(value) # Cast config to bool
elif coerce is int:
value = str2int(value) # Cast config to int
elif coerce is list:
value = value.split(delimiter) # Split string into list on delimiter
return value # Return the config value
# Usage
os.environ["TEST_VAR"] = "True"
test_var = get_config("TEST_VAR", bool, False)
print(test_var) # output is True
print(type(test_var)) # output is <class 'bool'>
To me this seems more clear and pythonic than using a string such as "str" or "bool" to specify the type. However, I would like to know if there could be any problems caused by passing around built in types as function arguments.