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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T16:00:39+00:00 2026-06-10T16:00:39+00:00

I decided to try to preprocess function text before it’s compilation into byte-code and

  • 0

I decided to try to preprocess function text before it’s compilation into byte-code and following execution. This is merely for training. I hardly imagine situations where it’ll be a satisfactory solution to be used. I have faced one problem which I wanted to solve in this way, but eventually a better way was found. So this is just for training and to learn something new, not for real usage.

Assume we have a function, which source code we want to be modified quite a bit before compilation:

def f():
    1;a()
    print('Some statements 1')
    1;a()
    print('Some statements 2')

Let, for example, mark some lines of it with 1;, for them to be sometimes commented and sometimes not. I just take it for example, modifications of the function may be different.

To comment these lines I made a decorator. The whole code it bellow:

from __future__ import print_function


def a():
    print('a()')


def comment_1(s):
    lines = s.split('\n')
    return '\n'.join(line.replace(';','#;',1) if line.strip().startswith('1;') else line for line in lines)


def remove_1(f):    
    import inspect
    source = inspect.getsource(f)    
    new_source = comment_1(source)
    with open('temp.py','w') as file:
        file.write(new_source)
    from temp import f as f_new
    return f_new


def f():
    1;a()
    print('Some statements 1')
    1;a()
    print('Some statements 2')


f = remove_1(f) #If decorator @remove is used above f(), inspect.getsource includes @remove inside the code.

f()

I used inspect.getsourcelines to retrieve function f code. Then I made some text-processing (in this case commenting lines starting with 1;). After that I saved it to temp.py module, which is then imported. And then a function f is decorated in the main module.

The output, when decorator is applied, is this:

Some statements 1
Some statements 2

when NOT applied is this:

a()
Some statements 1
a()
Some statements 2

What I don’t like is that I have to use hard drive to load compiled function. Can it be done without writing it to temporary module temp.py and importing from it?

The second question is about placing decorator above f: @replace. When I do this, inspect.getsourcelines returns f text with this decorator. I could manually be deleted from f‘s text. but that would be quite dangerous, as there may be more than one decorator applied. So I resorted to the old-style decoration syntax f = remove_1(f), which does the job. But still, is it possible to allow normal decoration technique with @replace?

  • 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-10T16:00:41+00:00Added an answer on June 10, 2026 at 4:00 pm

    One can avoid creating a temporary file by invoking the exec statement on the source. (You can also explicitly call compile prior to exec if you want additional control over compilation, but exec will do the compilation for you, so it’s not necessary.) Correctly calling exec has the additional benefit that the function will work correctly if it accesses global variables from the namespace of its module.

    The problem described in the second question can be resolved by temporarily blocking the decorator while it is running. That way the decorator remains, along all the other ones, but is a no-op.

    Here is the updated source.

    from __future__ import print_function
    
    import sys
    
    
    def a():
        print('a()')
    
    
    def comment_1(s):
        lines = s.split('\n')
        return '\n'.join(line.replace(';','#;',1) if line.strip().startswith('1;') else line for line in lines)
    
    _blocked = False
    
    def remove_1(f):
        global _blocked
        if _blocked:
            return f
        import inspect
        source = inspect.getsource(f)    
        new_source = comment_1(source)
        env = sys.modules[f.__module__].__dict__
        _blocked = True
        try:
            exec new_source in env
        finally:
            _blocked = False
        return env[f.__name__]
    
    
    @remove_1
    def f():
        1;a()
        print('Some statements 1')
        1;a()
        print('Some statements 2')
    
    
    f()
    
    def remove_1(f):    
        import inspect
        source = inspect.getsource(f)    
        new_source = comment_1(source)
        env = sys.modules[f.__module__].__dict__.copy()
        exec new_source in env
        return env[f.__name__]
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I decided to try to my hand at this, and have had a somewhat
After failing to achieve this with link_to remote, I decided to try jQuery way.
I recently decided to try emacs for java development, so this is the first
I decided to try http://www.screwturn.eu/ wiki as a code snippet storage utility. So far
I've decided to try and create a game before I finish studies. Searching around
I've stumbled upon this tutorial and decided to try it out :-). In the
Having decided to try AForge for video and imaging stuff, I tried to implement
i am new to scrapy and decided to try it out because of good
A few days ago I installed tomcat 7 and decided to try building a
I'm pretty new to PHP, but I decided to try and make a simple

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.