Is it possible to achieve Python code like below without using the with statement?

Asked 2 years ago, Updated 2 years ago, 355 views

with tf. GradientTape() as gen_tape, tf. GradientTape() as disc_tape:
  Processing 1
  Processing 2

python

2022-09-30 22:04

1 Answers

These articles and PEP343,346 seem to have some information.
It explains what the specifications of the with statement look like and how it works.

Is Python with statement exactly equal to a try-(except)-final block?
What is the equivalent try statement of the with statement?
PEP343 – The "with" Statement
PEP346 – User Defined("with") Statements

These syntaxes are:

 with EXPR as VAR:
    BLOCK

It says it will be expanded here.

mgr=(EXPR)
exit=type(mgr).__exit__#Not calling it yet
value=type(mgr).__enter__(mgr)
exc = True
try:
    try:
        VAR=value#Only if "as VAR" is present
        BLOCK
    except:
        # The exceptional case is handled here
        exc = False
        if not exit(mgr, *sys.exc_info()):
            raise
        # The exception is swallowed if exit() returns true
finally:
    # The normal and non-local-gotocases are handled here
    if exc:
        exit(mgr, None, None, None)

If there are two parts of EXPR as VAR as in the question, you can create a set of mgr, exit, value for each of them, and use mgr1, exit1, value1, mgr2, exit2, value2.
You may not be able to make it completely equivalent, but try it.


2022-09-30 22:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.