Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason why when importing python files, you still need to name the file.function_name?

Tags:

python

import

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.

like image 564
Andy Avatar asked Dec 02 '22 00:12

Andy


2 Answers

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.

like image 160
Owen Johnson Avatar answered Dec 06 '22 08:12

Owen Johnson


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
...
like image 33
mgilson Avatar answered Dec 06 '22 09:12

mgilson