In the snippet above, CountWords is the function inside the wordcounter.py file. To make sure this is the case, just create a new Python file in the same directory where you have the wordcounter.py file. Note that all your Python files must be in the same directory, in this case.
Python import functions from another file code#
If you need that function in a new file and don't want to rewrite the whole code or function, all you need to do is import that function as a module in your new file. That file holds a function called CountWords. Remember that you earlier created a file named wordcounter.py. That's it we're created a word counter module. Now that the raw code is working, we then modularize it by creating a function that makes the code reusable: # Next, loop through the variable to count the words in the created variable # create a variable called word that holds some strings Here's what the wordcounter file looks like: In this case, the file is named as wordcounter.py ensure that you use the correct. Next, open up a text editor to your project location and create a new Python file. Note that while you might not have need for a word count, it's how the idea relates to code reusability that matters for this explanation. Generally, you can find a word count by adding one to the number of spaces in a sentence. That's when the concept of OOP comes into play.Īs a good practice, to create the word counter function, we first try to figure out a raw formula for calculating it. But it can also be in the form of methods in a class. The code you intend to reuse sometimes can stand alone as individual functions. While our example here is not based on object-oriented programming (OOP), we must discuss it briefly before moving on to creating a module. In essence, it makes your code more efficient and readable. Code modularization also improves execution speed and makes testing easier. This practice makes your job a lot easier and faster during a real-life project. That name is its identity and means the next time you need to use that block of code, you only need to call out its name and not the whole code. When you modularize a code, you give it a unique name. It's used to separate tasks from each other. Because Python is object-oriented, it's one of those languages that makes code reusability possible.Ĭode modularization involves writing codes that carry out different instructions in blocks. One of the best practices when working with most server-side languages is to modularize your code so that it's reusable. What Is Code Reusability and Why Should You Do It?
Python import functions from another file how to#
Let's take a deeper look to understand the origin of those modules, along with how to create and import them for reuse. However, as a newcomer, you might not have an idea where those modules come from. Whether you're an expert or beginner at Python programming, you must be familiar with the import modules command.