Daniel
Daniel

Reputation: 59

Imports in Python: Some Questions

I am a beginner, so I apologize for this question.

When importing in Python, if I do from star import triangle, am I importing the entire star module, or just the triangle function inside the star module?

As in, when I run my script, what does python do when it looks at that line?

Also, what is happening when someone does from . import square?

I think I saw someone use from ... import square also. What's that also?

Upvotes: 1

Views: 65

Answers (1)

Osamoele
Osamoele

Reputation: 476

In question order :

  • You are importing only the triangle object (function, class...) from your star module

  • Python runs the defintion, checking that there is no "typographic" error (doesn't mean there will be no runtime error later, as scripting language are so versatile, one cannot predict the valididy of a certain context early on, like in compiled language) If this is done without issues, then you have an object "triangle" that contains your definition. In the same exact way doing triangle = 2 you have an object containing an int instance with a value of 2. In python, everything is an object, with methods and properties. You can alwas check the methods of an object doing

    dir(triangle) 
    

    for example. Doing dir(triangle) with triangle being an int, we see that there is a .real method, and other ones. Doing dir(triangle) you would see the methods that your function of class implements. (method enclosed in __underscores__ are default methods, created without the need for you declaring them. They can be overloaded anyway if you want to.

  • from . import x means it imports the module after the "import" keyword, searching in the parent directory (one directory above the one your file is currentely being executed, with vary if you are in your "main" or in a module being imported)

Upvotes: 1

Related Questions