Re: Coping with cyclic imports



Torsten Bronger <bronger@xxxxxxxxxxxxxxxxxxxxx> wrote:

So, the last question is: Under which circumstances does this
happen? It happens when you import a module which imports (directly
or indictly) the current module and which comes before the current
module in the import order while the program runs.

If you don't rely on imported things at top-level code (but only in
functions and methods which in turn must not be called from the
top-level), everything is fine.

Can anybody confirm that this is correct?

Imports are pretty straightforward really. Just remember the following:

'import' and 'from xxx import yyy' are executable statements. They execute
when the running program reaches that line.

If a module is not in sys.modules, then an import creates the new module
entry in sys.modules and then executes the code in the module. It does not
return control to the calling module until the execution has completed.

If a module does exist in sys.modules then an import simply returns that
module whether or not it has completed executing. That is the reason why
cyclic imports may return modules which appear to be partly empty.

Finally, the executing script runs in a module named __main__, importing
the script under its own name will create a new module unrelated to
__main__.

Take that lot together and you shouldn't get any surprises when importing
modules.
.



Relevant Pages

  • Re: performance critical Python features
    ... Fortunately Python does optimize this case. ... imports are so expensive that it makes sense to optimize them. ... execute it, ... which are slow the first time. ...
    (comp.lang.python)
  • Re: Module imports during object instantiation
    ... if verbose is True: ... you have because of the "execute code only once" behavior - if the ... This is what even my understanding is. ... Going with your point of try/except imports at the top level, ...
    (comp.lang.python)
  • Unable to cast COM object error in SSIS
    ... save it as .txt using a Script Task. ... following error when I attempt to execute the Script Task containing the code ... Imports Microsoft.Vsa ... Dim wdApp As Microsoft.Office.Interop.Word.Application ...
    (microsoft.public.sqlserver.dts)
  • Re: Executing UpdateGram with .NET Managed Class does nothing
    ... UpdateGrams return exception information in an XML response. ... the command using the ExecuteXmlReader method and reading the response, ... Imports System.IO ... When I execute an Updategram using the .NET Managed class nothing ...
    (microsoft.public.sqlserver.xml)
  • Re: Reading a in app.config
    ... question with what I did to get the code to execute but beings the code runs ... if others had a better method to reading a <SectionGroup> and found ... > name of the configuration file? ... >> Imports System.Configuration ...
    (microsoft.public.dotnet.framework)