This indicates it may make a difference:

"import statements can be executed just about anywhere. It's often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python's interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement can seriously affect performance in some circumstances."

These two OS questions, local import statements? and import always at top of module? discuss this at length.

Finally, if you are curious about your specific case you could profile/benchmark your two alternatives in your environment.

I prefer to put all of my import statements at the top of the source file, following stylistic conventions and for consistency (also it would make changes easier later w/o having to hunt through the source file looking for import statements scattered throughout)

Answer from Levon on Stack Overflow
Top answer
1 of 2
12

This indicates it may make a difference:

"import statements can be executed just about anywhere. It's often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python's interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement can seriously affect performance in some circumstances."

These two OS questions, local import statements? and import always at top of module? discuss this at length.

Finally, if you are curious about your specific case you could profile/benchmark your two alternatives in your environment.

I prefer to put all of my import statements at the top of the source file, following stylistic conventions and for consistency (also it would make changes easier later w/o having to hunt through the source file looking for import statements scattered throughout)

2 of 2
2

The general rule of thumb is that imports should be at the top of the file, as that makes code easier to follow, and that makes it easier to figure out what a module will need without having to go through all the code.

The Python style guide covers some basic guidelines for how imports should look: http://www.python.org/dev/peps/pep-0008/#imports

In practice, though, there are times when it makes sense to import from within a particular function. This comes up with imports that would be circular:

# Module 1
from module2 import B

class A(object):
    def do_something(self):
        my_b = B()
        ...

# Module 2
from module1 import A

class B(object):
    def do_something(self):
        my_a = A()
        ...

That won't work as is, but you could get around the circularity by moving the import:

# Module 1
from module2 import B

class A(object):
    def do_something(self):
        my_b = B()
        ...

# Module 2
class B(object):
    def do_something(self):
        from module1 import A
        my_a = A()
        ...

Ideally, you would design the classes such that this would never come up, and maybe even include them in the same module. In that toy example, having each import the other really doesn't make sense. However, in practice, there are some cases where it makes more sense to include an import for one method within the method itself, rather than throwing everything into the same module, or extracting the method in question out to some other object.

But, unless you have good reason to deviate, I say go with the top-of-the-module convention.

🌐
LabEx
labex.io › tutorials › python-how-to-efficiently-organize-python-imports-435505
How to efficiently organize Python imports | LabEx
## Install py-spy pip install py-spy ## Profile import performance py-spy record -o profile.svg python script.py ... ## Preferred: Specific import from math import sqrt, pow ## Avoid: Entire module import import math ## Higher memory overhead · By implementing these optimization strategies, you can significantly improve your Python project's import efficiency, reducing memory consumption and startup time with LabEx's recommended approaches.
🌐
Python
wiki.python.org › moin › PythonSpeed › PerformanceTips
PythonSpeed/PerformanceTips - Python Wiki
import statements can be executed just about anywhere. It's often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python's interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement ...
🌐
JetBrains
jetbrains.com › help › pycharm › creating-and-optimizing-imports.html
Auto import | PyCharm Documentation
3 weeks ago - In the Optimize Imports dialog, click Run. Start typing a name in the editor. If the name references a class that has not been imported, the following prompt appears: The unresolved references will be underlined, and you will have to invoke ...
🌐
Gregoryszorc
gregoryszorc.com › blog › 2019 › 01 › 10 › what-i've-learned-about-optimizing-python
Gregory Szorc's Digital Home | What I've Learned About Optimizing Python
January 10, 2019 - As I've demonstrated with PyOxidizer, replacing the default find and load a module from the filesystem with an architecturally simpler solution of read the module data from an in-memory data structure makes importing the Python standard library take 70-80% of its original time!
🌐
PyTutorial
pytutorial.com › optimize-python-import-performance
PyTutorial | Optimize Python Import Performance
May 10, 2025 - Follow Python import best practices for clean package structure. Python caches bytecode in __pycache__. Ensure it's enabled: python -O my_app.py # Generates optimized .pyc files
🌐
PyPI
pypi.org › project › importanize
Client Challenge
JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 72420132 › optimize-imports-python
optimization - Optimize imports python - Stack Overflow
and the output program has almost 500MB is there any way I can optimize it? ... One thing to do would be to see where these modules are used - if you import a large module like tkinter (with all its dependencies) for something very small, which you could also do by hand, that might be worth cutting out. Other modules are so small, that it will hardly ever be worth the time. If you want lean and mean, Python isn't the way to go to begin with.
🌐
Medium
medium.com › @balakrishna0106 › best-ways-and-practices-to-import-modules-in-python-optimize-space-and-reduce-loading-time-8b2200ad6d55
Best Ways and Practices to Import Modules in Python: Optimize Space and Reduce Loading Time | by Balakrishna | Medium
October 18, 2024 - When you import an entire module, Python loads everything in memory, which can increase the program’s size unnecessarily. Instead of importing the whole module, you can import only the specific functions or classes you need.
🌐
Iifx
iifx.dev › english › python
optimization - Optimizing Python Imports: A Deep Dive - pep8
Use Explicit Imports Prefer explicit imports over implicit ones to avoid namespace conflicts. Prioritize Readability Strive for clear and concise code, even if it means sacrificing some performance. python optimization pep8
🌐
sqlpey
sqlpey.com › python › solved-optimizing-python-imports-with-best-practices
Solved: Optimizing Python Imports with Best Practices - …
December 5, 2024 - This means all imports should be in alphabetical order within each category, ignoring case. The Google Python Style Guide recommends sorting imports within each group in lexicographical order based on the full package path.
🌐
Python
peps.python.org › pep-0690
PEP 690 – Lazy Imports - Python Enhancement Proposals
Since Python programs commonly import many more modules than a single invocation of the program is likely to use in practice, lazy imports can greatly reduce the overall number of modules loaded, improving startup time and memory usage.
🌐
Quora
quora.com › What-does-optimize-imports-mean-on-PyCharm
What does 'optimize imports' mean on PyCharm? - Quora
Answer (1 of 2): it means that if you are doing this : [code]from math import cos from math import sin from math import sqrt from math import factorial [/code]and you optimise imports it will convert that to : [code]from math import cos, sin, sqrt, factorial [/code]further more it will remove a...
🌐
SciPy
docs.scipy.org › doc › scipy › tutorial › optimize.html
Optimization (scipy.optimize) — SciPy v1.17.0 Manual
Objective functions in scipy.optimize expect a numpy array as their first parameter which is to be optimized and must return a float value. The exact calling signature must be f(x, *args) where x represents a numpy array and args a tuple of additional arguments supplied to the objective function.
🌐
Apmonitor
apmonitor.com › wiki › index.php › Main › PythonApp
Python Optimization Package
Another method to obtain APMonitor is to include the following code snippet at the beginning of a Python script. The installation is only required once and then the code can be commented or removed. try: from pip import main as pipmain except: from pip._internal import main as pipmain pipmain(['install','APMonitor']) # to upgrade: pipmain(['install','--upgrade','APMonitor'])
🌐
Real Python
realpython.com › python-scipy-cluster-optimize
Scientific Python: Using SciPy for Optimization – Real Python
July 21, 2023 - Try out the code below to solve this problem. First, import the modules you need and then set variables to determine the number of buyers in the market and the number of shares you want to sell: ... 1import numpy as np 2from scipy.optimize import minimize, LinearConstraint 3 4n_buyers = 10 5n_shares = 15
🌐
Mend
mend.io › blog › developer › python import: mastering the advanced features
Python Import: Mastering The Advanced Features
October 31, 2024 - This section delves into a range of strategies and solutions that can help you handle package compatibility across Python versions, address missing packages using alternatives or mocks, import scripts as modules, run Python scripts from ZIP files, manage cyclical imports, profile imports for performance optimization, and tackle common real-world import challenges with practical solutions.