rspec/rules/S6928/python/rule.adoc

65 lines
2.2 KiB
Plaintext

This rule raises an issue when a Python side effect happens inside a `tensorflow.function`.
== Why is this an issue?
Python sides effects such as printing, mutating a list or a global variable, inside of a `tensorflow.function` may not behave as expected.
Because of the https://www.tensorflow.org/guide/function#rules_of_tracing[Rules of tracing],
the execution of side effects will depend on the input values of the function and will execute only once per tracing.
[source,python]
----
import tensorflow as tf
@tf.function
def f(x):
print("A side effect", x)
f(1) # prints "A side effect 1"
f(1) # does not print anything
f(2) # prints "A side effect 2"
----
The example above depicts the issue encountered when using Python side effects in a `tensorflow.function`. As a single trace is created per input values,
the second call to `f(1)` does not output anything to the console.
The best practice would be to avoid using Python side effects and prefer the usage of the TensorFlow API with functions such as `tf.print` or tf.TensorArray`.
== How to fix it
To fix this issue either remove the side effect or use the corresponding TensorFlow function.
=== Code examples
==== Noncompliant code example
[source,python,diff-id=1,diff-type=noncompliant]
----
import tensorflow as tf
@tf.function
def f(x):
print("Printing", x) # Noncompliant print is a side effect
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
import tensorflow as tf
@tf.function
def f(x):
tf.print("Printing", x) # Compliant
----
== Resources
=== Documentation
* TensorFlow Documentation - https://www.tensorflow.org/guide/function#executing_python_side_effects[Executing Python side effects]
* TensorFlow Documentation - https://www.tensorflow.org/api_docs/python/tf/print[tf.print reference]
* TensorFlow Documentation - https://www.tensorflow.org/api_docs/python/tf/summary[tf.summary reference]
* TensorFlow Documentation - https://www.tensorflow.org/api_docs/python/tf/Variable#methods[tf.Variable methods reference]
* TensorFlow Documentation - https://www.tensorflow.org/api_docs/python/tf/TensorArray[tf.TensorArray reference]
* TensorFlow Documentation - https://www.tensorflow.org/api_docs/python/tf/data[tf.data reference]