Python – Module Object and Function Object

functionsmodulespython

I am currently teaching myself Python, using the GNU licensed book "Introduction to Computer Science using Python."

In chapter 3, functions are covered. While I understand the concept of functions and how they simplify code by executing a defined sequence of statements whenever they care called, and that Modules are collections of related functions and variables, stored in a file, I do not understand the concept of module objects and function objects. For example, when "import math" is executed, it says, a module object is created. Also, when a function is defined and is executed, a function object is created.

Could someone please explain what these "objects" are to me?

Best Answer

Python at run-time keeps a lot of information around about the state of the code it's executing, and exposes quite a lot of it to programmers. So, at run time, there is an actual object (an instance of a class) called a module object that is created when a module is imported. It is a genuine Python object and you can do anything with it that you can do with a Python object. It has methods and everything.

When a function definition that gets executed (which isn't the same as the function being executed - normally the definition would be executed once for the function when the module is imported) it creates a function object, which is just a special kind of object that is a wrapper around the executable code. This too is a real object, you can set variables to it, pass it as a parameter, call it's methods, etc.

Related Topic