tensorflow/tensorflow
Patterns and conventions
Coding patterns the codebase enforces, and how to follow them in new code.
Style guides
- C++: Google C++ Style Guide. Format with
clang-format(configured in.clang-format). - Python: PEP 8 with Google flavor (4-space indent, no
*imports). Lint withpylintconfigured bytensorflow/tools/ci_build/pylintrc(top-level symlink.pylintrc). - Bazel:
buildifier(run before sending PRs). - Markdown / docs: lower-case headings in some sub-projects, but match the surrounding file's style.
CONTRIBUTING.md has links to the official Google style guides and several language-specific notes.
Naming
- C++ files:
snake_case.{h,cc}. CUDA files:*.cu.cc. - C++ types:
CamelCasefor classes,kCamelCasefor constants. - Python:
snake_casefor modules, functions, vars;CamelCasefor classes;UPPER_SNAKEfor module-level constants. - Op kernels: file named after the op family (e.g.
matmul_op.cc,cwise_op_add.cc); the op class isMatMulOp. - Test files end in
_test.ccor_test.py; mock/test helpers in*_test_util.{cc,h,py}.
Error handling
C++
- Returning errors uses
tensorflow::Status(now an alias forabsl::Status). The macros intensorflow/core/platform/errors.h(TF_RETURN_IF_ERROR,TF_ASSIGN_OR_RETURN) are the canonical way to propagate them. - Op kernels signal errors by setting
OpKernelContext::SetStatus(...)or via theOP_REQUIRES_OK(ctx, ...)macro. Never throw exceptions. - Long-lived async operations use
Statuscallbacks; sync APIs returnStatusdirectly.
TF_RETURN_IF_ERROR(ReadFromFile(filename, &out));
OP_REQUIRES(ctx, input.dims() == 2,
errors::InvalidArgument("expected rank-2 input"));Python
- Public APIs raise
tf.errors.*fromtensorflow/python/framework/errors_impl.py(InvalidArgumentError,OutOfRangeError,ResourceExhaustedError). These wrap C++ statuses on the way out of pybind11. - For internal Python logic,
ValueError,TypeError,RuntimeErrorare standard. - Don't
raiseinside@tf.function-traced graphs; usetf.debugging.assert_*instead so the assertion becomes a graph node.
Op + kernel registration
A new op normally needs both:
- An OpDef under
tensorflow/core/ops/. Registered withREGISTER_OP("Foo").Input(...).Output(...).SetShapeFn(...). - A kernel under
tensorflow/core/kernels/. Registered withREGISTER_KERNEL_BUILDER(Name("Foo").Device(DEVICE_CPU), FooOp).
If you change inputs/outputs/attrs of an existing op, you usually need a new op name and a v2 kernel — TF's API stability guarantees forbid breaking existing ops. See systems/kernels-and-ops.
Generated code
A lot of Python is generated:
- Python wrappers for ops (e.g.,
tensorflow/python/ops/gen_math_ops.py) are produced fromOpDefregistrations by Bazel rules intensorflow.bzl. - API export markers come from
@tf_export("foo.bar")decorators (tensorflow/python/util/tf_export.py). Theapi_template*.pyfiles at the repo root are the templates the docs build uses to filltensorflow/_api/.... - Don't hand-edit
gen_*files — change the upstreamREGISTER_OPor template instead.
Backwards compatibility
TensorFlow has explicit API stability guarantees (documented at tensorflow.org under "Versioning"). Implementation in tensorflow/python/util/deprecation.py, with decorators like @deprecated, @deprecated_args, @deprecated_endpoints. When you see one of those decorators, it's making a contract: the function will keep working but emit a warning until at least the next major version.
Cross-cutting patterns
- Trackable /
tf.train.Checkpoint— to make a Python class checkpointable, subclasstensorflow/python/trackable/base.pyand expose dependencies through_track_trackableor_checkpoint_dependencies. tf.Module— the lightweight base class for alltf.keras.layers.Layer,tf.keras.Model, and most user-facing Python classes (tensorflow/python/module/module.py).tf_export— the public API surface is defined by@tf_exportdecorators. Anything not exported is private.- Resource variables — almost all variables are
ResourceVariable(tensorflow/python/ops/resource_variable_ops.py); the olderRefVariableis rarely used.
Related
- tooling — how the generators run.
- systems/kernels-and-ops — kernel patterns in detail.
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.