I am trying to understand a piece of Python code.
First, I have the following file structure:
folder1--
model
__init__.py
file1.py
file2.py
__init__.py
The __init__.py
in the folder folder1 has nothing.
The __init__.py
in the folder model has the following:
import os
files = os.listdir(os.path.split(os.path.realpath(__file__))[0])
files.remove('__init__.py')
for file in files:
if file.endswith('.py'):
exec('from .{} import *'.format(file[:-3]))
With that said, I have some code in python that uses all the above Now, I am trying to understand the following code
from folder1 import model as mymodel
My first question is what does this do? I mean model is a folder name right? it is not an object. or is it? What is exactly importing as mymodel
here?
then later in the same code it says
global args, cfg, is_fov120
args = parser.parse_args()
model = getattr(mymodel, args.arch)(sync_bn=False)
Apparently there is some arguments called arch
. What is happening here and what does model
have after this?
Edit
When I do print(mymodel)
I get
<module 'folder1.model' from 'C:\\path\\to\\folder1\\model\\__init__.py'>
Investigating even more I can see that I have imported all the objects from the files in the folder model.
mymodel.files
gives the list of files in the folder, and I can call mymodel.somevariable
if some variable was defined in file1.py or file2.py. As for classes I have to create an object first like x=mymodel.aClass()
and then I can access the elements of the object x.someElement
.
Finally I found out that getattr
is getting a class from the files inside model and I can guess that the sync_bn=False
is a parameter to the constructor of that class.
So in the end, model is an object of that class.
getattr
would get an attribute which is a function or method because it's getting called. – Hundredfold