Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Feedback on module
#1
I wrote a module that calculates the area of shapes and I wanted to get feedback if I'm on the right track before adding more shapes.

import math

# A python program to calculate the area of shapes


# area of a square is length multiplied by width
def area_of_square(length, width):
	_check_if_values_are_strings(length = length, width = width)
	_check_if_values_are_negitive(lenth=length, width = width)
	
	return length * width
	
# area of a triangle is base multiplied by height divided by 2
def area_of_triangle(base_value, height):
	_check_if_values_are_strings(base_value = base_value, height = height)
	_check_if_values_are_negitive(base_value = base_value, height = height)
	
	return (base_value * height) / 2

# area of a circle is radius squared times pi
def area_of_circle(radius):
    _check_if_values_are_strings(radius = radius)
    _check_if_values_are_negitive(radius = radius)
    
    return math.pow(radius,2) * math.pi

	
def _check_if_values_are_strings(**values):
	for k,v in values.items():
		if (isinstance(v,str)):
			raise TypeError("{0} is a string".format(k))
			
def _check_if_values_are_negitive(**values):
	for k,v in values.items():
		if v < 0:
			raise ValueError("{0} is a negitive".format(k))
Reply
#2
Function arguments are seldom checked in python, but there is a place where they are often checked: the standard library! (at least the functions implemented in C). So we cannot say that this is fundamentally unpythonic. It depends on the use case. I would check what the values should be rather than what they should not be, so for example, with more explicit name and message
from numbers import Number

def _fail_unless_non_negative_number(*kwargs):
    for k, v in kwargs.items():
        if not (isinstance(v, Number) and (v >= 0)):
            raise TypeError(('Expected non negative number for parameter', k, 'got', repr(v)))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Feedback on my first Python module CodeRaker 11 6,595 Jun-21-2018, 02:16 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020