In module A, I import module B. Then, in module C, I import module A. In module C, will I be able to use the content of module B implicitly via the import of module A, or will I have to explicitly import it into module C?
That should work just fine. However, it would save you some trouble to explicitly import the module as well if only to keep track in your head when looking back at code
If you have any other questions about importing, try taking a gander to this article here
https://docs.python.org/3/reference/import.html
It should help.
Yes, it will work.
I think however you'll have to do:
import moduleB
rather than:
from moduleB import methodX
A simple example down below to give you a start but really you should read the basic tutorial and give it a go first
#A.py
import B
def func_in_a():
B.func_from_b
#C.py
import A
A.func_in_a():
It works fine.
If C imports A (C.py : import A) and A imports B (A.py : import B) and in B you have a function
def funcb():
return `foo`
you can call it from module C :
res = A.B.funcb()
and it will give res = 'foo'
Related
Thankyou for helping me in advance.
What I am curious is this.
I made the File A, and in there exist module named B, and there is function C.
Then to use the C, I should type
from A import B
B.C() Something like this.
but when I use the module numpy, there is file named numpy, and there are many files and module in the numpy.
And if I just type
Import numpy
then I can use numpy.array and everything even though I didnt import any module.
I also want If I just import the file A, then I can use the function C.
How is it possible? Sorry for my poor English..
You should import it initially as:
from A import B.C
That should help
I am very new to python, I have a simple question.
For example
If I do
import A
then I can use A.b().
I am wondering, how to omit A in A.b()?
If you want to use b from module A:
from A import b
If you want to rename it:
from A import b as my_b
If you need several objects:
from A import b, c, d
If you need everything:
from A import *
About the import * option, please do read this post.
It's rather short, but tl;dr: do not import everything from a module by from A import *.
If you really need everything from the module, or a very big part of its content, prefer the normal import, possibly with renaming:
import numpy as np
import tkinter as tk
Since A is a module, you can do:
from A import b
b()
This question has already been answered, but one thing to note when using imports is that
from module import foo
and
import module
Are absolutely the same, as far as memory and performance is concerned. In either case, the module is compiled and loaded into sys.modules. The only difference is what is brought into your namespace. In the first case, it is foo. In the second case, it is module.
Since the other answers do not explain why using from module import * is bad, this is the reason: * will import everything into your namespace for direct use. This is not a good idea unless you know what you are doing. Name clashes are definitely possible, especially when importing multiple large modules.
This may be a matter of opinion, but I believe import module followed by module.foo() is safer and gives the reader a better idea about that method/attribute, where it came from, and what it is doing. Readability matters!
I have a custom package called 'package' and a custom module in that package called 'module' which has a function returning 'test' when called. When I import my package if I do:
from package import module
Everything works fine but if I do:
from package import *
Or
import package
Then when trying to use the 'module' module it comes up with an error name 'module' is not defined. Why is it not importing the module when I use import * or when I import the package?
The code in the module I am trying to call is this:
def printTest():
return("Test")
The code in the file calling the module is this:
import package
print(module.printTest())
This is a surprisingly common issue and this question was still without an proper answer, so here we go.
Let's suppose we have a module only with functions inside, say:
file app/foo.py:
def a():
print('Hello from foo.a')
def b():
print('Hello from foo.b')
I would genuinely expect this to work (but it DOESN'T):
file app/bar.py:
import app.foo
# These will not work!
foo.a()
foo.b()
It turns out that you have to import each element explicitly or give app.foo a name:
Import everything (usually considered a bad practice):
from app.foo import *
# Both will work fine
a()
b()
Import only what you want:
from app.foo import b
# This will work
b()
# But this will not
a()
Give app.foo a (nice) name:
import app.foo as baz
# Both will work as expected
baz.a()
baz.b()
Even if the examples above use only functions, it works exactly the same for everything declared at the top most scope of the module, like classes or variables.
Hope it helps!
If you just want to execute the script outside the original file, you can try:
exec(open('filename').read())
it may be more suitable than using import?
I was facing the same issue, turns out that the file that I wanted to import has the name in lowercase like this global.py once I changed it to Global.py and added
import Global as glb
in main.py (the file where I wanted to import) everything worked as expected.
I've literally been trying to understand Python imports for about a year now, and I've all but given up programming in Python because it just seems too obfuscated. I come from a C background, and I assumed that import worked like #include, yet if I try to import something, I invariably get errors.
If I have two files like this:
foo.py:
a = 1
bar.py:
import foo
print foo.a
input()
WHY do I need to reference the module name? Why not just be able to write import foo, print a? What is the point of this confusion? Why not just run the code and have stuff defined for you as if you wrote it in one big file? Why can't it work like C's #include directive where it basically copies and pastes your code? I don't have import problems in C.
To do what you want, you can use (not recommended, read further for explanation):
from foo import *
This will import everything to your current namespace, and you will be able to call print a.
However, the issue with this approach is the following. Consider the case when you have two modules, moduleA and moduleB, each having a function named GetSomeValue().
When you do:
from moduleA import *
from moduleB import *
you have a namespace resolution issue*, because what function are you actually calling with GetSomeValue(), the moduleA.GetSomeValue() or the moduleB.GetSomeValue()?
In addition to this, you can use the Import As feature:
from moduleA import GetSomeValue as AGetSomeValue
from moduleB import GetSomeValue as BGetSomeValue
Or
import moduleA.GetSomeValue as AGetSomeValue
import moduleB.GetSomeValue as BGetSomeValue
This approach resolves the conflict manually.
I am sure you can appreciate from these examples the need for explicit referencing.
* Python has its namespace resolution mechanisms, this is just a simplification for the purpose of the explanation.
Imagine you have your a function in your module which chooses some object from a list:
def choice(somelist):
...
Now imagine further that, either in that function or elsewhere in your module, you are using randint from the random library:
a = randint(1, x)
Therefore we
import random
You suggestion, that this does what is now accessed by from random import *, means that we now have two different functions called choice, as random includes one too. Only one will be accessible, but you have introduced ambiguity as to what choice() actually refers to elsewhere in your code.
This is why it is bad practice to import everything; either import what you need:
from random import randint
...
a = randint(1, x)
or the whole module:
import random
...
a = random.randint(1, x)
This has two benefits:
You minimise the risks of overlapping names (now and in future additions to your imported modules); and
When someone else reads your code, they can easily see where external functions come from.
There are a few good reasons. The module provides a sort of namespace for the objects in it, which allows you to use simple names without fear of collisions -- coming from a C background you have surely seen libraries with long, ugly function names to avoid colliding with anybody else.
Also, modules themselves are also objects. When a module is imported in more than one place in a python program, each actually gets the same reference. That way, changing foo.a changes it for everybody, not just the local module. This is in contrast to C where including a header is basically a copy+paste operation into the source file (obviously you can still share variables, but the mechanism is a bit different).
As mentioned, you can say from foo import * or better from foo import a, but understand that the underlying behavior is actually different, because you are taking a and binding it to your local module.
If you use something often, you can always use the from syntax to import it directly, or you can rename the module to something shorter, for example
import itertools as it
When you do import foo, a new module is created inside the current namespace named foo.
So, to use anything inside foo; you have to address it via the module.
However, if you use from from foo import something, you don't have use to prepend the module name, since it will load something from the module and assign to it the name something. (Not a recommended practice)
import importlib
# works like C's #include, you always call it with include(<path>, __name__)
def include(file, module_name):
spec = importlib.util.spec_from_file_location(module_name, file)
mod = importlib.util.module_from_spec(spec)
# spec.loader.exec_module(mod)
o = spec.loader.get_code(module_name)
exec(o, globals())
For example:
#### file a.py ####
a = 1
#### file b.py ####
b = 2
if __name__ == "__main__":
print("Hi, this is b.py")
#### file main.py ####
# assuming you have `include` in scope
include("a.py", __name__)
print(a)
include("b.py", __name__)
print(b)
the output will be:
1
Hi, this is b.py
2
I've following use case:
a.py:
import b
import c
c.fun()
b.py:
def fun():
print 'b'
c.py:
def fun():
b.fun()
python a.py doesn't work. It fails with NameError: global name 'b' is not defined.
My understanding of import in python was that a name is added in sys.modules. If that is the case then c.py should also see module b. But apparently that is not the case. So can anyone explain what exactly happens when a module is imported.
Thanks.
The module c.py has to import b in order to get this working...
When importing a module then it is added to the globals-dictionary that is available in the current script's scope only (use "globals()" to print its content)
You have to add all modules which you want to use in that script.
Other way to pass that module in function argument and after that you can call that modules method.
The other way is to add it in _ _ builtins _ _ which is better explain in other post
You have added b and c to the a module, but but not to the c module. When you are inside a module, you can only see what has been added to it. b and c are added to sys.modules, but you haven't imported sys, and you aren't using sys.modules['b'].