# uproot.WritableTree

Defined in [uproot.writing.writable](https://github.com/scikit-hep/uproot/blob/f1299d71fa4f435b1901386346c8a42adbd72642/src/uproot/writing/writable.py) on [line 2355](https://github.com/scikit-hep/uproot/blob/f1299d71fa4f435b1901386346c8a42adbd72642/src/uproot/writing/writable.py#L2355).

### *class* uproot.writing.writable.WritableTree(path, file, cascading)

* **Parameters:**
  * **path** (*tuple* *of* *str*) – Path of directory names to this TTree.
  * **file** ([uproot.WritableFile](uproot.writing.writable.WritableFile.html.md)) – Handle to the file in
    which this TTree can be found.
  * **cascading** (uproot.writing._cascadetree.Tree) – The low-level
    directory object.

Represents a writable `TTree` from a ROOT file.

This object can be created using the [mktree](uproot.writing.writable.WritableDirectory.html.md#uproot-writing-writable-writabledirectory-mktree) method. For instance:

```python
my_directory.mktree("tree1", {"branch1": np.array(...), "branch2": ak.Array(...)})
my_directory.mktree("tree2", numpy_structured_array)
my_directory.mktree("tree3", awkward_record_array)
my_directory.mktree("tree4", pandas_dataframe)
```

Recognized data types:

* dict of NumPy arrays (flat, multidimensional, and/or structured), Awkward Arrays containing one level of variable-length lists and/or one level of records, or a Pandas DataFrame with a numeric index
* a single NumPy structured array (one level deep)
* a single Awkward Array containing one level of variable-length lists and/or one level of records
* a single Pandas DataFrame with a numeric index

The arrays may have different types, but their lengths must be identical, at
least in the first dimension (i.e. number of entries).

If the Awkward Array contains variable-length lists (i.e. it is “jagged”), a
counter TBranch will be created along with the data TBranch. ROOT needs the
counter TBranch to quantify the size of the variable-size arrays. Combining
Awkward Arrays with the same number of nested items using
[ak.zip](https://awkward-array.readthedocs.io/en/latest/_auto/ak.zip.html) prevents
a proliferation of counter TBranches:

```python
my_directory.mktree("tree5", ak.zip({"branch1": array1, "branch2": array2, "branch3": array3}))
```

would produce only one counter TBranch.

The uproot.writing.writable.WritableDirectory.mktree method allows you to separate
the process of creating the TTree metadata from filling the first TBasket:

```python
my_directory.mktree("tree6", {"branch1": numpy_dtype, "branch2": awkward_type})
```

The uproot.writing.writable.WritableDirectory.mktree method can also control the
title of the TTree and the rules used to name counter TBranches and nested field TBranches.

The `numpy_dtype` is any data that NumPy recognizes as a `np.dtype`, and the
`awkward_type` is an [ak.types.Type](https://awkward-array.readthedocs.io/en/latest/ak.types.Type.html) from
[ak.type](https://awkward-array.readthedocs.io/en/latest/_auto/ak.type.html) or
a string in that form, such as `"var * float64"` for variable-length doubles.

TBaskets can be added to each TBranch using the [extend](#uproot-writing-writable-writabletree-extend)
method:

```python
my_directory["tree6"].extend({"branch1": another_numpy_array,
                              "branch2": another_awkward_array})
```

Be sure to make these extensions as large as is feasible within memory constraints,
because a ROOT file full of small TBaskets is bloated (larger than it needs to be)
and slow to read (especially for Uproot, but also for ROOT).

For instance, if you want to write a million events and have enough memory
available to do that 100 thousand events at a time (total of 10 TBaskets),
then do so. Filling the TTree a hundred events at a time (total of 10000 TBaskets)
would be considerably slower for writing and reading, and the file would be much
larger than it could otherwise be, even with compression.

<a id="uproot-writing-writable-writabletree-path"></a>

## path

#### WritableTree.path

Path of directory names to this TTree as a tuple of strings.

<a id="uproot-writing-writable-writabletree-object-path"></a>

## object_path

#### WritableTree.object_path

Path of directory names to this TTree as a single string, delimited by
slashes.

<a id="uproot-writing-writable-writabletree-file-path"></a>

## file_path

#### WritableTree.file_path

Filesystem path of the open file, or None if using a file-like object.

<a id="uproot-writing-writable-writabletree-file"></a>

## file

#### WritableTree.file

Handle to the [uproot.WritableDirectory](uproot.writing.writable.WritableDirectory.html.md) in which
this directory can be found.

<a id="uproot-writing-writable-writabletree-close"></a>

## close

#### WritableTree.close()

Explicitly close the file.

(Files can also be closed with the Python `with` statement, as context
managers.)

After closing, objects cannot be read from or written to the file.

<a id="uproot-writing-writable-writabletree-closed"></a>

## closed

#### WritableTree.closed

True if the file has been closed; False otherwise.

The file may have been closed explicitly with
[close](uproot.writing.writable.WritableFile.html.md#uproot-writing-writable-writablefile-close) or implicitly in the Python
`with` statement, as a context manager.

After closing, objects cannot be read from or written to the file.

<a id="uproot-writing-writable-writabletree-compression"></a>

## compression

#### WritableTree.compression

Compression algorithm and level ([uproot.compression.Compression](uproot.compression.Compression.html.md) or None)
for new TBaskets added to the TTree.

This property can be changed and doesn’t have to be the same as the compression
of the file, which allows you to write different objects with different
compression settings.

The following are equivalent:

```python
my_directory["tree"]["branch1"].compression = uproot.ZLIB(1)
my_directory["tree"]["branch2"].compression = uproot.LZMA(9)
```

and

```python
my_directory["tree"].compression = {"branch1": uproot.ZLIB(1),
                                    "branch2": uproot.LZMA(9)}
```

<a id="uproot-writing-writable-writabletree-num-entries"></a>

## num_entries

#### WritableTree.num_entries

The number of entries accumulated so far.

<a id="uproot-writing-writable-writabletree-num-baskets"></a>

## num_baskets

#### WritableTree.num_baskets

The number of TBaskets accumulated so far.

<a id="uproot-writing-writable-writabletree-add-branches"></a>

## add_branches

#### WritableTree.add_branches(branches, \*, counter_name=None)

* **Parameters:**
  * **branches** (*dict* *of* *str -> array*) – Names and data of new branches.
  * **counter_name** (*callable* *of* *str -> str* *,* *optional*) – Function to generate
    counter-TBranch names for Awkward Arrays of variable-length lists.
    Defaults to the tree’s configured counter_name (typically `"n" + name`).

Adds new branches to this TTree in-place. Only the new branch data and
an updated TTree header are written; existing baskets are never touched.

```python
with uproot.update("file.root") as f:
    f["tree"].add_branches({"new_branch": np.ones(100, dtype=np.float32)})
```

#### NOTE
Only trees whose branches are all plain `TBranch` (not
`TBranchElement`, e.g. split objects) are supported. Rewriting
the branch listing for a tree with `TBranchElement` branches
would silently drop them, so this raises `NotImplementedError`
for such trees instead. This mirrors the same restriction on
[extend](#uproot-writing-writable-writabletree-extend). The same goes
for other things that the rewritten listing would lose, such as
data in embedded baskets, cluster ranges, and packed branches.

A new branch always gets one basket, so this also raises
`NotImplementedError` for a tree whose branches all have the same
number of baskets, if that number is more than one: the result
couldn’t be extended anymore.

<a id="uproot-writing-writable-writabletree-extend"></a>

## extend

#### WritableTree.extend(data, \*, accept_new_fields=False)

* **Parameters:**
  * **data** (*dict* *of* *str → arrays*) – More array data to add to the TTree.
  * **accept_new_fields** (*bool*) – If True, new fields in data are automatically added
    with zeros back-filled for existing entries before extending: empty
    lists for jagged fields, or lists of zeros if a jagged field’s
    counter (per the tree’s `counter_name`) already exists. A new
    field given as a list of lists that all have the same length gets
    a fixed size, like a NumPy array; pass an Awkward Array to make
    it jagged.

This method adds data to an existing TTree, whether it was created through
assignment or uproot.writing.writable.WritableDirectory.mktree.

The arrays must be a dict, but the values of the dict can be any of the
array/DataFrame types described in [uproot.WritableTree](uproot.writing.writable.WritableTree.html.md).
However, these types must be compatible with the established TBranch
types, the dict must contain a key for every TBranch, and the arrays must have
the same lengths (in their first dimension).

For example,

```python
my_directory.mktree("tree6", {"branch1": numpy_dtype, "branch2": awkward_type})

my_directory["tree6"].extend({"branch1": another_numpy_array,
                              "branch2": another_awkward_array})
```

#### WARNING
**As a word of warning,** be sure that each call to [extend](#uproot-writing-writable-writabletree-extend) includes at least 100 kB per branch/array. (NumPy and Awkward Arrays have an [nbytes](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.nbytes.html) property; you want at least `100000` per array.) If you ask Uproot to write very small TBaskets, it will spend more time working on TBasket overhead than actually writing data. The absolute worst case is one-entry-per-[extend](#uproot-writing-writable-writabletree-extend). See [#428 (comment)](https://github.com/scikit-hep/uproot/pull/428#issuecomment-908703486).

#### NOTE
On a tree reopened with uproot.writing.writable.WritableDirectory.update,
only trees whose branches are all plain `TBranch` (not
`TBranchElement`, e.g. split objects) are supported, only trees
with no data in embedded baskets, and only trees whose branches all
agree on basket count/capacity (true by construction for a tree
Uproot itself wrote and has not touched with
[add_branches](#uproot-writing-writable-writabletree-add-branches) since).
Trees with anything else Uproot can’t rewrite, such as cluster
ranges and packed branches, aren’t supported either.
Any of these cases raises `NotImplementedError` rather than
desynchronizing or corrupting the tree’s branches.

<a id="uproot-writing-writable-writabletree-show"></a>

## show

#### WritableTree.show(\*, filter_name=<function no_filter>, filter_typename=<function no_filter>, filter_branch=<function no_filter>, recursive=True, full_paths=True, name_width=20, typename_width=24, interpretation_width=30, stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)

Opens the TTree for reading and calls uproot.behaviors.TBranch.HasBranches.show
on it (follow link for documentation of this method).
