Modify 'import' command

For main programs, I don’t know the official reason, but main programs are often shorter than an imported module, and there’s only one of them, compared to the dozens or hundreds of modules you might import over the course of the run.

For exec(), Dunc has mentioned the dynamic nature of exec’d code. But also, there’s no file name, so there’s no simple way to decide where to store it and then find it again in the future.

In any case, these days compiling a .py file is really fast, so it won’t be a concern.

And if you ARE in a situation where you are exec’ing the same code more than once, chances are you’d benefit from caching it in a different way, eg an in-memory dictionary mapping the code to an actual code object (or maybe a function or some other useful entry point).

Hi Ned, I see you are thinking about arbitrary code run in exec(), I hadn’t thought about that, I was considering the case where exec() is being used to run Python Scripts (modules) which obviously do have a file name. However now I look at it I see that exec() is not linked directly in any way to that file.

If Python had an execfile() function I could see the case for saving the compile as *.pyc.

In my case I have resorted to using:

spec = importlib.util.spec_from_file_location(module_name, source_filepath)
spec.loader.exec_module(module)

Which does save the compiled bytecode in a *.pyc. Then on subsequent runs I exec() the *.pyc directly. Just feels like a bit of a faff and I had hoped that Python might have been able to do this itself somehow.

It is, because you are doing things the hard way instead of using Python as it was designed to be used.

Why would it? The way you’re supposed to combine code from different modules is to expose functions, classes etc. that can be used where they are needed.

Sometimes ‘the hard way’ is most appropriate to the requirement. I get the feeling occasionally that Python restricts itself for purely ideological reasons rather than what best suits the requirements.

I have no idea what ideology you’re referring to. Python doesn’t have a simple hook for changing source code at compile time. That’s not because of philosophical opposition. It’s because there hasn’t been a strong need for it and/or the costs of providing it outweigh the benefits.

You have a way to do what you want though, so everything is good?

This is, by the way, exactly the reason that we are constantly asking why you’re trying to do something. We are actually trying to help you determine what best suits your requirements. Python has a lot of ways to do a lot of things to suit various requirements, so it’s really difficult to help without knowing the requirements in the first place.

@jfong Thank you very much for your introduction of preprocess.exe into the discussion; that is much like what I was trying to do although didn’t quite know it at the time.

Have now almost completed writing a compiler directive, similar preprocess.exe, exclusively in Python. However as a Python noobie I don’t know where the best place is to publish it for others to test and ultimately see if there is perhaps any support for building it into a future version of Python.

The place to publish it is PyPI. This tutorial will walk you through the steps: Packaging Python Projects - Python Packaging User Guide

Be prepared for the process to be different than you expect. You will need to do it the surprising way anyway.

About building it into a future version of Python: this is very very very unlikely to happen for a number of reasons. Publish it to PyPI and enjoy the adoption you get from there.

Many programming languages support conditional compilation, including D, C, C++, C#, Visual Basic, and Rust. May I know what’s the reasons Python will not have it in the future version?

The main reason is that it has been proposed before and has not gained traction.

About conditional compilation as a general concept: Python modules are compiled independently of each other, so nothing imported into a module can affect the compilation of that module. That severely limits the possible uses. Changing that independent compilation would be a drastic change to the language.

But in particular about this specific proposal: shepherding a change to the language requires an interaction style that I have not seen here.

With the sole exception of __future__ imports, which are very much a special case that cannot be generalized to arbitrary user compile directives.

@nedbat What about __debug__ for a start?

Not sure what you mean. It is simply a constant, like True and False, except that its value depends on a parameter. It isn’t like conditional compilation; it’s simply a run-time check, but one that the optimizer can remove. The behaviour - aside from performance - is exactly the same as if you simply create a builtin and check that.

What about it? It already affects compilation. Code under a false __debug__ check isn’t included in the compiled code:

% bat deb.py
     1 │ import dis
     2 │
     3 │ def f():
     4 │     print("Hello")
     5 │     if __debug__:
     6 │         print("Debug")
     7 │
     8 │ dis.dis(f)

% python deb.py
  3           0 RESUME                   0

  4           2 LOAD_GLOBAL              1 (NULL + print)
             12 LOAD_CONST               1 ('Hello')
             14 CALL                     1
             22 POP_TOP

  5          24 NOP

  6          26 LOAD_GLOBAL              1 (NULL + print)
             36 LOAD_CONST               2 ('Debug')
             38 CALL                     1
             46 POP_TOP
             48 RETURN_CONST             0 (None)

% python -O deb.py
  3           0 RESUME                   0

  4           2 LOAD_GLOBAL              1 (NULL + print)
             12 LOAD_CONST               1 ('Hello')
             14 CALL                     1
             22 POP_TOP

  5          24 RETURN_CONST             0 (None)

Because this is reading like nefarious intentions, like some kind of polymorphic that self-modifies but hides the transformation.

@adrianofdoom Not got a clue what your comment means. The ultimate idea is to try, if possible, to create a system of compile time directives for Python.

Let’s be very specific about what this means. Usually, compile-time directives are literally equivalent to cutting pieces of the code out, which allows you to have directives managing partial syntax, like this:

#if COLLECT_RESULTS
#define COMMA ,
results = [
#else
#define COMMA
#endif
thing_one() COMMA
thing_two() COMMA
thing_three() COMMA
thing_four() COMMA
#if COLLECT_RESULTS
]
#endif

This is entirely legal in languages like C, where the preprocessor examines the text before the compiler looks at it (hence “pre” processing). This isn’t how it works with __debug__, which is simply a magic constant. You can’t do something like:

if __debug__:
    stuff = [
# then this part is unconditional
thing_one()
if __debug__:
    ]

There is a strict flow through compilation: first preprocessing, then syntax parsing, and then optimization happens afterwards. The fact that you can’t see the debug code in disassembly does NOT mean that it got deleted in preprocessing; it means it got optimized out. (You can often see some residue of it, with a NOP opcode left behind.)

So, when you ask for compile-time directives, do you want something that can manipulate syntax, or are you simply looking for something that gets evaluated during the compilation phase and then is treated as a constant? Those are two very different requirements, with correspondingly different ideas to fulfil them.

For something that can manipulate syntax, I would recommend getting an actual preprocessor. You can do neat stuff with import hooks, or for simplicity, just run your code through m4 or similar as part of deployment. But for a compile-time constant? That would require some support from the Python language. It would be a narrower proposal than a full preprocessor, but OTOH would also have broader application. Imagine if you had something like this:

def f():
    if $(math.random() < 0.5):
        print("I'm nondeterministic!")
    else:
        print("Why are you doing something insane?")

I’m using the deliberately-ugly $(EXPR) syntax as a placeholder here. If this meant “evaluate this once, while the module is being compiled, and put the result here as a constant”, it could be used for all kinds of things - it’s basically constant folding, but for arbitrary expressions. And since it has effectively become a constant, the optimizer could then kick in afterwards, treating this as either if True: or if False: depending on which way the RNG decided.

Which one was it that you had in mind?