The Python Oracle

Passing 'None' as function parameter (where parameter is a function)

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Track title: CC H Dvoks String Quartet No 12 Ame

--

Chapters
00:00 Passing 'None' As Function Parameter (Where Parameter Is A Function)
01:43 Answer 1 Score 8
03:21 Accepted Answer Score 8
03:51 Answer 3 Score 3
04:26 Answer 4 Score 1
04:46 Answer 5 Score 1
05:19 Thank you

--

Full question
https://stackoverflow.com/questions/3730...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #lambda

#avk47



ANSWER 1

Score 8


update

I would normally delete this post because THC4k saw through all the complexity and rewrote your function correctly. However in a different context, the K combinator trick might come in handy, so I'll leave it up.


There is no builtin that does what you want AFIK. I believe that you want the K combinator (the link came up on another question) which can be encoded as

 def K_combinator(x, name):
     def f():
         return x
     f.__name__ = name
     return f

 none_function = K_combinator(None, 'none_function')

 print none_function()

of course if this is just a one off then you could just do

def none_function():
    return None

But then you don't get to say "K combinator". Another advantage of the 'K_combinator' approach is that you can pass it to functions, for example,

foo(call_back1, K_combinator(None, 'name_for_logging'))

as for your second statement, only expressions are allowed in lambda. pass is a statement. Hence, lambda: pass fails.

You can slightly simplify your call to sanity check by removing the lambda around the first argument.

def sanity_check(b, true_func, false_func):
    if b:
        logfunc = log.debug
        execfunc = true_func
    else:
        logfunc = log.warning
        execfunc = false_func
    logfunc('exec: %s', execfunc.__name__)
    execfunc()

def sanity_checks():
    sanity_check(sanity_access(PATH['userhome'], os.F_OK),
                 K_combinator(None, 'none_func'), sys.exit)

This is more readable (largely from expanding the ternary operator into an if). the boolfunc wasn't doing anything because sanity_check wasn't adding any arguments to the call. Might as well just call instead of wrapping it in a lambda.




ANSWER 2

Score 3


You might want to rethink this.

class SanityCheck( object ):
    def __call__( self ):
        if self.check():
            logger.debug(...)
            self.ok()
        else:
            logger.warning(...)
            self.not_ok()
    def check( self ):
        return True
    def ok( self ):
        pass
    def not_ok( self ):
        sys.exit(1)

class PathSanityCheck(SanityCheck):
    path = "/path/to/resource"
    def check( self ):
        return os.access( path, os.F_OK )

class AnotherPathSanityCheck(SanityCheck):
    path = "/another/path"

def startup():
    checks = ( PathSanityCheck(), AnotherPathSanityCheck() )
    for c in checks:
        c()

Callable objects can simplify your life.




ANSWER 3

Score 1


>>> import dis
>>> f = lambda: None
>>> dis.dis(f)
  1           0 LOAD_CONST               0 (None)
              3 RETURN_VALUE    

>>> g = lambda: Pass 
>>> 
>>> 
>>> dis.dis(g)
  1           0 LOAD_GLOBAL              0 (Pass)
              3 RETURN_VALUE 


>>> g = lambda: pass 
  File "<stdin>", line 1
    g = lambda: pass 
                   ^
SyntaxError: invalid syntax



ANSWER 4

Score 1


Actually, what you want is a function which does nothing, but has a __name__ which is useful to the log. The lambda function is doing exactly what you want, but execfunc.__name__ is giving "<lambda>". Try one of these:

def nothing_func():
    return
def ThisAppearsInTheLog():
    return

You can also put your own attributes on functions:

def log_nothing():
       return
log_nothing.log_info = "nothing interesting"

Then change execfunc.__name__ to getattr(execfunc,'log_info', '')