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.
Discussions

optimization - Optimize imports python - Stack Overflow
i might be asking something stupid here. right now I'm importing these: import os from datetime import datetime from time import sleep import cv2 import numpy as np import mediapipe as mp import math More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - What is the best way to import for optimizing code? - Stack Overflow
I'm looking to get my compiled .exe as small in size and optimized as possible. Is it worth doing this or does python not include unused functions and classes when compiling? ... I doubt you will see any difference in resulting file size. Unlike include in C, import in Python doesn't actually ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Are local imports a good idea to speed up import time?
If I'm not wrong, this is common for large libraries. For instance, Pandas doesn't import xlrd unless you try to write excel files, it doesn't import matplotlib unless you plot a chart, it doesn't import database libraries unless you connect to a database, etc. More on reddit.com
๐ŸŒ r/Python
78
190
January 17, 2024
Import of modules is slowing down executable. Can it be imported locally or what can be done differently ?
Don't pack your exe into a single file. Don't use Anaconda Python; just use stock python. Build your exe while inside a virtual env. Explicitly remove DLL/SO files and see if your code still works. If it does, you don't need them. This matters more if you insist on a single file exe. More on reddit.com
๐ŸŒ r/Python
26
3
March 16, 2022
๐ŸŒ
PyTutorial
pytutorial.com โ€บ optimize-python-import-performance
PyTutorial | Optimize Python Import Performance
May 10, 2025 - The Python Import System has overhead that adds up. ... This shows each import's time contribution. Focus on the slowest ones first. Delay imports until needed. This speeds up initial execution.
๐ŸŒ
SciPy
docs.scipy.org โ€บ doc โ€บ scipy โ€บ tutorial โ€บ optimize.html
Optimization (scipy.optimize) โ€” SciPy v1.17.0 Manual
>>> from scipy.optimize import linear_sum_assignment >>> row_ind, col_ind = linear_sum_assignment(cost)
๐ŸŒ
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
๐ŸŒ
Python
wiki.python.org โ€บ moin โ€บ PythonSpeed โ€บ PerformanceTips
PythonSpeed/PerformanceTips - Python Wiki
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.
๐ŸŒ
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.
Find elsewhere
๐ŸŒ
Real Python
realpython.com โ€บ python-scipy-cluster-optimize
Scientific Python: Using SciPy for Optimization โ€“ Real Python
July 21, 2023 - 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 = ...
๐ŸŒ
JetBrains
jetbrains.com โ€บ help โ€บ pycharm โ€บ creating-and-optimizing-imports.html
Auto import | PyCharm Documentation
3 weeks ago - Press Alt+Enter. If there are multiple choices, select the desired import from the list. You can define your preferred import style for Python code by using the following options available on the Auto Import page of the project settings (Settings ...
๐ŸŒ
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!
๐ŸŒ
Real Python
realpython.com โ€บ python-import
Python import: Advanced Techniques and Tips โ€“ Real Python
August 16, 2024 - The Python import system is as powerful as it is useful. In this in-depth tutorial, you'll learn how to harness this power to improve the structure and maintainability of your code.
๐ŸŒ
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
๐ŸŒ
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...
๐ŸŒ
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 - Best Ways and Practices to Import Modules in Python: Optimize Space and Reduce Loading Time When coding in Python, importing modules is a crucial aspect of making your code functional and reusable โ€ฆ
๐ŸŒ
Medium
medium.com โ€บ @theodoretsori โ€บ optimize-your-python-code-with-modules-learn-how-to-import-and-use-modules-in-python-6c2e86ac63b0
Optimize Your Python Code with Modules: Learn how to import and use modules in Python | by Theodore Tsori | Medium
December 19, 2022 - To create your own module, simply create a new Python file and write the code you want to include in the module. For example, you could create a my_module.py file with the following code: ... This code defines a simple say_hello function that prints a greeting to the screen. To use this function in another program, you would import the my_module module using the import keyword, and then call the say_hello function using the dot (.) operator:
๐ŸŒ
sqlpey
sqlpey.com โ€บ python โ€บ solved-optimizing-python-imports-with-best-practices
Solved: Optimizing Python Imports with Best Practices - โ€ฆ
December 5, 2024 - Explore the best methods to organize and sort Python imports effectively according to various coding standards.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ optimization-in-python
Optimization in Python: Techniques, Packages, and Best Practices | DataCamp
August 31, 2024 - Each has its strengths and applications, but regardless of the optimization problem you face, there is usually a robust tool to help you address it in Python. Here are four of the most common optimization packages: The scipy.optimize module is a versatile library in the SciPy ecosystem, offering a wide array of algorithms for both unconstrained and constrained optimization problems. It includes functions for finding the minima of scalar and multi-variable functions, solving root-finding problems, and fitting curves to data. ... from scipy.optimize import minimize def objective_function(x): return x[0]**2 + x[1]**2 result = minimize(objective_function, [1, 1], method='BFGS') print(result.x) # Optimal solution # >>> [-1.07505143e-08 -1.07505143e-08]
๐ŸŒ
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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ optimization-in-scipy
Optimization in SciPy - GeeksforGeeks
July 23, 2025 - Import the optimize.newton package using the below command. Newton package contains a function that will calculate the root using the Newton Raphson method. Define a function for the given objective function. Use the newton function.