Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8371313
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T14:07:53+00:00 2026-06-09T14:07:53+00:00

If I have this function, what should I do to replace the inner function

  • 0

If I have this function, what should I do to replace the inner function with my own custom version?

def foo():
    def bar():
        # I want to change this
        pass

    # here starts a long list of functions I want to keep unchanged
    def baz():
        pass

Using classes this would be easily done overriding the method. Though, I can’t figure out how to do that with nested functions. Changing foo to be a class (or anything else) is not an option because it comes from a given imported module I can’t modify.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T14:07:54+00:00Added an answer on June 9, 2026 at 2:07 pm

    Here’s one way of doing it, creating a new foo that “does the right thing” by hacking the function internals. ( As mentioned by @DSM ). Unfortunately we cant just jump into the foo function and mess with its internals, as they’re mostly marked read only, so what we have to do is modify a copy we construct by hand.

    # Here's the original function
    def foo():
      def bar():
        print("    In bar orig")
      def baz():
        print("  Calling bar from baz")
        bar()
      print("Foo calling bar:")
      bar()
      print("Foo calling baz:")
      baz()
    
    # Here's using it
    foo()
    
    # Now lets override the bar function
    
    import types
    
    # This is our replacement function
    def my_bar():
      print("   Woo hoo I'm the bar override")
    
    # This creates a new code object used by our new foo function 
    # based on the old foo functions code object.
    foocode = types.CodeType(
        foo.func_code.co_argcount,
        foo.func_code.co_nlocals,
        foo.func_code.co_stacksize,
        foo.func_code.co_flags,
        foo.func_code.co_code,
        # This tuple is a new version of foo.func_code.co_consts
        # NOTE: Don't get this wrong or you will crash python.
        ( 
           foo.func_code.co_consts[0],
           my_bar.func_code,
           foo.func_code.co_consts[2],
           foo.func_code.co_consts[3],
           foo.func_code.co_consts[4]
        ),
        foo.func_code.co_names,
        foo.func_code.co_varnames,
        foo.func_code.co_filename,
        foo.func_code.co_name,
        foo.func_code.co_firstlineno,
        foo.func_code.co_lnotab,
        foo.func_code.co_freevars,
        foo.func_code.co_cellvars )
    
    # This is the new function we're replacing foo with
    # using our new code.
    foo = types.FunctionType( foocode , {})
    
    # Now use it
    foo()
    

    I’m pretty sure its not going to catch all cases. But it works for the example (for me on an old python 2.5.1 )

    Ugly bits that could do with some tidy up are:

    1. The huge argument list being passed to CodeType
    2. The ugly tuple constructed from co_consts overriding only one member. All the info is in co_consts to determine which to replace – so a smarter function could do this. I dug into the internals by hand using print( foo.func_code.co_consts ).

    You can find some information about the CodeType and FunctionType by using the interpreter
    command help( types.CodeType ).

    UPDATE:
    I thought this was too ugly so I built a helper function to make it prettier. With the helper you can write:

    # Use our function to get a new version of foo with "bar" replaced by mybar    
    foo = monkey_patch_fn( foo, "bar", my_bar )
    
    # Check it works
    foo()
    

    Here’s the implementation of monkey_patch_fn:

    # Returns a copy of original_fn with its internal function
    # called name replaced with new_fn.
    def monkey_patch_fn( original_fn, name, new_fn ):
    
      #Little helper function to pick out the correct constant
      def fix_consts(x):
        if x==None: return None
        try:
          if x.co_name == name:
            return new_fn.func_code
        except AttributeError, e:
            pass
        return x
    
      original_code = original_fn.func_code
      new_consts = tuple( map( fix_consts, original_code.co_consts ) )
      code_type_args = [
         "co_argcount", "co_nlocals", "co_stacksize", "co_flags", "co_code",
         "co_consts", "co_names", "co_varnames", "co_filename", "co_name",
         "co_firstlineno", "co_lnotab", "co_freevars", "co_cellvars" ]
    
      new_code = types.CodeType(
         *[ ( getattr(original_code,x) if x!="co_consts" else new_consts )
            for x in code_type_args ] )
      return types.FunctionType( new_code, {} )
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this rev_comp() function >>> def rev_comp(sequence): ... def reverse(s): ... letters =
I have a problem with the function replace . What I want to accomplish
I have this function // add history paths and save data function AddPath( strTag,
I have this function: int firstHeapArray (IntHeapArray h) { if(!emptyHeapArray(h)) return h.array[0]; } It's
I have this function to create a request to another file to update the
I have this function: function validate($data) { $newData = str_replace( , , $newData); $newData =
I have this function that I would like to condense into some iterator. How
I have this function, and i animate via css a flipbox. How could i
I have this function which is supposed to set a certain time format to
I have this function above to create url slugs from posts title, the problem

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.