What is a MetaPathFinder?
Working with JSON files is not a big deal for Python programmers and the purpose of writing this package is indeed educational. It helps me to understand the import mechanism of the Python language and now I want to tell you that.
A MetaPathFinder is a class that can be derived and tell Python where and how it can find and load a module.
At first, we should know about sys.meta_path , according to Python documentation:
A list of meta path finder objects that have their
find_spec()methods called to see if one of the objects can find the module to be imported.
In other words, sys.meta_path is a list of objects that Python asks them to see if they can find the module or not, respectively. Each of these objects must have a method called find_spec that should return a ModuleSpec instance if and only if they can find the module and returns None otherwise.
It helps a lot if you see it by yourself, so run this code and see the printed results.
find_spec(fullname=kishpil, path=None, target=None)
find_spec(fullname=kishpil.pishpil, path=_NamespacePath(['.../kishpil', '.../kishpil']), target=None)What is a Loader?
Next, we must know how to build an instance of ModuleSpec , this class needs a name and a loader . the name is a string and the loader is an instance of a class derived from importlib.abc.Loader .
Get Hamed Zaghaghi’s stories in your inbox
Join Medium for free to get updates from this writer.
There is a helper method that builds a ModuleSpec instance from a name and a loader , importlib.util.spec_from_loader .
The Loader class should implement two methods, create_module and exec_module . According to Python documentation:
create_module(spec)A method that returns the module object to use when importing a module. This method may return
None, indicating that default module creation semantics should take place.
exec_module(module)An abstract method that executes the module in its own namespace when a module is imported or reloaded. The module should already be initialized when
exec_module()is called. When this method exists,create_module()must be defined.
Again, It helps a lot to see it by yourself.