Exporting a function to another file

Sometimes, to create more encapsulation and modularity for your Python program, you might want to move some functions that perform very specific tasks to another file. Then, other programs can simply import those functions and use them inside their logic. We see this the most in Python programming with util.py files, which are also in most external packages and modules that contain various miscellaneous utility functions.

To simulate this process, let's try moving the two functions we just converted from class methods—draw() and draw_arrow()—into another Python script. Let's get started:

  1. Move your cursor to the signature of one of the two functions (you can also highlight the whole function) and select Refactor | Move... (as always, keep track of the keyboard shortcut for future usage). After this, a familiar pop-up window will appear:

Moving functions to a new file
  1. In the To prompt (highlighted in the preceding screenshot, where you specify which file to send the selected function to), enter point_util.py (or any name for the script that you prefer) within the current path. Note that, even if the file we are specifying does not exist yet, PyCharm will create it automatically for us.
  2. Hit Refactor and the exporting process starts. Afterward, go ahead and do the same thing for the other function (out of draw() and draw_arrow()), while making sure that the destination file is the same for the two files. You can also move several components to another file in bulk by checking them in the Bulk move section, which is in the middle of the pop-up window (illustrated in the preceding screenshot).

A powerful thing about this feature is that import statements are generated according to the interaction between files. In our example, the newly created point_util.py file utilizes the matplotlib library in its functions, so the library was imported automatically there. The matplotlib library was also removed from the point.py file as it is not needed in that scope anymore. Instead, point.py is now importing the draw() function from point_util.py appropriately.

Throughout several topics in this section, we have learned the specifics of some of the most common refactoring techniques in Python programming that PyCharm handles seamlessly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.186.201