1

As I'm new to the python world, I'm asking you today about the best way to use another python file's functions.

Let's take this example:

- app/
  - __init__.py
  - helpers/
    - __init__.py
    - myhelper.py 
- run.py

run.py

import app
app.setname("helloworld")
app.run()

app/__init__.py

def setname(fname):
    global name
    name = fname

def run():
    import helpers.myhelper as my_helper
    my_helper.function()

app/helpers/myhelper.py

from .. import name

def function:
    return "hello world ! "+name

My question: Is it clear to use an import in the middle of a function, as I can't use it at the top?

Is it a good way to use a global variable like this? As you know I have multiple global variables in my case etc and this is how I made things.

Any suggestions?

1
  • Why can't you import at the top? Commented Oct 10, 2017 at 1:20

3 Answers 3

3

PEP8, the general standard for Python code style, states that:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

So no, it is not considered clear to have an import in the middle of a function, or anywhere besides at the top of your code.

Also note that name is probably a poor choice for a variable/function name, because it's a word like list, def, dict, a 'reserved keyword' that can clash with a word used for other things within Python. PEP8 recommends using a synonym/alternative (which is what I would do in this case), or to append with an underscore: name_

NB There are some use cases where importing inside a function is necessary to avoid circular imports, scoping etc. These can include testing, Flask webapps, but these are specific use cases, and general access of a function from another module should follow the PEP except by necessity. Usually such imports are expected in those contexts, however, and as such are clearer.

Sign up to request clarification or add additional context in comments.

Comments

2

You should follow PEP8 guidelines, BUT with an exception.

If you're importing a function that would be used only in your function, you can do that. Note it will load the module only when the function is executed. That means if your env missing the module, it would raise an exception only when the function is used.

You should avoid that, but when there is no other option, it will run.

Comments

1

Why can't you import it at the top? Imports are expensive (speed wise) and you probably don't want to be importing the same module everytime you call that function. Also, import results are cached in python making redundant imports an even bigger waste.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.