Getting to Know the Example Function
00:00 Let’s take a look at a small example. Here I have a function, it’s just an example function that takes as an input, a file object, and then does something with that file object and returns some output, right?
00:13
In this case, what it does is it reads this file object and then just uppercases the text content that’s in there and therefore it’s aptly named as upcase_file_content()
.
00:24
So again, this is just an example and I also have an example text file here, and now I want to upcase these. So what you would do when you just normally open the file, you would use the open()
function and then just run upcase_file_content()
.
00:39 Let’s try it out in the terminal.
00:42
I’m going to use the ptpython
shell, but anything that I do in here works also if you want to use a different shell.
00:51 So first I will need to import this function into my REPL session.
00:55
I’m gonna type from process import
upcase_file_content()
, and it’s a good practice to open a file using a context manager. So I’m gonna use the with
statement and say with open()
, put in the file name.
01:10
This is example.txt
. I’ll open it in read mode,
01:16
and I’ll call it f
for short here. And now I want to call upcase_file_content()
and pass it that file object, right? And let’s also print()
the output so it looks the same.
01:31
Alright, so this is a way I would use this upcase_file_content()
function. And you see it works. It takes the input from example.txt
and then upcases it.
01:41 Alright. What I’m working with here is a function that takes as an input a file object. But now what if you want to simulate this file object, you don’t actually have that file.
01:53
And maybe you’re working in an environment where you can’t create that file, for example, for tests. We’re gonna look at that a little later as well. But for now, I want to show you the solution and how you can simulate such a file object like this example.txt
, using Python and just Python standard library.
Become a Member to join the conversation.