0

I have created a list of functions and they working fine individually. However other developers have to call these functions individually.

Calling function like this. I would want to simplify more while creating module like user should call using the below line

'type' will be any of the below (mandatory)

a, b, c, d

for each type, relevant function should be called from module

'info' will be input from developer (optional)

'param' will be compulsory list for DBNAME (SQL, ORACLE, TERADATA etc) and optional for rest.

I have created below class for type. However I am unable make proper code to create above functions using IF statement using above types. How might I achieve this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Raju
  • 175
  • 1
  • 2
  • 11
  • This doesn't seem like it would simplify anything for the user. N function calls will be replaced by N (slightly different) function calls. – goodvibration Dec 03 '19 at 11:16
  • Did you mean something like [this](https://stackoverflow.com/questions/34794634/how-to-use-a-variable-as-function-name-in-python)? – Guven Degirmenci Dec 03 '19 at 11:30

2 Answers2

0

IIUC. You can use a dict to call the required function.

Ex:

def log_info(info=None):
    print('log_info', info)

def log_info_DBCS(info=None):
    print('log_info', info)

def log_info_DBName(param, info=None):
    print('log_info_DBName', param, info)

def log_info_TableName(info=None):
    print('log_info_TableName', info)  

def log_info_RecordCount(info=None):
    print('log_info_RecordCount', info)

def log_info_Duration(info=None):
    print('log_info_Duration', info)


def call_func(func, **kargs):
    f = {'log_info': log_info,
         'log_info_DBCS': log_info_DBCS,
         'log_info_DBName': log_info_DBName,
         'log_info_TableName': log_info_TableName,
         'log_info_RecordCount': log_info_RecordCount,
         'log_info_Duration': log_info_Duration}

    return f[func](**kargs)

typ = 'log_info_DBName'
dbname = 'SQL'    

call_func(typ, **{"param":dbname})
call_func(typ, **{"param":dbname, 'info': "Hello World"})
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

First off, I wouldn't name anything type since that is a built-in.

Second, you don't need any if statements; it looks like the only thing that varies is the error string, so you can just stick that into the enum value, and use it as a format string:

from enum import Enum

class LogType(Enum):
  Info = "cmd: {}"
  DBName = "cmd: Connected to database-({})"
  # .. etc.

def log_info(logtype, info):
    logger.info(logtype.value.format(info))
tzaman
  • 46,925
  • 11
  • 90
  • 115