Search code examples
pythonimportpycharmmanim

How to properly import a Python package in PyCharm?


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:

enter image description here

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:

enter image description here

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


Solution

  • 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:

    1. Having a rather large import list (which is by no means wrong) as you have in your second picture.
    2. 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.