Best practice for using assert?
To be able to automatically throw an error when x become less than zero throughout the function. You can use class descriptors. Here is an example:
class LessThanZeroException(Exception):
pass
class variable(object):
def __init__(self, value=0):
self.__x = value
def __set__(self, obj, value):
if value < 0:
raise LessThanZeroException('x is less than zero')
self.__x = value
def __get__(self, obj, objType):
return self.__x
class MyClass(object):
x = variable()
>>> m = MyClass()
>>> m.x = 10
>>> m.x -= 20
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "my.py", line 7, in __set__
raise LessThanZeroException('x is less than zero')
LessThanZeroException: x is less than zero
Is it good practice to use assert in Java?
The main reason assertions are not used is because they are not enabled by default. Therefore if you have a condition that is important enough to require an assertion you can't rely on assertions being enabled to get the job done.
As other answers have correctly stated they're designed for development-time testing and debugging because they cost nothing if assertions are disabled in production. I think it's better to create explicit tests in your testing framework (e.g. a unit test for edge conditions) than rely on someone enabling assertions while testing.
However a good example I've seen for using assertions is checking private method arguments. Since you control the access to those methods you can check that your own class is using the method correctly while your public methods use more reliable argument checking techniques (annotations, if statements, 3rd-party libraries, etc). That way even if assertions are disabled your method should be protected but developers looking at the source code can see the preconditions for your method and turn assertions on for an extra safety net when working on that class.
Is using assert() in C++ bad practice?
Assertions are entirely appropriate in C++ code. Exceptions and other error handling mechanisms aren't really intended for the same thing as assertions.
Error handling is for when there's a potential for recovering or reporting an error nicely to the user. For example if there's an error trying to read an input file you may want to do something about that. Errors could result from bugs, but they could also simply be the appropriate output for a given input.
Assertions are for things like checking that an API's requirements are met when the API wouldn't normally be checked, or for checking things the developer believes he's guaranteed by construction. For example if an algorithm requires sorted input you wouldn't normally check that, but you might have an assertion to check it so that debug builds flag that kind of bug. An assertion should always indicate an incorrectly operating program.
If you're writing a program where an unclean shutdown could cause a problem then you may want to avoid assertions. Undefined behavior strictly in terms of the C++ language doesn't qualify as such a problem here, since hitting an assertion is probably already the result of undefined behavior, or the violation of some other requirement which could prevent some clean-up from working properly.
Also if you implement assertions in terms of an exception then it could potentially be caught and 'handled' even though this contradicts the very purpose of the assertion.
What is the use of assert in Python?
The assert
statement exists in almost every programming language. It has two main uses:
It helps detect problems early in your program, where the cause is clear, rather than later when some other operation fails. A type error in Python, for example, can go through several layers of code before actually raising an
Exception
if not caught early on.It works as documentation for other developers reading the code, who see the
assert
and can confidently say that its condition holds from now on.
When you do...
assert condition
... you're telling the program to test that condition, and immediately trigger an error if the condition is false.
In Python, it's roughly equivalent to this:
if not condition:
raise AssertionError()
Try it in the Python shell:
>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
Assertions can include an optional message, and you can disable them when running the interpreter.
To print a message if the assertion fails:
assert False, "Oh no! This assertion failed!"
Do not use parenthesis to call assert
like a function. It is a statement. If you do assert(condition, message)
you'll be running the assert
with a (condition, message)
tuple as first parameter.
As for disabling them, when running python
in optimized mode, where __debug__
is False
, assert statements will be ignored. Just pass the -O
flag:
python -O script.py
See here for the relevant documentation.
Assert on all outputs - is that a good practice?
Using the assert
statements on the instance of an object is generally not good in your case as it is always True
.
The assert
is quite useful to check on the data-type
of the inputs
.
example:
def add_num(num1):
assert isinstance(num1, int), "the num1 should be of type 'int'."
return num1+3
Or the code can be made better when you use the type-hint
to the respective arguments
you pass into the object
of the class
.
example:
def add_num(num1: int):
return num1+3
Best practice: assert methods' argument positioning
Even the answer and comments imply differently, there is actual best practice: be consistent!.
So, choose an ordering (for example your hard-coded/fixture value is first) and stick to that for the rest of your code.
is this assert for development not for production?
If nothing else, you lose control over the behavior of get_age
using assertions, because they can be disabled at runtime without modifying the code itself. For production usage, be more explicit and raise a ValueError
(or, if you deem it worth the effort, a custom subclass of ValueError
):
def get_age(age):
if age <= 0:
raise ValueError("Age can't be nonpositive!")
print("your age is" + str(age))
What is the best practice when unit testing methods that have assertions instead of exceptions?
Interesting question.
In my opinion if you want to test the case where x
or y
are not within range explicitly than you should throw the IllegalArgumentException
and not use assert
. On the other hand you have no method comment that tells the caller of this method that x
or y
must be within a range. So if you see it from the callers perspective you have no right to assert this at all. :-p
I would use assert
for checking pre conditions I have no unit tests for. But on the other hand you simply should have a unit test for that example.
At the end of the day assert
throws a RuntimeException
as well and - as you told - only during development time when a compiler flag is that. So why not simply use the IllegalArgumentException
which seems perfect for that case. And please give the caller of the method the hint in which case it is thrown with the @throws
comment.
My conclusion: assert
is rather useless as long as you have good unit test coverage. It's only good for manual testing during development to check up pre conditions where you don't want or can write explicit unit tests for.
Related Topics
How to Speed Up Bulk Insert to Ms SQL Server Using Pyodbc
Why Don't These List Operations Return the Resulting List
How to Highlight Text in a Tkinter Text Widget
Index a 2D Numpy Array with 2 Lists of Indices
How to Access the Ith Column of a Numpy Multidimensional Array
How to Get the Path of the Current Executed File in Python
What's the Fastest Way of Checking If a Point Is Inside a Polygon in Python
How to Do a Recursive Sub-Folder Search and Return Files in a List
Python Strings and Integer Concatenation
Post-Install Script with Python Setuptools
Is There a Label/Goto in Python