In using a function, I wish to ensure that the type of the variables are as expected. How to do it right?
Here is an example fake function trying to do just this before going on with its role:
def my_print(begin, text, end): """Print 'text' in UPPER between 'begin' and 'end' in lower """ for i in (begin, text, end): assert isinstance(i, str), "Input variables should be strings" out = begin.lower() + text.upper() + end.lower() print out def test(): """Put your test cases here! """ assert my_print("asdf", "fssfpoie", "fsodf") assert not my_print("fasdf", 33, "adfas") print "All tests passed" test()
Is assert the right approach? Should I use try/except instead?
Also, my assert set of tests does not seem to work properly :S
Thanks pythoneers
To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.
Python has built-in assert statement to use assertion condition in the program. assert statement has a condition or expression which is supposed to be always true. If the condition is false assert halts the program and gives an AssertionError .
Syntax of the Python type() function The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.
The isinstance
built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:
def my_print(text, begin, end): "Print 'text' in UPPER between 'begin' and 'end' in lower" try: print begin.lower() + text.upper() + end.lower() except (AttributeError, TypeError): raise AssertionError('Input variables should be strings')
This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)
You might want to try this example for version 2.6 of Python.
def my_print(text, begin, end): "Print text in UPPER between 'begin' and 'end' in lower." for obj in (text, begin, end): assert isinstance(obj, str), 'Argument of wrong type!' print begin.lower() + text.upper() + end.lower()
However, have you considered letting the function fail naturally instead?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With