Library Files

Updated on 28 Dec 2022

If we had all our code in a single file, it might get very big, very complicated very quickly. Besides from the previous section we might want to resuse the random_quote() function in our other scripts without having to copy and paste all the time.

Separate files

Python allows you to separate your code into separate files. We’ve already encountered this when we’ve imported some Python libraries.

import re
import random
import datetime

The interesting thing here is that we can import our own libraries for use, i.e. random_quote! Lets create a new file and put our random_quote() function in it.

random_quote.py

import random

def random_quote():
    quotes = [
        'git',
        'imbecile',
        'invented TIM',
        'need to ask yourself, what are we really trying to solve'
    ]

    return random.choice(quotes)

And now lets import this into our code.

function5.py

import random_quote

print(random_quote.random_quote())

Nuances

A key difference with this technique and from function1.py is that we are using random_quote.random_quote() instead of just random_quote like before. This is because when we import a file, we need to specify the filename (minus the .py) before the function call. So, random_quote.random_quote() is following the syntax.

import filename

filename.function_name()

stopping inadvertent use

The random_quote.py file is meant to be imported into your python scripts. It is not supposed to be executed on its own. How do we stop this type of behaviour:

python3 random_quote.py

We can stop this type of behaviour by adding the following code to random_quote.py.

if __name__ == "__main__":
    print('you can not run this directly.')
    print("use 'import random_quote.py' in your own files to import the functionality")
    print("then you'll be able to use the function like this: random_quote.random_quote()")
    exit()

functions - extended exercise

Our imported file, random_quote.py includes the import statment import random. Can our script that imports random_quote also use the random library or does it need to import it itself?

Write some code to test this out.