Skip to content

Commit

Permalink
GH-30058: [Python] Add StructType attribute to access all its fields (#…
Browse files Browse the repository at this point in the history
…43481)

### Rationale for this change
Currently you cannot directly access the names of all the fields within a StructType, and it is not obvious how to access each field either. This change allows people to directly access the fields and their names directly. See #30058.

### What changes are included in this PR?
I added a .names and .fields attribute to StructType. 
.names returns a list of the names of the fields in the StructType, and .fields returns a list of the fields in the StructType.

### Are these changes tested?
Yes. I made two tests to check if the new .names and .fields attributes would operate as intended. The tests check if the .names attribute would return a list of the names of each field and if .fields returns a list of the fields.

### Are there any user-facing changes?
Yes, there are two new attributes users can now use.

* GitHub Issue: #30058

Authored-by: Abhinand-J <wabhinandj@gmail.com>
Signed-off-by: Joris Van den Bossche <jorisvandenbossche@gmail.com>
  • Loading branch information
Abhinand-J authored Aug 9, 2024
1 parent 4314fd7 commit 7e44aeb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
2 changes: 2 additions & 0 deletions python/pyarrow/tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -693,6 +693,8 @@ def test_struct_type():
assert list(ty) == fields
assert ty[0].name == 'a'
assert ty[2].type == pa.int32()
assert ty.names == [f.name for f in ty]
assert ty.fields == list(ty)
with pytest.raises(IndexError):
assert ty[3]

Expand Down
27 changes: 27 additions & 0 deletions python/pyarrow/types.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -1025,6 +1025,33 @@ cdef class StructType(DataType):
def __reduce__(self):
return struct, (list(self),)

@property
def names(self):
"""
Lists the field names.
Examples
--------
>>> import pyarrow as pa
>>> struct_type = pa.struct([('a', pa.int64()), ('b', pa.float64()), ('c', pa.string())])
>>> struct_type.names
['a', 'b', 'c']
"""
return [f.name for f in self]

@property
def fields(self):
"""
Lists all fields within the StructType.
Examples
--------
>>> import pyarrow as pa
>>> struct_type = pa.struct([('a', pa.int64()), ('b', pa.float64()), ('c', pa.string())])
>>> struct_type.fields
[pyarrow.Field<a: int64>, pyarrow.Field<b: double>, pyarrow.Field<c: string>]
"""
return list(self)

cdef class UnionType(DataType):
"""
Expand Down

0 comments on commit 7e44aeb

Please sign in to comment.