Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between import modx and from modx import *? [duplicate]

Tags:

If I were to import some module called modx, how would that be different from saying

from modx import * 

Wouldn't all the contents be imported from each either way? This is in python just to clarify.

like image 743
DCIndieDev Avatar asked Feb 26 '11 00:02

DCIndieDev


People also ask

What is the difference between import and from import *?

The difference between import and from import in Python is: import imports the whole library. from import imports a specific member or members of the library.

What is the difference between import module and from module?

“import” in Python loads a module into its own namespace whereas “from” imports a module into the current namespace. When “from” is used we don't need to mention the module name whereas, when the “import” is used we should mention the module name.

What is the meaning of import * in Python?

What is Importing? Importing refers to allowing a Python file or a Python module to access the script from another Python file or module. You can only use functions and properties your program can access. For instance, if you want to use mathematical functionalities, you must import the math package first.

What does from turtle import mean?

"import turtle brings" the module and "from turtle import *" brings objects from the module.


2 Answers

If you import somemodule the contained globals will be available via somemodule.someglobal. If you from somemodule import * ALL its globals (or those listed in __all__ if it exists) will be made globals, i.e. you can access them using someglobal without the module name in front of it.

Using from module import * is discouraged as it clutters the global scope and if you import stuff from multiple modules you are likely to get conflicts and overwrite existing classes/functions.

like image 135
ThiefMaster Avatar answered Oct 12 '22 22:10

ThiefMaster


If a defines a.b and a.c...

import a a.b() a.c() 

vs.

from a import b b() c() # fails because c isn't imported 

vs.

from a import * b() c() 

Note that from foo import * is generally frowned upon since:

  1. It puts things into the global namespace without giving you fine control
  2. It can cause collisions, due to everything being in the global namespace
  3. It makes it unclear what is actually defined in the current file, since the list of what it defines can vary depending on what's imported.
like image 42
Amber Avatar answered Oct 12 '22 22:10

Amber