1

Consider this:

def function1():
   def nestedfunc(param1, **kw):
      logging.info("nested function %s" % kw) #error
   function2(nestedfunc("is called"), string="not default")


def function2(func, string="default"):
   try:
      #doing some setting
      func()
   finally:
      #reset back to setting

I am getting:

func()
TypeError: 'NoneType' object is not callable

I am assuming the func() is not passing parameters and it causes the error.

To clarify, the desire result is to be able to call func() with any number of parameters added.

Does anyone know what is the proper way to do it? Any advice would be thankful!

1
  • the desire result is to be able to call func() with any number of parameters added. Commented May 24, 2016 at 9:41

2 Answers 2

4

Your function2 recieves func=None because that's the (default) return value of nestedfunc(), which is called with the parameter "is called". You could use functools.partial to 'freeze' some function's arguments:

from functools import partial

def function1():
   def nestedfunc(param1, **kw):
      logging.info("nested function %s" % kw) #error
   function2(partial(nestedfunc, "is called"), string="not default")
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice, functool.partial is the right way to go.
1

nestedfunc("is called") is the value returned by the function call: None. You should pass nestedfunc to function2 without calling it first.

If you want to pass a parameter to nestedfunc, pass it to function2 first.

def function1():
   def nestedfunc(param1, **kw):
      logging.info("nested function %s" % kw) #error
   function2(nestedfunc, "is called", string="not default")


def function2(func, funcparam, string="default"):
   try:
      #doing some setting
      func(funcparam)
   finally:
      #reset back to setting

2 Comments

this is what i did, but my goal is to add the func() with any number of params. not sure if it is possible.
The other answer does what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.