Modules and packages

  • small programs, we can just put all our classes into one file and put some code at the end of the file to start them interacting.
  • However, as our projects grow, it can become difficult to find one class that needs to be edited among the many classes we’ve defined.
  • This is where modules come in. Modules are simply Python files, nothing more.
  • The single file in our small program is a module.
  • Two Python files are two modules. If we have two files in the same folder, we can load a class from one module for use in the other module.

  • we can import just the one class we need using the from…notation. Alternatively, we can import just the one class we need using the from… import syntax:
  • If, for some reason, products already has a class called Database, and we don’t want the two names to be confused, we can rename the class when used inside the products module:
  • We can also import multiple items in one statement. If our database module also contains a Query class, we can import both classes using:
  • we can even import all classes and functions from the database module using this syntax:

    Absolute import :-

    Absolute imports specify the complete path to the module, function, or path we want to import. If we need access to the Product class inside the products module, we could use any of these syntaxes to do an absolute import:

    Relative Path:–

    Relative imports are basically a way of saying “find a class, function, or module as it is positioned relative to the current module”. For example, if we are working in the products module and we want to import the Database class from the database module “next” to it, we could use a relative import:

    If we were editing the paypal module inside the ecommerce.payments package, we would want to say, “Use the database package inside the parent package”, instead. That is easily done with two periods:s.

    we had a package containing an email module and wanted to import the send_mail function into our paypal module:

    Open chat