From and Import in Python - where is the module loaded from?
Archive - Originally posted on "The Horse's Mouth" - 2016-11-06 10:40:24 - Graham Ellis
Python's from and import statements both require you to give the name of the source from where you'll be loading extra code. And for a module held in a single file, thats's a file name but without extension.
So if I say import fourth, Python will look for a file called fourth.py. Where it looks is governed by a list of places in sys.path so it will look in the current folder and a number of other standard places too. Where a .pyc or .pyo file is found (in a directory called __pycache__ in Python 3) that will be used instead if it's got a more recent timestamp that the .py file, or if no .py file exists. And if no .pyc file exists, Python will write one having done the import so that it's available for next time.
This is good, and in the case of from the name of the file the extra code is read from need not be referred to again. However, with an import, the name of the import needs to be added as a namespace in front of the member names when they are referred to - poor practise as it glues file names to the internals of the code. By using import ... as this issue can be overcome by renaming the namespace being read. For example import fourth as block
to bring in code from fourth.py / fourth.pyc / fourth.pyo. But then it can be referred to under the block namespace: passTheBox.append(block.box(x+layer+1,y+layer+1,z+layer+1))
Recommonedation is to use import rather than from for almost all of your loading of extra code. From mixes up the names you're loading into the current namespace, and as soon as you start getting involved with serious code you're likely to find that you're getting name conflicts. Think back to your schooldays, and think if there were two children with the same forename in your class ...