Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the same line of code in all functions?

Tags:

python

I am newbie in Python. I wonder if it is possible that all functions inherit the same line of code?

with open(filename, 'r') as f: as this line of code is the same in all three functions. Is it possible to inherit the code without using classes?

I tried to find the answer on stackoverflow and python documentation, but with no luck.

def word_count(filename):
    with open(filename, 'r') as f:
        return len(f.read().split())


def line_count(filename):
    with open(filename, 'r') as f:
        return len(f.read().splitlines())


def character_count(filename):
    with open(filename, 'r') as f:
        return len(f.read())
like image 653
John Onslaught Avatar asked Sep 02 '15 07:09

John Onslaught


People also ask

How do I put everything on the same line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")

How to reuse a code in Python?

And when it comes to reusing code in Python, it all starts and ends with the humble function. Take some lines of code, give them a name, and you've got a function (which can be reused). Take a collection of functions and package them as a file, and you've got a module (which can also be reused).

What is reusable function?

Functions are reusable, self-contained pieces of code that are called with a single command. They can be designed to accept arguments as input and return values, but they don't need to do either.

How many lines of code are in a function?

The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. Functions should not be 100 lines long. Functions should hardly ever be 20 lines long.


2 Answers

The common code in your case is

with open(filename, 'r') as f:
    contents = f.read()

So just move it to its own function:

def get_file_contents(filename):
    with open(filename, 'r') as f:
        return f.read()

def word_count(filename):
    return len(get_file_contents(filename).split())

def line_count(filename):        
    return len(get_file_contents(filename).splitlines())

def character_count(filename):
    return len(get_file_contents(filename))
like image 115
fjarri Avatar answered Oct 19 '22 11:10

fjarri


What I've done in the past is split the code out into another function, in your example

with open(filename, 'r') as f:
         f.read()

Is common within all of your methods, so I'd look at rewriting it like so.

def read_file(filename):
    with open(filename, 'r') as f:
         return f.read()

def word_count(filename):
    return len(read_file(filename).split())

def line_count(filename):
    return len(read_file(filename).splitlines())

def character_count(filename):
    return len(read_file(filename))
like image 44
AJefferiss Avatar answered Oct 19 '22 10:10

AJefferiss