imports after function definitions?

  • Thread starter Hallvard B Furuseth
  • Start date
H

Hallvard B Furuseth

Is there any reason not to structure my program like this?

def ...
def ...
var = ...
var = ...
import ...
import ...
main_function()

E.g. does it compile to slower code, or does it confuse PyChecker or
something, if I put the imports after the functions that use them?
 
T

Terry Reedy

Hallvard B Furuseth said:
Is there any reason not to structure my program like this?

def ...
def ...
var = ...
var = ...
import ...
import ...
main_function()

It is helpful to human readers to see dependencies at the top and to
know what globals are avaiable when reading defs. What would be
compensating gain of doing such?

Terry J. Reedy
 
H

Hallvard B Furuseth

Terry said:
in message news:[email protected]...

It is helpful to human readers to see dependencies at the top and to
know what globals are avaiable when reading defs. What would be
compensating gain of doing such?

I'm setting sys.path in a config function which depends on variables
near the end of the file. So the config function must be called late,
and the imports that depend on it after that.
 
R

Robert Dickinson

The only restriction is that if you want to reference some imported thing at
the module level, then the import has to precede the use:

import x
class cls(x.cls1):
pass

Other than that I don't know of any reasons (other than readability, which
can be interpreted to advantage either way).

-- Rob --
 
H

Hallvard B Furuseth

Thanks for all the answers.

Peter said:
Sounds like the structure ought to be changed (IMHO).

OK, I did. Moved the sys.path setting out of the config function.
In other words, why do you need all those defines and all those
variables to come before the imports?

I needed the config function to be called before the imports since
it set sys.path, and the config function should be able to access
some variables. So the imports had to come after it, and after
those variables. I thought it looked better to have the imports
at the end of the program than in the middle of it.

Never mind, though. Now I have them right after the config function.
I want that one at the beginning because that's what people need
to edit.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top