Search code examples
pythondictionarylambda

Assigning a method to a variable


I have a Dictionary paths, and if its not set correctly i want it to call a command

import os
import platform
import logging

paths={}

def setup_paths():
    path_root=get_project_root()
    paths['root']=path_root
    paths['documents']=lambda :createError('system',0,'Folder not Found')

def createError(sender,level,error):
    #Do something
    return errorMessage

so when I would call paths['documents'] (or something else wrong) I could handle something but still get back a normal string or what ever [level,errorMessage]. could you actually do something like this, this simply?

can I \t Tab

I tried lambda once and gave up and came here. As I understand it:

lambda m:method(Args)
#turns m into an abstract method method(Args) 
#so that you call m and not method(Args)

this is the only way I know to pass a method as an argument, with arguments


Solution

  • So I have found the answer, and thoroughly think its cool and wanted to share, so...

    #you can pass along a Method as a Variable
    m=lambda arg,arg2:_method(arg,arg2)
    
    #then call on it latter
    m()
    

    with this I can set a method to a value

    if: os.path.exsits(pathTOdoc): path['Document']=pathTOdoc
    else: path['Documents']=lambda :errorHandle(name,errorLVL,'Document Not Found')
    

    Now when I call path['Documents'] (or a get path method) it will preform a error handle while i can deal with any return normally

    Like this you can also give a callback method to sub classes