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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T17:59:44+00:00 2026-05-12T17:59:44+00:00

I’d like to create a decorator like below, but I can’t seem to think

  • 0

I’d like to create a decorator like below, but I can’t seem to think of an implementation that works. I’m starting to think it’s not possible, but thought I would ask you guys first.

I realize there’s various other ways to create static variables in Python, but I find those ways ugly. I’d really like to use the below syntax, if possible.

@static(x=0)
def f():
    x += 1
    print x

f() #prints 1
f() #prints 2

I don’t care if the implementation of static is long or hackity, as long as it works like above.

I created this version, but it only allows a <function>.<varname> syntax, which gets cumbersome pretty quickly with longer function and variable names.

def static(**assignments):
    def decorate(func):
        for var, val in assignments.items():
            setattr(func, var, val)
        return func
    return decorate

Various things I thought of, but couldn’t get to work were:

  1. Changing f (the decorated function) into a callable class, and somehow storing the static vars in self transparently.
  2. Modifying the globals of f() inside the decorator, and somehow inserting ‘global x’ statements into the code for f.
  3. Changing f into a generator where we bind the variables by hand and then execute f’s code directly.
  • 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-05-12T17:59:44+00:00Added an answer on May 12, 2026 at 5:59 pm

    Here is a decorator that seems to work.
    Note that this requires return locals() at the end of the function due to being unable to set locals from the outside (I don’t have much experience programming so if there is a way, I don’t know it).

    class Static(object):
        def __init__(self, **kwargs):
            self.kwargs = kwargs
    
        def __call__(self, f):
            def wrapped_f():
                try:
                    new_kwargs = {}
                    for key in self.kwargs:
                        i = getattr(f, key)
                        new_kwargs[key] = i
                    self.kwargs = new_kwargs
                except:
                    pass
                for key, value in f(**self.kwargs).items():
                    setattr(f, key, value)
            return wrapped_f
    
    @Static(x=0, y=5, z='...')
    def f(x, y, z):
        x += 1
        y += 5
        print x, y, z
        return locals()
    

    The output would be:

    >>> f()
    1 10 ...
    >>> f()
    2 15 ...
    >>> f()
    3 20 ...
    

    EDIT:

    I found something at http://code.activestate.com/recipes/410698/ and decided to try adding it to this. It works without the return now.

    EDIT again: Changed to to make it a few seconds faster.
    Edit 3; changed to function instead of class

    def static(**kwargs):
        def wrap_f(function):
            def probeFunc(frame, event, arg):
                if event == 'call':
                    frame.f_locals.update(kwargs)
                    frame.f_globals.update(kwargs)
                elif event == 'return':
                    for key in kwargs:
                        kwargs[key] = frame.f_locals[key]
                    sys.settrace(None)
                return probeFunc
            def traced():
                sys.settrace(probeFunc)
                function()
            return traced
        return wrap_f
    

    tested:

    @static(x=1)
    def f():
        x += 1
    
    global_x = 1
    def test_non_static():
        global global_x
        global_x += 1
    
    
    print 'Timeit static function: %s' % timeit.timeit(f)
    print 'Timeit global variable: %s' % timeit.timeit(test_non_static)
    

    output:

    Timeit static function: 5.10412869535
    Timeit global variable: 0.242917510783
    

    Using settrace slows it down quite drastically.

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

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
Does anyone know how can I replace this 2 symbol below from the string
I'm trying to create an if statement in PHP that prevents a single post
Is it possible to replace javascript w/ HTML if JavaScript is not enabled on
I would like to count the length of a string with PHP. The string
For some reason, after submitting a string like this Jack’s Spindle from a text

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.