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 9060267
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T15:11:03+00:00 2026-06-16T15:11:03+00:00

I have rather strange question about function variable scope and return. Is there any

  • 0

I have rather strange question about function variable scope and return.
Is there any way to inspect the scope of called function in the caller after called function returns value?

Use case is simple: in Flask views I would like to bypass locals() to my templates. I can define what template I need by convention and having return a dictionary in every view bothers me.

  • 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-16T15:11:04+00:00Added an answer on June 16, 2026 at 3:11 pm

    After the function returns, its scope no longer exists. This makes it problematic to get the scope after the function returns.

    However, using Python’s trace or profile capability, it’s possible to run some code just as a function is about to return, and extract the locals from its stack frame at that time. These can then be squirreled away somewhere and returned along with (or instead of) the return value of the called function using a wrapper function.

    Here is a decorator that can be used for this nefarious purpose. Keep in mind that this implementation is a horrible hack and it would be bad style to use it for mere convenience. I could probably think of legitimate uses… give me a few days. Also, it may not work with non-CPython implementations (probably won’t, in fact).

    import sys, functools
    
    def givelocals(func):
        
        localsdict = {}
    
        def profilefunc(frame, event, arg):
            if event == "call":
                localsdict.clear()
            elif event == "return":
                localsdict.update(frame.f_locals)
            return profilefunc    
    
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            oldprofilefunc = sys.getprofile()
            sys.setprofile(profilefunc)
            try:
                return func(*args, **kwargs), dict(localsdict)
            except Exception as e:
                e.locals = dict(localsdict)
                raise
            finally:
                sys.setprofile(oldprofilefunc)
    
        return wrapper
    

    Example:

    @givelocals
    def foo(x, y):
        a = x + y
        return x * y
    
    >>> foo(3, 4)
    (12, {'y': 4, 'x': 3, 'a': 7})
    

    If you have some arbitrary function you want to use it with that you can’t decorate because it’s in a module you didn’t write, you can create the wrapper on the fly and call it:

    def foo(x, y):
        a = x + y
        return x * y
    
    >>> givelocals(foo)(3, 4)
    (12, {'y': 4, 'x': 3, 'a': 7})
    

    Or store the wrapper and call it later:

    locals_foo = givelocals(foo)
    >>> locals_foo(3, 4)
    (12, {'y': 4, 'x': 3, 'a': 7})
    

    The wrapper returns a tuple of the actual return value and the locals dictionary. If an exception is raised, the .locals attribute of the exception object is set to the locals dict.

    Keep in mind that usually Python frees the memory used by the local variables when the function returns. Retaining these values will cause your program to use more memory (for as long as there are references to them), so it’d be a good idea to clean them up when you no longer need them.

    One last note: I’m using Python’s profile functionality here because it’s invoked only at function calls and returns. If you’re using a Python version prior to 2.6, you don’t have profiling, so you’d need to use tracing instead. The profile function will also work as a trace function as written, you’d just need to use gettrace() and settrace() rather than the corresponding profile-related functions. However, since tracing is called for each line, the wrapped function may be noticeably slower.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a rather strange question: I have a Java application which uses applications
I have a rather strange question regarding urls which point to another url. So,
We stumbled upon a rather strange problem IMO. Our clients have been complaining about
Hi I have a strange question about java. I will leave out the background
I've experienced rather strange behavior of JSTL forEach tag. I have some bean called
So i have this rather strange issue, i am trying to line up some
I have a strange behaviour. I am using a rather heavy page (4000 nodes)
Have a rather simple question. Does anyone knows if i can use jparallax both
I have a rather complicated (and very inefficient) way of getting utilisation from a
Here's a strange question for you guys, I have a nice sorted list that

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.