![]() |
|
Feedback on module - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: Feedback on module (/thread-8755.html) |
Feedback on module - GamePatrol - Mar-06-2018 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))
RE: Feedback on module - Gribouillis - Mar-06-2018 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)))
|