I am currently doing a python tutorial, but they use IDLE, and I opted to use the interpreter on terminal. So I had to find out how to import a module I created. At first I tried
import my_file
then I tried calling the function inside the module by itself, and it failed. I looked around and doing
my_file.function
works. I am very confused why this needs to be done if it was imported. Also, is there a way around it so that I can just call the function? Can anyone point me in the right direction. Thanks in advance.
If you wanted to use my_file.function
by just calling function
, try using the from
keyword.
Instead of import my_file
try from my_file import *
.
You can also do this to only import parts of a module like so :
from my_file import function1, function2, class1
To avoid clashes in names, you can import things with a different name:
from my_file import function as awesomePythonFunction
EDIT:
Be careful with this, if you import two modules (myfile, myfile2
) that both have the same function
inside, function
will will point to the function
in whatever module you imported last. This could make interesting things happen if you are unaware of it.
This is a central concept to python. It uses namespaces (see the last line of import this
). The idea is that with thousands of people writing many different modules, the likelihood of a name collision is reasonably high. For example, I write module foo
which provides function baz
and Joe Smith writes module bar
which provides a function baz
. My baz
is not the same as Joe Smiths, so in order to differentiate the two, we put them in a namespace (foo
and bar
) so mine can be called by foo.baz()
and Joe's can be called by bar.baz()
.
Of course, typing foo.baz()
all the time gets annoying if you just want baz()
and are sure that none of your other modules imported will provide any problems... That is why python provides the from foo import *
syntax, or even from foo import baz
to only import the function/object/constant baz
(as others have already noted).
Note that things can get even more complex: Assume you have a module foo which provides function bar and baz, below are a few ways to import and then call the functions contained inside foo...
import foo # >>> foo.bar();foo.baz()
import foo as bar # >>> bar.bar();bar.baz()
from foo import bar,baz # >>> bar(); baz()
from foo import * # >>> bar(); baz()
from foo import bar as cow # >>> cow() # This calls bar(), baz() is not available
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With