This question already has answers here:
Why import when you need to use the full name?
(8 answers)
Closed 1 year ago.
I'm new to PyCharm, and after downloading a Python package (Manim) my code won't recognize the methods used in the package, unless I very precisely tell it where to look. In other words, when trying to just import Manim, I get this:
where PyCharm even seems to indicate that it doesn't need the two gray lines, as it has already imported Manim. The problem is the errors (underlined in red), they point to classes and/or methods from the Manim package, but are not recognized until I precise:
How can I optimize my imports so that one line suffices for all that's concerning Manim? (This works fine with just from manimlib import * using Spyder3 editor.)
As #Mike Scotty pointed out in his comments, import * and from a import * are generally bad ideas, since python won't know what to import, especially if there are multiple classes with the same name.
An IDE not complaining does NOT mean, your code runs smoothly.
You have several options here:
Having a rather large import list (which is by no means wrong) as you have in your second picture.
Using import manimlib and having rather long function/class calls: intro_words = manimlib.mobject.svg.text_mobject.Text
It's possible to bunch similar imports together like this:
from manimlib.mobject import geometry.Polygon as Polygon, svg.text_mobject.Text as Text
To my humble knowledge, the most pythonic way to go, is having very specific imports, even if that means you'll end up with a large import list. To add to this, most IDEs like PyCharm, Atom or Visual Studio have ways collapsing large import lists into one line:
for example PyCharm does this: import ... which displays all imports by clicking on it.
Refer to pythons documentation on imports and pythons documentation on modules to get a better understanding on how imports work.
Related
This question already has answers here:
Can't import my own modules in Python
(14 answers)
Closed 2 years ago.
I am working in python3 for a year now and I still don't get the import system....
I always put the empty init.py file on each folder.
But however if my project start to have nested directories (and it append a lot and often) I have to run a war to be able to import my own module (who python thinks he is ????)... It is driving me crazy.
So for now the 'best' trick I have found, but clearly I am not satisfied with it is to put ligne like this on top of my file:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(file))))
I do not like it, first because when the directory is nested on several level the line is extraordinary long, then because my linter is always yelling at me because my import are not on top of my files.
So I was wondering, what am I missing ? Is there an information I missed ? What's your technique ?
Thank you !
Can't import my own modules in Python
Someone suggested it's similar to this answer but it is not.
First I do not want to use relative import.
Then the 'sys.path.append("..")' is not clean in my opinion, and my imports are still not on top of my files.
Basically let's say I have a structure like:
folder_a
----file_1
----file2
----folder_b
--------file_3
--------folder_c
-----------file_4
I am instanciating a class from file_1 in file_3,I have to do this:
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(file)))))
from folder_a.file_1 import class_1
doing this obviously won't work:
sys.path.append("..")
from folder_a.file_1 import class_1
This is so not logic for me
If you don't want to use relative imports, and you don't want to mess with sys.path, the other option is to package your modules and install them using pip install.
I think that reading the import documentation instead of just trying to "make it work" will be beneficial. Python's documentation is really good. Focus for a while with a good cup of tea and read it :)
This question already has answers here:
Import folder of modules in Python
(3 answers)
Closed 7 years ago.
I know this question has been asked before but I can't make heads or tails of what the answer means.
I am making the transition from MATLAB to Python. In MATLAB I can write my own functions and use them in my code. I know I can do the same thing in Python. But I am having a hard time figuring out how to do it.
What I would like to do it create a file with multiple function definitions and then import it into Python like any other module.
First, is this the proper way of thinking it about it? Or do I just need to create multiple definition files for each function?
Second, if it is the proper way of thinking about it how do I access the file? I know you have to set the PYTHONPATH. I have looked at it and where it is looking makes no sense to me.
As an Example: I created a folder called User. In it I have a python function called ted.py. I put said file where the rest of the library files are located (as in numpy or scipy). I want to import the file called User. How can I do this?
After working with Python for awhile I get it. As long as the file is in the same directory and you use the import properly you can use one , some or all of the function definitions in the file.
You have an un-matlab-like (matlab-unlike? dis-matlab-like?) option of putting multiple function definitions into the same .py file. Once the file -- say, fundefs.py -- is on your path, possibly through having issued import sys; sys.path.append('path/to/fundefs');, you can import it
through import fundefs, after which you can access the functions therein by fundefs.fun1, fundefs.fun2 etc.
through from fundefs import *, which will throw all the functions into your current namespace. This is generally discouraged (and frowned upon) for larger modules as it will pollute your namespace, but for a few functions of your own this might just be what you're after. See also this very informative answer (and also comments therein).
as a middle ground through import very_long_and_descriptive_module_name as shorthand to access your functions as shorthand.fun1, shorthand.fun2 etc. (in the obvious case if your definitions are in the file very_long_and_descriptive_module_name.py)
You don't import User. What you want is to import ted. Typically, you would put ted.py in the same folder as your main python file, not in a separate folder.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python import coding style
When I write some code that requires an import, and the import is only introduced by the bit of code I'm currently writing, should I:
Stick the import at the top of the file where it is made clear that to make this module work it needs these imports, yet the import is detached from the usage and should the need be removed later the module may still import stuff it doesn't ever actually use, or
Keep the import with the code that uses it immediately thereafter so it is obvious what the import is used to do and whence it can be safely removed, but risk importing the same libs multiple times and make it hard to work out what libs are required to make the module work.
Best practice?
Put the import at the top? Or put it where it gets used?
Import_Statement_Overhead from the Python wiki states:
"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."
I follow general stylistic conventions and put all of my import statements at the top of the program. PEP 8 states re imports:
"Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants."
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python: Circular (or cyclic) imports
I'm new to Python, and I'm having an issue, but I'm not exactly sure if this is my issue. I have two files, user.py and comments.py. In user.py, I do
from comments import Comment
and in comments.py I do
from user import User
My user loads fine, but when I load the URL that leads to comments, I get a server error. Commenting out the from comments import Comment fixes the problem. Am I doing something wrong?
Yes, you have a circular import, and those cause many many problems. If you think about what is actually happening when you import, it is analogous to saying, "copy the code from file x in to this file," but if you copy from x to y then back from y to x, you've created an infinite loop where it's difficult to impossible for the interpreter to figure out which module is supposed to supersede or load which in which situations. However, if your program is architected properly, you should not have any. What reason do you have for having this circular import? Chances are you don't actually need it at all if we look at the problem a little more carefully.
This kind of circular import does not work. Importing a module means essentially executing the statements in it. The import statements are executed in the moment they are encountered, so in at least one of the modules the other module has not yet been initialised, so the import will fail.
A circular dependency is considered an antipattern. There are situations where they somehow occur naturally, but in general they are a sign of a bad design.
You can probably make this work by moving one of the import statements to the end of the module or to function level, but I'd recommend against these "fixes".
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Should Python import statements always be at the top of a module?
I recently answered a SO question and provided this routine as a solution:
def set_fontsize(fig,fontsize):
import matplotlib
"""
For each text object of a figure fig, set the font size to fontsize
"""
if not isinstance(fig,matplotlib.figure.Figure):
raise Exception("fig is not a matplotlib.figure.Figure")
for textobj in fig.findobj(match=matplotlib.text.Text):
textobj.set_fontsize(fontsize)
I imported matplotlib into the definition of set_fontsize(fig,fontsize) because it's not guaranteed that someone using this routine would import matplotlib at a more-global scope (better terminology?). Especially since many of the matplotlib examples invoke routines using this import: import matplotlib.pyplot as plt.
Are there instances where my import of matplotlib would cause a conflict?
Are there any efficiency costs?
Is there a preferable/more-common alternative to test if fig is an instance of matplotlib.figure.Figure; an alternative that does not require importing the module?
there's nothing wrong with importing inside functions and classes - it's a useful way of handling mutually recursive imports (where two files each imports the other), for example.
however, there is something wrong with checking the type of an argument. idiomatic python would not check the type of fig. instead, just let misuse fail wherever it fails. this is because you are breaking "duck typing" - people cannot call your routine with objects that "work like" fig, even if they want to (an obvious example is testing mocks; another example is someone writing a replacement for matplotlib that has the same API, but looks or works better).
so, for the code you have there, it is not necessary to have the import at all. just use fig.
more generally, imports are cached when first used, so you typically don't need to worry much about efficiency (i'm not saying it's perfect, but it's the kind of thing you need to profile before worrying about).
There's nothing particularly wrong with importing inside the function - although you should do it after the docstring, otherwise Python won't see the docstring - but your reasoning doesn't make any sense.
If you import at module level, and someone imports your function, the function has access to all the things in its module, including imports. Users of your function don't need to import anything specifically.