def fcn_a(): print('function A module name=' + __name__, ';') from test3 import fcn_b def fcn_b(): print('function B module name=' + __name__, ';') fcn_a() print('End-1', 'module name=' + __name__, ';') print('Total End', 'module name=', __name__, ';') print(" ") fcn_b() print('End of fn B module name=' + __name__, ';')Can someone please explain how "from test3 import fcn_b" is importing, The output looks wired
from module import function
from module import function
|
Apr-21-2020, 08:13 PM
It's all one module import is not required.
Apr-21-2020, 08:24 PM
Your codelooks weird. What is the name of this file? Is it test3.py?
You use "import" to import a module so you can use the resources in that module. Python comes with a bunch of standard libraries (math, intertools, types, pprint, datetime, io, sys, tkinter, …) If my graphical user interface program uses tkinter, the top of the fill will have a line like this: import tkinterThen I can use functions from that module like: window = tkinter.Tk() # Make top level window for programYou can write your own modules and import them in other modules as well. It looks like this program is trying to import fcn_b from module test3 (file test3.py) However, the following code immediately defines a new fcn_b, so what was the point of the import? It is also unusual to see an import statement that isn't at the top of the file. What does test3.py look like?
Apr-22-2020, 07:40 AM
(This post was last modified: Apr-22-2020, 07:40 AM by krishanu21.)
Thank u for your reply, I do understand that 'import' command will import a module, but if someone can explain how importing a module inside the same module will work.
A detailed answer will help me to understand the subject. Here the file name is "test3.py"
The reason why it looks weird is because when you do
from some_module import some_name it doesn't import just that name, but the whole module.so you start by calling func_a. it prints function A module name=__main__ . Note __main__ is the name when you execute it and not import it (i.e. top level script).then it imports the module (i.e. goes from the start and then execute fcn_a again. Now the module name is test3 that is because you import in test3 and not execute it.then you continue execution and module name in the print output is again __main__ then the output as result of the import in fcn_a. Note that it does not result in recursive import, the module is imported just once, unless you force to reload it. then the continued output from top level
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link Create MCV example Debug small programs |
|
Users browsing this thread: 2 Guest(s)