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
Related
Let's say I open up a large source file and see this:
print(x)
x isn't defined in this file and there are a dozen import statements. How do I determine where x was imported from?
If x is a primitive type (int, float, complex, str, bytes, etc.) you don't really have a good way of checking it. I guess this serves as a good reminder of avoiding things such as from somemodule import *.
If x is an object (such as a class or a function), then you can look at x.__module__, which will tell you the module name. There is also inspect.getmodule(x) which will give you some more info (e.g. the exact path of the module).
If it is a "primitive type", as Marco calls it, you could try accessing it after each import. Basic version (could be improved):
from fractions import *
try:
pi
print('fractions')
except NameError:
pass
from math import *
try:
pi
print('math')
except NameError:
pass
That reports math. Try it online!
When you import a module e.g. numpy:
import numpy as np
you can clearly see what are numpy objects or numpy methods because you can only call numpy functions for example like this np.roll(), np.array(),...
however if you dont need the full module and only a litte part of it you import it like this
from numpy import roll
now you can call the roll function simply like this:
roll()
Conclusion: If e.g. x is nowhere defined in a script it must come from an import you just need to look exactly how the module is imported
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!
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'
So this is what I'm dealing with:
I have a module A, where
submodule A.B contains a function called "func1"
submodule A.B.C contains a function called "func2"
I also have a separate module B with an class C
Lastly, A.B.func1 uses class C from module B, through the import statement "from B import C"
What I've learned so far is that, if I just do:
from A.B import func1
func1 will work.
However, if I were to do:
from A.B import func1
from A.B.C import func2
func1 will not work.
After digging around and trying stuff, I've found that A.B.func1's usage of C would look at func1's globals to find C (put there by its "from B import C"). However, the entry for C in the globals is overwritten when "from A.B.C import func2" is executed. Basically, the fact that I have both A.B.C and B.C is confusing the global namespace and thus causing this unexpected failure, despite that within each module the code looks correct.
However, I'm at a loss for how to prevent this from happening in the future. What naming rules/conventions should I follow to prevent something like this happening? A drastic solution might be to make sure you never have two submodules with the same name, but I would imagine with a large enough library system this may be difficult to upkeep. What does everyone else do in this situation?
Perhaps I should be using imports differently, and do something other than "from ... import ..."?
Any comments/help would be greatly appreciated.
This looks like circular imports, which in general you need to better structure your project to avoid. If you have to do so, then you need to do a local import. On the other hand, if you have naming conflicts, the easiest thing to do is to simply:
import A
and then call the function with A.B.fun*
I have written the odd handy function while I've been doing python. (A few methods on lists, couple of more useful input functions ect.)
What I want is to be able to access these functions from a python file without having to import a module through import my_module.
The way I though it would happen is automatically importing a module, or putting these functions in another default python module, but I don't really mind how it's done.
Can anyone shed some light on how I should do this?
(I know import my_module is not a lot, but you could end up with
sys.path.append("c:\fake\path")
from my_module import *
which is getting long...)
The python module site is imported automatically whenever the python interpreter is run. This module attempts to import another, named sitecustomize. You could put your functions in there, adding them to the __builtins__ mapping with:
for func in [foo, bar, baz]:
__builtins__[func.__name__] = func
Note that this only works on cpython, where __builtins__ is a mutable dict. Doing so will automatically make these functions available to all your python code for this installation.
I strongly would discourage you from doing so! Implicit is never better than explicit, and anyone maintaining your code will wonder where the hell these came from.
You'd be better off with a from myglobalutils import * import in your modules.
See import this (it says a lot in a few lines). You can import a module which has imported the the other ones, for example:
import my.main # where main.py contains `import X, Y, Z`
# X, Y, and Z access:
my.main.X
my.main.Y
my.main.Z