Skip to content

Synapse Factory Operations

Contained within this file are experimental interfaces for working with the Synapse Python Client. Unless otherwise noted these interfaces are subject to change at any time. Use at your own risk.

API Reference

synapseclient.operations.get_async async

get_async(synapse_id: Optional[str] = None, *, entity_name: Optional[str] = None, parent_id: Optional[str] = None, version_number: Optional[int] = None, activity_options: Optional[ActivityOptions] = None, file_options: Optional[FileOptions] = None, table_options: Optional[TableOptions] = None, link_options: Optional[LinkOptions] = None, synapse_client: Optional[Synapse] = None) -> Union[Dataset, DatasetCollection, EntityView, File, Folder, Link, MaterializedView, Project, SubmissionView, Table, VirtualTable]

Factory method to retrieve any Synapse entity by its ID or by name and parent ID.

This method serves as a unified interface for retrieving any type of Synapse entity without needing to know the specific entity type beforehand. It automatically determines the entity type and returns the appropriate model instance.

You can retrieve entities in two ways:

  1. By providing a synapse_id directly
  2. By providing entity_name and optionally parent_id for lookup
PARAMETER DESCRIPTION
synapse_id

The Synapse ID of the entity to retrieve (e.g., 'syn123456'). Mutually exclusive with entity_name.

TYPE: Optional[str] DEFAULT: None

entity_name

The name of the entity to find. Must be used with this approach instead of synapse_id. When looking up projects, parent_id should be None.

TYPE: Optional[str] DEFAULT: None

parent_id

The parent entity ID when looking up by name. Set to None when looking up projects by name. Only used with entity_name.

TYPE: Optional[str] DEFAULT: None

version_number

The specific version number of the entity to retrieve. Only applies to versionable entities (File, Table, Dataset). If not specified, the most recent version will be retrieved. Ignored for other entity types.

TYPE: Optional[int] DEFAULT: None

file_options

File-specific configuration options. Only applies to File entities. Ignored for other entity types.

TYPE: Optional[FileOptions] DEFAULT: None

link_options

Link-specific configuration options. Only applies when the entity is a Link. Ignored for other entity types.

TYPE: Optional[LinkOptions] DEFAULT: None

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
Union[Dataset, DatasetCollection, EntityView, File, Folder, Link, MaterializedView, Project, SubmissionView, Table, VirtualTable]

The appropriate Synapse entity model instance based on the entity type.

RAISES DESCRIPTION
ValueError

If both synapse_id and entity_name are provided, or if neither is provided.

ValueError

If entity_name is provided without this being a valid lookup scenario.

ValueError

If the synapse_id is not a valid Synapse ID format.

Note

When using entity_name lookup:

  • For projects: leave parent_id=None
  • For all other entities: provide the parent_id of the containing folder/project
Retrieving entities by ID

Get any entity by Synapse ID:

import asyncio
from synapseclient import Synapse
from synapseclient.models import File, Project
from synapseclient.operations import get_async

async def main():
    syn = Synapse()
    syn.login()

    # Works for any entity type
    entity = await get_async(synapse_id="syn123456")

    # The returned object will be the appropriate type
    if isinstance(entity, File):
        print(f"File: {entity.name}")
    elif isinstance(entity, Project):
        print(f"Project: {entity.name}")

asyncio.run(main())
Retrieving entities by name

Get an entity by name and parent:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import get_async

async def main():
    syn = Synapse()
    syn.login()

    # Get a file by name within a folder
    entity = await get_async(
        entity_name="my_file.txt",
        parent_id="syn123456"
    )

    # Get a project by name (parent_id=None)
    project = await get_async(
        entity_name="My Project",
        parent_id=None
    )

asyncio.run(main())
Retrieving a specific version

Get a specific version of a versionable entity:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import get_async

async def main():
    syn = Synapse()
    syn.login()

    entity = await get_async(synapse_id="syn123456", version_number=2)

asyncio.run(main())
Retrieving a file with custom options

Get file metadata with specific download options:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import get_async, FileOptions, ActivityOptions

async def main():
    syn = Synapse()
    syn.login()

    file_entity = await get_async(
        synapse_id="syn123456",
        activity_options=ActivityOptions(include_activity=True),
        file_options=FileOptions(
            download_file=False
        )
    )

asyncio.run(main())
Retrieving a table with activity and columns

Get table with activity and column information:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import get_async, ActivityOptions, TableOptions

async def main():
    syn = Synapse()
    syn.login()

    table_entity = await get_async(
        synapse_id="syn123456",
        activity_options=ActivityOptions(include_activity=True),
        table_options=TableOptions(include_columns=True)
    )

asyncio.run(main())
Following links

Get the target of a link entity:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import get_async, LinkOptions

async def main():
    syn = Synapse()
    syn.login()

    target_entity = await get_async(
        synapse_id="syn123456",
        link_options=LinkOptions(follow_link=True)
    )

asyncio.run(main())
Working with Link entities

Get a Link entity without following it:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import get_async, LinkOptions

async def main():
    syn = Synapse()
    syn.login()

    # Get the link entity itself
    link_entity = await get_async(
        synapse_id="syn123456",  # Example link ID
        link_options=LinkOptions(follow_link=False)
    )
    print(f"Link: {link_entity.name} -> {link_entity.target_id}")

    # Then follow the link to get the target
    target_entity = await get_async(
        synapse_id="syn123456",
        link_options=LinkOptions(follow_link=True)
    )
    print(f"Target: {target_entity.name} (type: {type(target_entity).__name__})")

asyncio.run(main())
Comprehensive File options

Download file with custom location and collision handling:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import get_async, FileOptions

async def main():
    syn = Synapse()
    syn.login()

    file_entity = await get_async(
        synapse_id="syn123456",
        file_options=FileOptions(
            download_file=True,
            download_location="/path/to/download/",
            if_collision="overwrite.local"
        )
    )
    print(f"Downloaded file: {file_entity.name} to {file_entity.path}")

asyncio.run(main())
Table options for table-like entities

Get table entities with column information:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import get_async, TableOptions

async def main():
    syn = Synapse()
    syn.login()

    # Works for Table, Dataset, EntityView, MaterializedView,
    # SubmissionView, VirtualTable, and DatasetCollection
    table_entity = await get_async(
        synapse_id="syn123456",  # Example table ID
        table_options=TableOptions(include_columns=True)
    )
    print(f"Table: {table_entity.name} with {len(table_entity.columns)} columns")

asyncio.run(main())
Combining multiple options

Get a File with both activity and custom download options:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import get_async, FileOptions, ActivityOptions

async def main():
    syn = Synapse()
    syn.login()

    file_entity = await get_async(
        synapse_id="syn123456",
        activity_options=ActivityOptions(include_activity=True),
        file_options=FileOptions(
            download_file=False
        )
    )
    print(f"File: {file_entity.name} (activity included: {file_entity.activity is not None})")

asyncio.run(main())
Working with entity instances

Pass an existing entity instance to refresh or apply new options:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import get_async, FileOptions

async def main():
    syn = Synapse()
    syn.login()

    # Get an entity first
    entity = await get_async(synapse_id="syn123456")
    print(f"Original entity: {entity.name}")

    # Then use the entity instance to get it again with different options
    refreshed_entity = await get_async(
        entity,
        file_options=FileOptions(download_file=False)
    )
    print(f"Refreshed entity: {refreshed_entity.name} (download_file: {refreshed_entity.download_file})")

asyncio.run(main())
Source code in synapseclient/operations/factory_operations.py
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
async def get_async(
    synapse_id: Optional[str] = None,
    *,
    entity_name: Optional[str] = None,
    parent_id: Optional[str] = None,
    version_number: Optional[int] = None,
    activity_options: Optional[ActivityOptions] = None,
    file_options: Optional[FileOptions] = None,
    table_options: Optional[TableOptions] = None,
    link_options: Optional[LinkOptions] = None,
    synapse_client: Optional["Synapse"] = None,
) -> Union[
    "Dataset",
    "DatasetCollection",
    "EntityView",
    "File",
    "Folder",
    "Link",
    "MaterializedView",
    "Project",
    "SubmissionView",
    "Table",
    "VirtualTable",
]:
    """
    Factory method to retrieve any Synapse entity by its ID or by name and parent ID.

    This method serves as a unified interface for retrieving any type of Synapse entity
    without needing to know the specific entity type beforehand. It automatically
    determines the entity type and returns the appropriate model instance.

    You can retrieve entities in two ways:

    1. By providing a synapse_id directly
    2. By providing entity_name and optionally parent_id for lookup

    Arguments:
        synapse_id: The Synapse ID of the entity to retrieve (e.g., 'syn123456').
            Mutually exclusive with entity_name.
        entity_name: The name of the entity to find. Must be used with this approach
            instead of synapse_id. When looking up projects, parent_id should be None.
        parent_id: The parent entity ID when looking up by name. Set to None when
            looking up projects by name. Only used with entity_name.
        version_number: The specific version number of the entity to retrieve. Only
            applies to versionable entities (File, Table, Dataset). If not specified,
            the most recent version will be retrieved. Ignored for other entity types.
        file_options: File-specific configuration options. Only applies to File entities.
            Ignored for other entity types.
        link_options: Link-specific configuration options. Only applies when the entity
            is a Link. Ignored for other entity types.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        The appropriate Synapse entity model instance based on the entity type.

    Raises:
        ValueError: If both synapse_id and entity_name are provided, or if neither is provided.
        ValueError: If entity_name is provided without this being a valid lookup scenario.
        ValueError: If the synapse_id is not a valid Synapse ID format.

    Note:
        When using entity_name lookup:

        - For projects: leave parent_id=None
        - For all other entities: provide the parent_id of the containing folder/project

    Example: Retrieving entities by ID
        Get any entity by Synapse ID:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File, Project
        from synapseclient.operations import get_async

        async def main():
            syn = Synapse()
            syn.login()

            # Works for any entity type
            entity = await get_async(synapse_id="syn123456")

            # The returned object will be the appropriate type
            if isinstance(entity, File):
                print(f"File: {entity.name}")
            elif isinstance(entity, Project):
                print(f"Project: {entity.name}")

        asyncio.run(main())
        ```

    Example: Retrieving entities by name
        Get an entity by name and parent:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import get_async

        async def main():
            syn = Synapse()
            syn.login()

            # Get a file by name within a folder
            entity = await get_async(
                entity_name="my_file.txt",
                parent_id="syn123456"
            )

            # Get a project by name (parent_id=None)
            project = await get_async(
                entity_name="My Project",
                parent_id=None
            )

        asyncio.run(main())
        ```

    Example: Retrieving a specific version
        Get a specific version of a versionable entity:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import get_async

        async def main():
            syn = Synapse()
            syn.login()

            entity = await get_async(synapse_id="syn123456", version_number=2)

        asyncio.run(main())
        ```

    Example: Retrieving a file with custom options
        Get file metadata with specific download options:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import get_async, FileOptions, ActivityOptions

        async def main():
            syn = Synapse()
            syn.login()

            file_entity = await get_async(
                synapse_id="syn123456",
                activity_options=ActivityOptions(include_activity=True),
                file_options=FileOptions(
                    download_file=False
                )
            )

        asyncio.run(main())
        ```

    Example: Retrieving a table with activity and columns
        Get table with activity and column information:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import get_async, ActivityOptions, TableOptions

        async def main():
            syn = Synapse()
            syn.login()

            table_entity = await get_async(
                synapse_id="syn123456",
                activity_options=ActivityOptions(include_activity=True),
                table_options=TableOptions(include_columns=True)
            )

        asyncio.run(main())
        ```

    Example: Following links
        Get the target of a link entity:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import get_async, LinkOptions

        async def main():
            syn = Synapse()
            syn.login()

            target_entity = await get_async(
                synapse_id="syn123456",
                link_options=LinkOptions(follow_link=True)
            )

        asyncio.run(main())
        ```

    Example: Working with Link entities
        Get a Link entity without following it:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import get_async, LinkOptions

        async def main():
            syn = Synapse()
            syn.login()

            # Get the link entity itself
            link_entity = await get_async(
                synapse_id="syn123456",  # Example link ID
                link_options=LinkOptions(follow_link=False)
            )
            print(f"Link: {link_entity.name} -> {link_entity.target_id}")

            # Then follow the link to get the target
            target_entity = await get_async(
                synapse_id="syn123456",
                link_options=LinkOptions(follow_link=True)
            )
            print(f"Target: {target_entity.name} (type: {type(target_entity).__name__})")

        asyncio.run(main())
        ```

    Example: Comprehensive File options
        Download file with custom location and collision handling:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import get_async, FileOptions

        async def main():
            syn = Synapse()
            syn.login()

            file_entity = await get_async(
                synapse_id="syn123456",
                file_options=FileOptions(
                    download_file=True,
                    download_location="/path/to/download/",
                    if_collision="overwrite.local"
                )
            )
            print(f"Downloaded file: {file_entity.name} to {file_entity.path}")

        asyncio.run(main())
        ```

    Example: Table options for table-like entities
        Get table entities with column information:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import get_async, TableOptions

        async def main():
            syn = Synapse()
            syn.login()

            # Works for Table, Dataset, EntityView, MaterializedView,
            # SubmissionView, VirtualTable, and DatasetCollection
            table_entity = await get_async(
                synapse_id="syn123456",  # Example table ID
                table_options=TableOptions(include_columns=True)
            )
            print(f"Table: {table_entity.name} with {len(table_entity.columns)} columns")

        asyncio.run(main())
        ```

    Example: Combining multiple options
        Get a File with both activity and custom download options:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import get_async, FileOptions, ActivityOptions

        async def main():
            syn = Synapse()
            syn.login()

            file_entity = await get_async(
                synapse_id="syn123456",
                activity_options=ActivityOptions(include_activity=True),
                file_options=FileOptions(
                    download_file=False
                )
            )
            print(f"File: {file_entity.name} (activity included: {file_entity.activity is not None})")

        asyncio.run(main())
        ```

    Example: Working with entity instances
        Pass an existing entity instance to refresh or apply new options:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import get_async, FileOptions

        async def main():
            syn = Synapse()
            syn.login()

            # Get an entity first
            entity = await get_async(synapse_id="syn123456")
            print(f"Original entity: {entity.name}")

            # Then use the entity instance to get it again with different options
            refreshed_entity = await get_async(
                entity,
                file_options=FileOptions(download_file=False)
            )
            print(f"Refreshed entity: {refreshed_entity.name} (download_file: {refreshed_entity.download_file})")

        asyncio.run(main())
        ```
    """
    from synapseclient.api.entity_bundle_services_v2 import (
        get_entity_id_bundle2,
        get_entity_id_version_bundle2,
    )
    from synapseclient.api.entity_services import get_child, get_entity_type
    from synapseclient.core.constants import concrete_types
    from synapseclient.models import (
        Dataset,
        DatasetCollection,
        EntityView,
        File,
        Folder,
        Link,
        MaterializedView,
        Project,
        SubmissionView,
        Table,
        VirtualTable,
    )

    activity_options = activity_options or ActivityOptions()
    file_options = file_options or FileOptions()
    table_options = table_options or TableOptions()
    link_options = link_options or LinkOptions()

    # Handle case where an entity instance is passed directly
    entity_types = (
        Dataset,
        DatasetCollection,
        EntityView,
        File,
        Folder,
        Link,
        MaterializedView,
        Project,
        SubmissionView,
        Table,
        VirtualTable,
    )
    if isinstance(synapse_id, entity_types):
        return await _handle_entity_instance(
            entity=synapse_id,
            version_number=version_number,
            activity_options=activity_options,
            file_options=file_options,
            table_options=table_options,
            link_options=link_options,
            synapse_client=synapse_client,
        )

    # Validate input parameters
    if synapse_id is not None and entity_name is not None:
        raise ValueError(
            "Cannot specify both synapse_id and entity_name. "
            "Use synapse_id for direct lookup or entity_name with optional parent_id for name-based lookup."
        )

    if synapse_id is None and entity_name is None:
        raise ValueError(
            "Must specify either synapse_id or entity_name. "
            "Use synapse_id for direct lookup or entity_name with optional parent_id for name-based lookup."
        )

    # If looking up by name, get the synapse_id first
    if entity_name is not None and synapse_id is None:
        synapse_id = await get_child(
            entity_name=entity_name, parent_id=parent_id, synapse_client=synapse_client
        )
        if synapse_id is None:
            if parent_id is None:
                raise SynapseNotFoundError(
                    f"Project with name '{entity_name}' not found."
                )
            else:
                raise SynapseNotFoundError(
                    f"Entity with name '{entity_name}' not found in parent '{parent_id}'."
                )

    entity_header = await get_entity_type(
        entity_id=synapse_id, synapse_client=synapse_client
    )
    entity_type = entity_header.type

    if entity_type == concrete_types.LINK_ENTITY:
        return await _handle_link_entity(
            synapse_id=synapse_id,
            link_options=link_options,
            file_options=file_options,
            synapse_client=synapse_client,
        )

    elif entity_type == concrete_types.FILE_ENTITY:
        return await _handle_file_entity(
            synapse_id=synapse_id,
            version_number=version_number,
            activity_options=activity_options,
            file_options=file_options,
            synapse_client=synapse_client,
        )

    elif entity_type == concrete_types.PROJECT_ENTITY:
        return await _handle_simple_entity(
            entity_class=Project,
            synapse_id=synapse_id,
            version_number=version_number,
            synapse_client=synapse_client,
        )

    elif entity_type == concrete_types.FOLDER_ENTITY:
        return await _handle_simple_entity(
            entity_class=Folder,
            synapse_id=synapse_id,
            version_number=version_number,
            synapse_client=synapse_client,
        )

    elif entity_type == concrete_types.TABLE_ENTITY:
        return await _handle_table_like_entity(
            entity_class=Table,
            synapse_id=synapse_id,
            version_number=version_number,
            activity_options=activity_options,
            table_options=table_options,
            synapse_client=synapse_client,
        )

    elif entity_type == concrete_types.DATASET_ENTITY:
        return await _handle_table_like_entity(
            entity_class=Dataset,
            synapse_id=synapse_id,
            version_number=version_number,
            activity_options=activity_options,
            table_options=table_options,
            synapse_client=synapse_client,
        )

    elif entity_type == concrete_types.DATASET_COLLECTION_ENTITY:
        return await _handle_table_like_entity(
            entity_class=DatasetCollection,
            synapse_id=synapse_id,
            version_number=version_number,
            activity_options=activity_options,
            table_options=table_options,
            synapse_client=synapse_client,
        )

    elif entity_type == concrete_types.ENTITY_VIEW:
        return await _handle_table_like_entity(
            entity_class=EntityView,
            synapse_id=synapse_id,
            version_number=version_number,
            activity_options=activity_options,
            table_options=table_options,
            synapse_client=synapse_client,
        )

    elif entity_type == concrete_types.MATERIALIZED_VIEW:
        return await _handle_table_like_entity(
            entity_class=MaterializedView,
            synapse_id=synapse_id,
            version_number=version_number,
            activity_options=activity_options,
            table_options=table_options,
            synapse_client=synapse_client,
        )

    elif entity_type == concrete_types.SUBMISSION_VIEW:
        return await _handle_table_like_entity(
            entity_class=SubmissionView,
            synapse_id=synapse_id,
            version_number=version_number,
            activity_options=activity_options,
            table_options=table_options,
            synapse_client=synapse_client,
        )

    elif entity_type == concrete_types.VIRTUAL_TABLE:
        return await _handle_table_like_entity(
            entity_class=VirtualTable,
            synapse_id=synapse_id,
            version_number=version_number,
            activity_options=activity_options,
            table_options=table_options,
            synapse_client=synapse_client,
        )

    else:
        from synapseclient import Synapse

        client = Synapse.get_client(synapse_client=synapse_client)
        client.logger.warning(
            "Unknown entity type: %s. Falling back to returning %s as a dictionary bundle matching "
            "https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/entitybundle/v2/EntityBundle.html",
            entity_type,
            synapse_id,
        )

        # This allows the function to handle new entity types that may be added in the future
        if version_number is not None:
            return await get_entity_id_version_bundle2(
                entity_id=synapse_id,
                version=version_number,
                synapse_client=synapse_client,
            )
        else:
            return await get_entity_id_bundle2(
                entity_id=synapse_id, synapse_client=synapse_client
            )

synapseclient.operations.FileOptions dataclass

Configuration options specific to File entities when using the factory methods.

This dataclass allows you to customize how File entities are handled during retrieval, including download behavior, file location, and collision handling.

ATTRIBUTE DESCRIPTION
download_file

Whether to automatically download the file content when retrieving the File entity. If True, the file will be downloaded to the local filesystem. If False, only the metadata will be retrieved. Default is True.

TYPE: bool

download_location

The local directory path where the file should be downloaded. If None, the file will be downloaded to the default Synapse cache location. If specified, must be a valid directory path. Default is None.

TYPE: Optional[str]

if_collision

Strategy to use when a file with the same name already exists at the download location. Valid options are: - "keep.both": Keep both files by appending a number to the new file - "overwrite.local": Overwrite the existing local file - "keep.local": Keep the existing local file and skip download Default is "keep.both".

TYPE: str

Example

Configure file download options:

from synapseclient.operations import FileOptions

# Download file to specific location with overwrite
file_options = FileOptions(
    download_file=True,
    download_location="/path/to/downloads/",
    if_collision="overwrite.local"
)

# Only retrieve metadata, don't download file content
metadata_only = FileOptions(download_file=False)
Source code in synapseclient/operations/factory_operations.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
@dataclass
class FileOptions:
    """
    Configuration options specific to File entities when using the factory methods.

    This dataclass allows you to customize how File entities are handled during
    retrieval, including download behavior, file location, and collision handling.

    Attributes:
        download_file: Whether to automatically download the file content when
            retrieving the File entity. If True, the file will be downloaded to
            the local filesystem. If False, only the metadata will be retrieved.
            Default is True.
        download_location: The local directory path where the file should be
            downloaded. If None, the file will be downloaded to the default Synapse
            cache location. If specified,
            must be a valid directory path. Default is None.
        if_collision: Strategy to use when a file with the same name already
            exists at the download location. Valid options are:
            - "keep.both": Keep both files by appending a number to the new file
            - "overwrite.local": Overwrite the existing local file
            - "keep.local": Keep the existing local file and skip download
            Default is "keep.both".

    Example:
        Configure file download options:

        ```python
        from synapseclient.operations import FileOptions

        # Download file to specific location with overwrite
        file_options = FileOptions(
            download_file=True,
            download_location="/path/to/downloads/",
            if_collision="overwrite.local"
        )

        # Only retrieve metadata, don't download file content
        metadata_only = FileOptions(download_file=False)
        ```
    """

    download_file: bool = True
    download_location: Optional[str] = None
    if_collision: str = "keep.both"

synapseclient.operations.ActivityOptions dataclass

Configuration options for entities that support activity/provenance tracking.

This dataclass controls whether activity information (provenance data) should be included when retrieving entities. Activity information tracks the computational steps, data sources, and relationships that led to the creation of an entity.

ATTRIBUTE DESCRIPTION
include_activity

Whether to include activity/provenance information when retrieving the entity. If True, the returned entity will have its activity attribute populated with provenance data (if available). If False, the activity attribute will be None. Including activity may result in additional API calls and slower retrieval times. Default is False.

TYPE: bool

Example

Configure activity inclusion:

from synapseclient.operations import ActivityOptions

# Include activity information
with_activity = ActivityOptions(include_activity=True)

# Skip activity information (faster retrieval)
without_activity = ActivityOptions(include_activity=False)
Note

Activity information is only available for entities that support provenance tracking (File, Table, Dataset, etc...). For other entity types, this option is ignored.

Source code in synapseclient/operations/factory_operations.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
@dataclass
class ActivityOptions:
    """
    Configuration options for entities that support activity/provenance tracking.

    This dataclass controls whether activity information (provenance data) should
    be included when retrieving entities. Activity information tracks the computational
    steps, data sources, and relationships that led to the creation of an entity.

    Attributes:
        include_activity: Whether to include activity/provenance information when
            retrieving the entity. If True, the returned entity will have its
            activity attribute populated with provenance data (if available).
            If False, the activity attribute will be None. Including activity
            may result in additional API calls and slower retrieval times.
            Default is False.

    Example:
        Configure activity inclusion:

        ```python
        from synapseclient.operations import ActivityOptions

        # Include activity information
        with_activity = ActivityOptions(include_activity=True)

        # Skip activity information (faster retrieval)
        without_activity = ActivityOptions(include_activity=False)
        ```

    Note:
        Activity information is only available for entities that support provenance
        tracking (File, Table, Dataset, etc...). For other entity
        types, this option is ignored.
    """

    include_activity: bool = False

synapseclient.operations.TableOptions dataclass

Configuration options for table-like entities when using the factory methods.

This dataclass controls how table-like entities (Table, Dataset, EntityView, MaterializedView, SubmissionView, VirtualTable, and DatasetCollection) are retrieved, particularly whether column schema information should be included.

ATTRIBUTE DESCRIPTION
include_columns

Whether to include column schema information when retrieving table-like entities. If True, the returned entity will have its columns attribute populated with Column objects containing schema information (name, column_type, etc.). If False, the columns attribute will be an empty dict. Including columns may result in additional API calls but provides complete table structure information. Default is True.

TYPE: bool

Example

Configure table column inclusion:

from synapseclient.operations import TableOptions

# Include column schema information
with_columns = TableOptions(include_columns=True)

# Skip column information (faster retrieval)
without_columns = TableOptions(include_columns=False)
Source code in synapseclient/operations/factory_operations.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
@dataclass
class TableOptions:
    """
    Configuration options for table-like entities when using the factory methods.

    This dataclass controls how table-like entities (Table, Dataset, EntityView,
    MaterializedView, SubmissionView, VirtualTable, and DatasetCollection) are
    retrieved, particularly whether column schema information should be included.

    Attributes:
        include_columns: Whether to include column schema information when
            retrieving table-like entities. If True, the returned entity will
            have its columns attribute populated with Column objects containing
            schema information (name, column_type, etc.). If False, the columns
            attribute will be an empty dict. Including columns may result in
            additional API calls but provides complete table structure information.
            Default is True.

    Example:
        Configure table column inclusion:

        ```python
        from synapseclient.operations import TableOptions

        # Include column schema information
        with_columns = TableOptions(include_columns=True)

        # Skip column information (faster retrieval)
        without_columns = TableOptions(include_columns=False)
        ```
    """

    include_columns: bool = True

synapseclient.operations.LinkOptions dataclass

Configuration options specific to Link entities when using the factory methods.

This dataclass controls how Link entities are handled during retrieval, particularly whether the link should be followed to return the target entity or if the Link entity itself should be returned.

ATTRIBUTE DESCRIPTION
follow_link

Whether to follow the link and return the target entity instead of the Link entity itself. If True, the factory method will return the entity that the Link points to (e.g., if a Link points to a File, a File object will be returned). If False, the Link entity itself will be returned, allowing you to inspect the link's properties such as target_id, target_version, etc. Default is True.

TYPE: bool

Example

Configure link following behavior:

from synapseclient.operations import LinkOptions

# Follow the link and return the target entity
follow_target = LinkOptions(follow_link=True)

# Return the Link entity itself
return_link = LinkOptions(follow_link=False)
Note
  • When follow_link=True, the returned entity type depends on what the Link points to (could be File, Project, Folder, etc.)
  • When follow_link=False, a Link entity is always returned
Source code in synapseclient/operations/factory_operations.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
@dataclass
class LinkOptions:
    """
    Configuration options specific to Link entities when using the factory methods.

    This dataclass controls how Link entities are handled during retrieval,
    particularly whether the link should be followed to return the target entity
    or if the Link entity itself should be returned.

    Attributes:
        follow_link: Whether to follow the link and return the target entity
            instead of the Link entity itself. If True, the factory method will
            return the entity that the Link points to (e.g., if a Link points
            to a File, a File object will be returned). If False, the Link
            entity itself will be returned, allowing you to inspect the link's
            properties such as target_id, target_version, etc. Default is True.

    Example:
        Configure link following behavior:

        ```python
        from synapseclient.operations import LinkOptions

        # Follow the link and return the target entity
        follow_target = LinkOptions(follow_link=True)

        # Return the Link entity itself
        return_link = LinkOptions(follow_link=False)
        ```

    Note:
        - When follow_link=True, the returned entity type depends on what the
          Link points to (could be File, Project, Folder, etc.)
        - When follow_link=False, a Link entity is always returned
    """

    follow_link: bool = True

synapseclient.operations.delete_async async

delete_async(entity: Union[str, CurationTask, Dataset, DatasetCollection, EntityView, Evaluation, File, Folder, Grid, JSONSchema, MaterializedView, Project, RecordSet, SchemaOrganization, SubmissionView, Table, Team, VirtualTable], version: Optional[Union[int, str]] = None, version_only: bool = False, *, synapse_client: Optional[Synapse] = None) -> None

Factory method to delete any Synapse entity asynchronously.

This method serves as a unified interface for deleting any type of Synapse entity asynchronously. It automatically applies the appropriate delete logic based on the entity type.

Version Deletion Behavior

The function supports deleting specific versions of entities with the following precedence order:

  1. version parameter (highest priority): When provided, this version number will be used for deletion, overriding any version information from the entity object or the entity ID string.

  2. Entity's version_number attribute (secondary): If the entity object has a version_number attribute set and no explicit version parameter is provided, this version will be used.

  3. version_only parameter: When set to True, indicates that only a specific version should be deleted (not the entire entity). This parameter is only meaningful when combined with a version number from either the version parameter or the entity's version_number attribute.

Supported for version-specific deletion:

  • String ID with version (e.g., "syn123.4")
  • File, RecordSet (use version_only=True)
  • Table, Dataset, DatasetCollection, EntityView, MaterializedView, SubmissionView, VirtualTable (use version_only=True)

Not supported for version-specific deletion:

  • Project, Folder, Evaluation, Team, SchemaOrganization, CurationTask, Grid
PARAMETER DESCRIPTION
entity

The entity instance to delete, or a Synapse ID string (e.g., "syn123456" or "syn123456.4" for a specific version). Must be one of the supported entity types or a valid Synapse ID.

TYPE: Union[str, CurationTask, Dataset, DatasetCollection, EntityView, Evaluation, File, Folder, Grid, JSONSchema, MaterializedView, Project, RecordSet, SchemaOrganization, SubmissionView, Table, Team, VirtualTable]

version

Optional version number to delete. Takes precedence over any version information in the entity object or ID string. When provided with version_only=True, deletes only this specific version.

TYPE: Optional[Union[int, str]] DEFAULT: None

version_only

If True, only the specified version will be deleted, not the entire entity. Requires a version number from either the version parameter or the entity's version_number attribute. This parameter is applicable for entities that support version-specific deletion (File, RecordSet, Table, Dataset, DatasetCollection, EntityView, MaterializedView, SubmissionView, VirtualTable, JSONSchema).

TYPE: bool DEFAULT: False

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
None

None

RAISES DESCRIPTION
ValueError

If the entity is not a supported type or not a valid Synapse ID.

ValueError

If version_only is True but no version number is available.

Deleting a file by object

Delete a file from Synapse:

import asyncio
from synapseclient import Synapse
from synapseclient.models import File
from synapseclient.operations import delete_async

async def main():
    syn = Synapse()
    syn.login()

    file = File(id="syn123456")
    await delete_async(file)
    print("File deleted successfully")

asyncio.run(main())
Deleting a specific version of a file

Delete only version 2 of a file, keeping other versions:

import asyncio
from synapseclient import Synapse
from synapseclient.models import File
from synapseclient.operations import delete_async

async def main():
    syn = Synapse()
    syn.login()

    # Method 1: Using version parameter (highest priority)
    file = File(id="syn123456")
    await delete_async(file, version=2, version_only=True)

    # Method 2: Using entity's version_number attribute
    file = File(id="syn123456", version_number=2)
    await delete_async(file, version_only=True)

    # Method 3: Using synapse ID with version
    await delete_async("syn123456.2", version_only=True)
    print("File version 2 deleted successfully")

asyncio.run(main())
Deleting a file by ID string

Delete a file from Synapse using just its ID:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import delete_async

async def main():
    syn = Synapse()
    syn.login()

    await delete_async("syn123456")
    print("Entity deleted successfully")

asyncio.run(main())
Deleting a specific version of a RecordSet

Delete only a specific version of a RecordSet:

import asyncio
from synapseclient import Synapse
from synapseclient.models import RecordSet
from synapseclient.operations import delete_async

async def main():
    syn = Synapse()
    syn.login()

    record_set = RecordSet(id="syn123456", version_number=3)
    await delete_async(record_set, version_only=True)
    print("RecordSet version 3 deleted successfully")

asyncio.run(main())
Source code in synapseclient/operations/delete_operations.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
async def delete_async(
    entity: Union[
        str,
        "CurationTask",
        "Dataset",
        "DatasetCollection",
        "EntityView",
        "Evaluation",
        "File",
        "Folder",
        "Grid",
        "JSONSchema",
        "MaterializedView",
        "Project",
        "RecordSet",
        "SchemaOrganization",
        "SubmissionView",
        "Table",
        "Team",
        "VirtualTable",
    ],
    version: Optional[Union[int, str]] = None,
    version_only: bool = False,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> None:
    """
    Factory method to delete any Synapse entity asynchronously.

    This method serves as a unified interface for deleting any type of Synapse entity
    asynchronously. It automatically applies the appropriate delete logic based on the
    entity type.

    Version Deletion Behavior:
        The function supports deleting specific versions of entities with the following
        precedence order:

        1. **version parameter** (highest priority): When provided, this version number
           will be used for deletion, overriding any version information from the entity
           object or the entity ID string.

        2. **Entity's version_number attribute** (secondary): If the entity object has
           a `version_number` attribute set and no explicit `version` parameter is
           provided, this version will be used.

        3. **version_only parameter**: When set to True, indicates that only a specific
           version should be deleted (not the entire entity). This parameter is only
           meaningful when combined with a version number from either the `version`
           parameter or the entity's `version_number` attribute.

        **Supported for version-specific deletion:**

        - String ID with version (e.g., "syn123.4")
        - File, RecordSet (use version_only=True)
        - Table, Dataset, DatasetCollection, EntityView, MaterializedView,
          SubmissionView, VirtualTable (use version_only=True)

        **Not supported for version-specific deletion:**

        - Project, Folder, Evaluation, Team, SchemaOrganization, CurationTask, Grid

    Arguments:
        entity: The entity instance to delete, or a Synapse ID string (e.g., "syn123456"
            or "syn123456.4" for a specific version). Must be one of the supported
            entity types or a valid Synapse ID.
        version: Optional version number to delete. Takes precedence over any version
            information in the entity object or ID string. When provided with
            `version_only=True`, deletes only this specific version.
        version_only: If True, only the specified version will be deleted, not the
            entire entity. Requires a version number from either the `version` parameter
            or the entity's `version_number` attribute. This parameter is applicable for
            entities that support version-specific deletion (File, RecordSet, Table,
            Dataset, DatasetCollection, EntityView, MaterializedView, SubmissionView,
            VirtualTable, JSONSchema).
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        None

    Raises:
        ValueError: If the entity is not a supported type or not a valid Synapse ID.
        ValueError: If version_only is True but no version number is available.

    Example: Deleting a file by object
        Delete a file from Synapse:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File
        from synapseclient.operations import delete_async

        async def main():
            syn = Synapse()
            syn.login()

            file = File(id="syn123456")
            await delete_async(file)
            print("File deleted successfully")

        asyncio.run(main())
        ```

    Example: Deleting a specific version of a file
        Delete only version 2 of a file, keeping other versions:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File
        from synapseclient.operations import delete_async

        async def main():
            syn = Synapse()
            syn.login()

            # Method 1: Using version parameter (highest priority)
            file = File(id="syn123456")
            await delete_async(file, version=2, version_only=True)

            # Method 2: Using entity's version_number attribute
            file = File(id="syn123456", version_number=2)
            await delete_async(file, version_only=True)

            # Method 3: Using synapse ID with version
            await delete_async("syn123456.2", version_only=True)
            print("File version 2 deleted successfully")

        asyncio.run(main())
        ```

    Example: Deleting a file by ID string
        Delete a file from Synapse using just its ID:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import delete_async

        async def main():
            syn = Synapse()
            syn.login()

            await delete_async("syn123456")
            print("Entity deleted successfully")

        asyncio.run(main())
        ```

    Example: Deleting a specific version of a RecordSet
        Delete only a specific version of a RecordSet:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import RecordSet
        from synapseclient.operations import delete_async

        async def main():
            syn = Synapse()
            syn.login()

            record_set = RecordSet(id="syn123456", version_number=3)
            await delete_async(record_set, version_only=True)
            print("RecordSet version 3 deleted successfully")

        asyncio.run(main())
        ```
    """
    from synapseclient.models import (
        CurationTask,
        Dataset,
        DatasetCollection,
        EntityView,
        Evaluation,
        File,
        Folder,
        Grid,
        JSONSchema,
        MaterializedView,
        Project,
        RecordSet,
        SchemaOrganization,
        SubmissionView,
        Table,
        Team,
        VirtualTable,
    )

    # Handle string synapse ID
    if isinstance(entity, str):
        from synapseclient.core.utils import get_synid_and_version

        synapse_id = is_synapse_id_str(entity)
        if not synapse_id:
            raise ValueError(
                f"Invalid Synapse ID: {entity}. "
                "Expected a valid Synapse ID string (e.g., 'syn123456' or 'syn123456.4')."
            )

        # Check if version is embedded in the string ID (e.g., "syn123.4")
        syn_id, syn_version = get_synid_and_version(synapse_id)

        # Determine final version: explicit version parameter takes precedence
        final_version = version if version is not None else syn_version

        # If there's a version to delete, require version_only=True for safety
        if final_version is not None and not version_only:
            raise ValueError(
                f"Deleting a specific version requires version_only=True. "
                f"Use delete('{entity}', version_only=True) to delete version {final_version}."
            )

        await delete_entity(
            entity_id=syn_id,
            version_number=final_version,
            synapse_client=synapse_client,
        )
        return None

    # Determine final version to use based on precedence
    final_version_for_entity = version
    entity_version = None

    # Check if entity has version_number attribute
    if hasattr(entity, "version_number"):
        entity_version = getattr(entity, "version_number", None)
        if final_version_for_entity is None and entity_version is not None:
            final_version_for_entity = entity_version

    # Emit warning only when there's an actual version conflict (both are set and different)
    if (
        version_only
        and version is not None
        and entity_version is not None
        and version != entity_version
    ):
        from synapseclient import Synapse

        client = Synapse.get_client(synapse_client=synapse_client)
        client.logger.warning(
            f"Version conflict: 'version' parameter ({version}) differs from "
            f"entity's 'version_number' attribute ({entity_version}). "
            "Using 'version' parameter as it takes precedence."
        )

    # Handle entities that support version-specific deletion with version_only parameter
    if isinstance(entity, (File, RecordSet)):
        # Validate that if version_only is True, we have a version number
        if version_only and final_version_for_entity is None:
            raise ValueError(
                "version_only=True requires a version number. "
                "Provide either 'version' parameter or set 'version_number' on the entity."
            )

        # Only pass version_only=True when we actually have a version to delete
        if version_only and final_version_for_entity is not None:
            # Set the entity's version_number to the final version so delete_async uses it
            entity.version_number = final_version_for_entity
            return await entity.delete_async(
                version_only=True, synapse_client=synapse_client
            )
        else:
            return await entity.delete_async(
                version_only=False, synapse_client=synapse_client
            )

    # Handle table-like entities that support version deletion through the API
    elif isinstance(
        entity,
        (
            Table,
            Dataset,
            DatasetCollection,
            EntityView,
            MaterializedView,
            SubmissionView,
            VirtualTable,
        ),
    ):
        # Validate that if version_only is True, we have a version number
        if version_only and final_version_for_entity is None:
            raise ValueError(
                "version_only=True requires a version number. "
                "Provide either 'version' parameter or set 'version_number' on the entity."
            )

        # Only use version-specific deletion when version_only=True AND we have a version
        if version_only and final_version_for_entity is not None:
            # These entities support version deletion through the API
            return await delete_entity(
                entity_id=entity.id,
                version_number=final_version_for_entity,
                synapse_client=synapse_client,
            )
        else:
            # Delete entire entity (DeleteMixin will strip any version from entity.id)
            return await entity.delete_async(synapse_client=synapse_client)

    # Handle entities without version support
    elif isinstance(
        entity,
        (
            Folder,
            Project,
            Evaluation,
            Team,
            SchemaOrganization,
            CurationTask,
            Grid,
        ),
    ):
        if version_only or final_version_for_entity is not None:
            from synapseclient import Synapse

            client = Synapse.get_client(synapse_client=synapse_client)
            client.logger.warning(
                f"{type(entity).__name__} does not support version-specific deletion. "
                "The entire entity will be deleted."
            )
        return await entity.delete_async(synapse_client=synapse_client)

    # JSONSchema supports version parameter
    elif isinstance(entity, JSONSchema):
        if final_version_for_entity is not None:
            return await entity.delete_async(
                version=str(final_version_for_entity), synapse_client=synapse_client
            )
        else:
            return await entity.delete_async(synapse_client=synapse_client)

    else:
        raise ValueError(
            f"Unsupported entity type: {type(entity).__name__}. "
            "Supported types are: str (Synapse ID), CurationTask, Dataset, DatasetCollection, "
            "EntityView, Evaluation, File, Folder, Grid, JSONSchema, MaterializedView, "
            "Project, RecordSet, SchemaOrganization, SubmissionView, Table, Team, VirtualTable."
        )

synapseclient.operations.store_async async

Factory method to store any Synapse entity asynchronously.

This method serves as a unified interface for storing any type of Synapse entity asynchronously. It automatically applies the appropriate store logic based on the entity type and the options provided.

PARAMETER DESCRIPTION
entity

The entity instance to store. Must be one of the supported entity types.

TYPE: Union[AgentSession, CurationTask, Dataset, DatasetCollection, EntityView, Evaluation, File, Folder, FormData, FormGroup, Grid, JSONSchema, Link, MaterializedView, Project, RecordSet, SchemaOrganization, SubmissionView, Table, Team, VirtualTable]

parent

The parent folder or project to store the entity in. Only applicable for File, Folder, Link, and RecordSet entities. Ignored for other entity types.

TYPE: Optional[Union[Folder, Project]] DEFAULT: None

file_options

File-specific configuration options. Only applies to File and RecordSet entities. Ignored for other entity types.

TYPE: Optional[StoreFileOptions] DEFAULT: None

container_options

Container-specific configuration options. Only applies to Project and Folder entities. Ignored for other entity types.

TYPE: Optional[StoreContainerOptions] DEFAULT: None

table_options

Table-specific configuration options. Only applies to Table-like entities (Table, Dataset, EntityView, MaterializedView, SubmissionView, VirtualTable, DatasetCollection). Ignored for other entity types.

TYPE: Optional[StoreTableOptions] DEFAULT: None

json_schema_options

JSONSchema-specific configuration options. Only applies to JSONSchema entities. Required for JSONSchema. Ignored for other entity types.

TYPE: Optional[StoreJSONSchemaOptions] DEFAULT: None

grid_options

Grid-specific configuration options. Only applies to Grid entities. Ignored for other entity types.

TYPE: Optional[StoreGridOptions] DEFAULT: None

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
Union[AgentSession, CurationTask, Dataset, DatasetCollection, EntityView, Evaluation, File, Folder, FormData, FormGroup, Grid, JSONSchema, Link, MaterializedView, Project, RecordSet, SchemaOrganization, SubmissionView, Table, Team, VirtualTable]

The stored Synapse entity model instance.

RAISES DESCRIPTION
ValueError

If the entity is not a supported type.

Storing a file

Store a file to Synapse:

import asyncio
from synapseclient import Synapse
from synapseclient.models import File
from synapseclient.operations import store_async

async def main():
    syn = Synapse()
    syn.login()

    file = File(path="/path/to/file.txt", parent_id="syn123456")
    stored_file = await store_async(file)
    print(f"Stored file: {stored_file.name} (ID: {stored_file.id})")

asyncio.run(main())
Storing a file with custom options

Store a file with custom options:

import asyncio
from synapseclient import Synapse
from synapseclient.models import File
from synapseclient.operations import store_async, StoreFileOptions

async def main():
    syn = Synapse()
    syn.login()

    file = File(path="/path/to/file.txt", parent_id="syn123456")
    stored_file = await store_async(
        file,
        file_options=StoreFileOptions(
            synapse_store=True,
            content_type="text/plain",
            merge_existing_annotations=True
        )
    )
    print(f"Stored file: {stored_file.name}")

asyncio.run(main())
Storing a folder

Store a folder to Synapse:

import asyncio
from synapseclient import Synapse
from synapseclient.models import Folder
from synapseclient.operations import store_async

async def main():
    syn = Synapse()
    syn.login()

    folder = Folder(name="My Folder", parent_id="syn123456")
    stored_folder = await store_async(folder)
    print(f"Stored folder: {stored_folder.name} (ID: {stored_folder.id})")

asyncio.run(main())
Storing a project

Store a project to Synapse:

import asyncio
from synapseclient import Synapse
from synapseclient.models import Project
from synapseclient.operations import store_async

async def main():
    syn = Synapse()
    syn.login()

    project = Project(name="My Project")
    stored_project = await store_async(project)
    print(f"Stored project: {stored_project.name} (ID: {stored_project.id})")

asyncio.run(main())
Storing a table

Store a table to Synapse:

import asyncio
from synapseclient import Synapse
from synapseclient.models import Table, Column, ColumnType
from synapseclient.operations import store_async, StoreTableOptions

async def main():
    syn = Synapse()
    syn.login()

    table = Table(
        name="My Table",
        parent_id="syn123456",
        columns=[Column(name="col1", column_type=ColumnType.STRING, maximum_size=50)]
    )
    stored_table = await store_async(
        table,
        table_options=StoreTableOptions(dry_run=False, job_timeout=600)
    )
    print(f"Stored table: {stored_table.name} (ID: {stored_table.id})")

asyncio.run(main())
Storing a link

Store a link to Synapse:

import asyncio
from synapseclient import Synapse
from synapseclient.models import Link
from synapseclient.operations import store_async

async def main():
    syn = Synapse()
    syn.login()

    link = Link(name="My Link", parent_id="syn123456", target_id="syn789")
    stored_link = await store_async(link)
    print(f"Stored link: {stored_link.name} (ID: {stored_link.id})")

asyncio.run(main())
Storing with parent parameter

Store an entity by passing the parent as a parameter:

import asyncio
from synapseclient import Synapse
from synapseclient.models import File, Folder
from synapseclient.operations import store_async

async def main():
    syn = Synapse()
    syn.login()

    parent_folder = Folder(id="syn123456")
    file = File(path="/path/to/file.txt")
    stored_file = await store_async(file, parent=parent_folder)
    print(f"Stored file: {stored_file.name} in folder {parent_folder.id}")

asyncio.run(main())
Source code in synapseclient/operations/store_operations.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
async def store_async(
    entity: Union[
        "AgentSession",
        "CurationTask",
        "Dataset",
        "DatasetCollection",
        "EntityView",
        "Evaluation",
        "File",
        "Folder",
        "FormData",
        "FormGroup",
        "Grid",
        "JSONSchema",
        "Link",
        "MaterializedView",
        "Project",
        "RecordSet",
        "SchemaOrganization",
        "SubmissionView",
        "Table",
        "Team",
        "VirtualTable",
    ],
    parent: Optional[Union["Folder", "Project"]] = None,
    *,
    file_options: Optional[StoreFileOptions] = None,
    container_options: Optional[StoreContainerOptions] = None,
    table_options: Optional[StoreTableOptions] = None,
    json_schema_options: Optional[StoreJSONSchemaOptions] = None,
    grid_options: Optional[StoreGridOptions] = None,
    synapse_client: Optional["Synapse"] = None,
) -> Union[
    "AgentSession",
    "CurationTask",
    "Dataset",
    "DatasetCollection",
    "EntityView",
    "Evaluation",
    "File",
    "Folder",
    "FormData",
    "FormGroup",
    "Grid",
    "JSONSchema",
    "Link",
    "MaterializedView",
    "Project",
    "RecordSet",
    "SchemaOrganization",
    "SubmissionView",
    "Table",
    "Team",
    "VirtualTable",
]:
    """
    Factory method to store any Synapse entity asynchronously.

    This method serves as a unified interface for storing any type of Synapse entity
    asynchronously. It automatically applies the appropriate store logic based on the
    entity type and the options provided.

    Arguments:
        entity: The entity instance to store. Must be one of the supported entity types.
        parent: The parent folder or project to store the entity in. Only applicable
            for File, Folder, Link, and RecordSet entities. Ignored for other entity types.
        file_options: File-specific configuration options. Only applies to File and
            RecordSet entities. Ignored for other entity types.
        container_options: Container-specific configuration options. Only applies to
            Project and Folder entities. Ignored for other entity types.
        table_options: Table-specific configuration options. Only applies to Table-like
            entities (Table, Dataset, EntityView, MaterializedView, SubmissionView,
            VirtualTable, DatasetCollection). Ignored for other entity types.
        json_schema_options: JSONSchema-specific configuration options. Only applies to
            JSONSchema entities. Required for JSONSchema. Ignored for other entity types.
        grid_options: Grid-specific configuration options. Only applies to Grid entities.
            Ignored for other entity types.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        The stored Synapse entity model instance.

    Raises:
        ValueError: If the entity is not a supported type.

    Example: Storing a file
        Store a file to Synapse:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File
        from synapseclient.operations import store_async

        async def main():
            syn = Synapse()
            syn.login()

            file = File(path="/path/to/file.txt", parent_id="syn123456")
            stored_file = await store_async(file)
            print(f"Stored file: {stored_file.name} (ID: {stored_file.id})")

        asyncio.run(main())
        ```

    Example: Storing a file with custom options
        Store a file with custom options:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File
        from synapseclient.operations import store_async, StoreFileOptions

        async def main():
            syn = Synapse()
            syn.login()

            file = File(path="/path/to/file.txt", parent_id="syn123456")
            stored_file = await store_async(
                file,
                file_options=StoreFileOptions(
                    synapse_store=True,
                    content_type="text/plain",
                    merge_existing_annotations=True
                )
            )
            print(f"Stored file: {stored_file.name}")

        asyncio.run(main())
        ```

    Example: Storing a folder
        Store a folder to Synapse:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import Folder
        from synapseclient.operations import store_async

        async def main():
            syn = Synapse()
            syn.login()

            folder = Folder(name="My Folder", parent_id="syn123456")
            stored_folder = await store_async(folder)
            print(f"Stored folder: {stored_folder.name} (ID: {stored_folder.id})")

        asyncio.run(main())
        ```

    Example: Storing a project
        Store a project to Synapse:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import Project
        from synapseclient.operations import store_async

        async def main():
            syn = Synapse()
            syn.login()

            project = Project(name="My Project")
            stored_project = await store_async(project)
            print(f"Stored project: {stored_project.name} (ID: {stored_project.id})")

        asyncio.run(main())
        ```

    Example: Storing a table
        Store a table to Synapse:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import Table, Column, ColumnType
        from synapseclient.operations import store_async, StoreTableOptions

        async def main():
            syn = Synapse()
            syn.login()

            table = Table(
                name="My Table",
                parent_id="syn123456",
                columns=[Column(name="col1", column_type=ColumnType.STRING, maximum_size=50)]
            )
            stored_table = await store_async(
                table,
                table_options=StoreTableOptions(dry_run=False, job_timeout=600)
            )
            print(f"Stored table: {stored_table.name} (ID: {stored_table.id})")

        asyncio.run(main())
        ```

    Example: Storing a link
        Store a link to Synapse:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import Link
        from synapseclient.operations import store_async

        async def main():
            syn = Synapse()
            syn.login()

            link = Link(name="My Link", parent_id="syn123456", target_id="syn789")
            stored_link = await store_async(link)
            print(f"Stored link: {stored_link.name} (ID: {stored_link.id})")

        asyncio.run(main())
        ```

    Example: Storing with parent parameter
        Store an entity by passing the parent as a parameter:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File, Folder
        from synapseclient.operations import store_async

        async def main():
            syn = Synapse()
            syn.login()

            parent_folder = Folder(id="syn123456")
            file = File(path="/path/to/file.txt")
            stored_file = await store_async(file, parent=parent_folder)
            print(f"Stored file: {stored_file.name} in folder {parent_folder.id}")

        asyncio.run(main())
        ```
    """
    from synapseclient.models import (
        AgentSession,
        CurationTask,
        Dataset,
        DatasetCollection,
        EntityView,
        Evaluation,
        File,
        Folder,
        FormData,
        FormGroup,
        Grid,
        JSONSchema,
        Link,
        MaterializedView,
        Project,
        RecordSet,
        SchemaOrganization,
        SubmissionView,
        Table,
        Team,
        VirtualTable,
    )

    # Determine entity type and route to appropriate handler
    if isinstance(entity, (File, RecordSet)):
        return await _handle_store_file_entity(
            entity=entity,
            parent=parent,
            file_options=file_options,
            synapse_client=synapse_client,
        )

    elif isinstance(entity, (Project, Folder)):
        return await _handle_store_container_entity(
            entity=entity,
            parent=parent,
            container_options=container_options,
            synapse_client=synapse_client,
        )

    elif isinstance(
        entity,
        (
            Dataset,
            DatasetCollection,
            EntityView,
            MaterializedView,
            SubmissionView,
            Table,
            VirtualTable,
        ),
    ):
        return await _handle_store_table_entity(
            entity=entity,
            table_options=table_options,
            synapse_client=synapse_client,
        )

    elif isinstance(entity, Link):
        return await _handle_store_link_entity(
            entity=entity,
            parent=parent,
            synapse_client=synapse_client,
        )

    elif isinstance(entity, Evaluation):
        return await entity.store_async(synapse_client=synapse_client)

    elif isinstance(entity, Team):
        if entity.id:
            return await entity.store_async(synapse_client=synapse_client)
        else:
            return await entity.create_async(synapse_client=synapse_client)

    elif isinstance(entity, SchemaOrganization):
        return await entity.store_async(synapse_client=synapse_client)

    elif isinstance(entity, CurationTask):
        return await entity.store_async(synapse_client=synapse_client)

    elif isinstance(entity, AgentSession):
        return await entity.update_async(synapse_client=synapse_client)

    elif isinstance(entity, (FormGroup, FormData)):
        return await entity.create_or_get_async(synapse_client=synapse_client)

    elif isinstance(entity, JSONSchema):
        if not json_schema_options or not json_schema_options.schema_body:
            raise ValueError(
                "json_schema_options with schema_body is required for JSONSchema entities"
            )
        return await _handle_store_json_schema_entity(
            entity=entity,
            schema_body=json_schema_options.schema_body,
            version=json_schema_options.version,
            dry_run=json_schema_options.dry_run,
            synapse_client=synapse_client,
        )

    elif isinstance(entity, Grid):
        attach_to_previous = (
            grid_options.attach_to_previous_session if grid_options else False
        )
        timeout = grid_options.timeout if grid_options else 120
        return await entity.create_async(
            attach_to_previous_session=attach_to_previous,
            timeout=timeout,
            synapse_client=synapse_client,
        )

    else:
        raise ValueError(
            f"Unsupported entity type: {type(entity).__name__}. "
            "Supported types are: AgentSession, CurationTask, "
            "Dataset, DatasetCollection, EntityView, Evaluation, File, Folder, FormData, "
            "FormGroup, Grid, JSONSchema, Link, MaterializedView, Project, RecordSet, "
            "SchemaOrganization, SubmissionView, Table, Team, VirtualTable."
        )

synapseclient.operations.StoreFileOptions dataclass

Options for storing File entities.

ATTRIBUTE DESCRIPTION
synapse_store

Whether to store the file in Synapse or use an external URL.

TYPE: Optional[bool]

content_type

The content type of the file.

TYPE: Optional[str]

merge_existing_annotations

If True, merge existing annotations with new ones. If False, replace all annotations.

TYPE: Optional[bool]

associate_activity_to_new_version

If True, associate activity with new version. If False, do not associate activity.

TYPE: Optional[bool]

Source code in synapseclient/operations/store_operations.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@dataclass
class StoreFileOptions:
    """Options for storing File entities.

    Attributes:
        synapse_store: Whether to store the file in Synapse or use an external URL.
        content_type: The content type of the file.
        merge_existing_annotations: If True, merge existing annotations with new ones.
            If False, replace all annotations.
        associate_activity_to_new_version: If True, associate activity with new version.
            If False, do not associate activity.
    """

    synapse_store: Optional[bool] = None
    content_type: Optional[str] = None
    merge_existing_annotations: Optional[bool] = None
    associate_activity_to_new_version: Optional[bool] = None

synapseclient.operations.StoreContainerOptions dataclass

Options for storing container entities (Project, Folder).

ATTRIBUTE DESCRIPTION
failure_strategy

Strategy for handling failures when storing child entities. Can be either a FailureStrategy enum value or a string. Valid string values: "LOG_EXCEPTION", "RAISE_EXCEPTION". Valid enum values: FailureStrategy.LOG_EXCEPTION, FailureStrategy.RAISE_EXCEPTION.

TYPE: Optional[Union[str, FailureStrategy]]

Source code in synapseclient/operations/store_operations.py
55
56
57
58
59
60
61
62
63
64
65
66
@dataclass
class StoreContainerOptions:
    """Options for storing container entities (Project, Folder).

    Attributes:
        failure_strategy: Strategy for handling failures when storing child entities.
            Can be either a FailureStrategy enum value or a string.
            Valid string values: "LOG_EXCEPTION", "RAISE_EXCEPTION".
            Valid enum values: FailureStrategy.LOG_EXCEPTION, FailureStrategy.RAISE_EXCEPTION.
    """

    failure_strategy: Optional[Union[str, FailureStrategy]] = None

synapseclient.operations.StoreTableOptions dataclass

Options for storing Table-like entities.

ATTRIBUTE DESCRIPTION
dry_run

If True, will not actually store but will log what would be done.

TYPE: bool

job_timeout

Maximum time to wait for table schema update job to complete.

TYPE: int

Source code in synapseclient/operations/store_operations.py
69
70
71
72
73
74
75
76
77
78
79
@dataclass
class StoreTableOptions:
    """Options for storing Table-like entities.

    Attributes:
        dry_run: If True, will not actually store but will log what would be done.
        job_timeout: Maximum time to wait for table schema update job to complete.
    """

    dry_run: bool = False
    job_timeout: int = 600

synapseclient.operations.StoreJSONSchemaOptions dataclass

Options for storing JSONSchema entities.

ATTRIBUTE DESCRIPTION
schema_body

The body of the JSONSchema to store.

TYPE: dict

version

The version of the JSONSchema body to store.

TYPE: Optional[str]

dry_run

Whether or not to do a dry-run.

TYPE: bool

Source code in synapseclient/operations/store_operations.py
82
83
84
85
86
87
88
89
90
91
92
93
94
@dataclass
class StoreJSONSchemaOptions:
    """Options for storing JSONSchema entities.

    Attributes:
        schema_body: The body of the JSONSchema to store.
        version: The version of the JSONSchema body to store.
        dry_run: Whether or not to do a dry-run.
    """

    schema_body: dict
    version: Optional[str] = None
    dry_run: bool = False

synapseclient.operations.StoreGridOptions dataclass

Options for storing Grid entities.

ATTRIBUTE DESCRIPTION
attach_to_previous_session

If True and using record_set_id, will attach to an existing active session if one exists.

TYPE: bool

timeout

The number of seconds to wait for the job to complete.

TYPE: int

Source code in synapseclient/operations/store_operations.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
@dataclass
class StoreGridOptions:
    """Options for storing Grid entities.

    Attributes:
        attach_to_previous_session: If True and using record_set_id, will attach
            to an existing active session if one exists.
        timeout: The number of seconds to wait for the job to complete.
    """

    attach_to_previous_session: bool = False
    timeout: int = 120

synapseclient.operations.find_entity_id_async async

find_entity_id_async(name: str, parent: Optional[Union[str, Dataset, DatasetCollection, EntityView, File, Folder, Link, MaterializedView, Project, RecordSet, SubmissionView, Table, VirtualTable]] = None, *, synapse_client: Optional[Synapse] = None) -> Optional[str]

Find an Entity given its name and parent asynchronously.

PARAMETER DESCRIPTION
name

Name of the entity to find.

TYPE: str

parent

An Entity object (Dataset, DatasetCollection, EntityView, File, Folder, Link, MaterializedView, Project, RecordSet, SubmissionView, Table, VirtualTable) or the Id of an entity as a string. Omit if searching for a Project by name.

TYPE: Optional[Union[str, Dataset, DatasetCollection, EntityView, File, Folder, Link, MaterializedView, Project, RecordSet, SubmissionView, Table, VirtualTable]] DEFAULT: None

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
Optional[str]

The Entity ID or None if not found.

Finding a project by name

Find a project using only its name:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import find_entity_id_async

async def main():
    syn = Synapse()
    syn.login()

    project_id = await find_entity_id_async(name="My Project")
    if project_id:
        print(f"Found project: {project_id}")
    else:
        print("Project not found")

asyncio.run(main())
Finding an entity within a parent

Find a file within a specific folder:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import find_entity_id_async

async def main():
    syn = Synapse()
    syn.login()

    file_id = await find_entity_id_async(
        name="my_data.csv",
        parent="syn123456"  # Parent folder ID
    )
    if file_id:
        print(f"Found file: {file_id}")
    else:
        print("File not found in folder")

asyncio.run(main())
Source code in synapseclient/operations/utility_operations.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
async def find_entity_id_async(
    name: str,
    parent: Optional[
        Union[
            str,
            "Dataset",
            "DatasetCollection",
            "EntityView",
            "File",
            "Folder",
            "Link",
            "MaterializedView",
            "Project",
            "RecordSet",
            "SubmissionView",
            "Table",
            "VirtualTable",
        ]
    ] = None,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> Optional[str]:
    """
    Find an Entity given its name and parent asynchronously.

    Arguments:
        name: Name of the entity to find.
        parent: An Entity object (Dataset, DatasetCollection, EntityView, File,
            Folder, Link, MaterializedView, Project, RecordSet, SubmissionView,
            Table, VirtualTable) or the Id of an entity as a string. Omit if
            searching for a Project by name.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        The Entity ID or None if not found.

    Example: Finding a project by name
        Find a project using only its name:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import find_entity_id_async

        async def main():
            syn = Synapse()
            syn.login()

            project_id = await find_entity_id_async(name="My Project")
            if project_id:
                print(f"Found project: {project_id}")
            else:
                print("Project not found")

        asyncio.run(main())
        ```

    Example: Finding an entity within a parent
        Find a file within a specific folder:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import find_entity_id_async

        async def main():
            syn = Synapse()
            syn.login()

            file_id = await find_entity_id_async(
                name="my_data.csv",
                parent="syn123456"  # Parent folder ID
            )
            if file_id:
                print(f"Found file: {file_id}")
            else:
                print("File not found in folder")

        asyncio.run(main())
        ```
    """
    from synapseclient.api import get_child
    from synapseclient.core.utils import id_of

    parent_id = id_of(parent) if parent else None
    return await get_child(
        entity_name=name,
        parent_id=parent_id,
        synapse_client=synapse_client,
    )

synapseclient.operations.is_synapse_id_async async

is_synapse_id_async(syn_id: str, *, synapse_client: Optional[Synapse] = None) -> bool

Check if given synID is valid (attached to actual entity) asynchronously.

PARAMETER DESCRIPTION
syn_id

A Synapse ID to validate.

TYPE: str

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
bool

True if the Synapse ID is valid.

Validating a Synapse ID

Check if a Synapse ID exists:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import is_synapse_id_async

async def main():
    syn = Synapse()
    syn.login()

    if await is_synapse_id_async("syn123456"):
        print("Valid Synapse ID")
    else:
        print("Invalid or non-existent Synapse ID")

asyncio.run(main())
Validating multiple IDs concurrently

Check multiple Synapse IDs concurrently:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import is_synapse_id_async

async def main():
    syn = Synapse()
    syn.login()

    ids_to_check = ["syn123456", "syn999999", "syn789012"]
    results = await asyncio.gather(
        *[is_synapse_id_async(synapse_id) for synapse_id in ids_to_check]
    )
    for synapse_id, is_valid in zip(ids_to_check, results):
        if is_valid:
            print(f"{synapse_id} is valid")
        else:
            print(f"{synapse_id} is invalid or does not exist")

asyncio.run(main())
Source code in synapseclient/operations/utility_operations.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
async def is_synapse_id_async(
    syn_id: str,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> bool:
    """
    Check if given synID is valid (attached to actual entity) asynchronously.

    Arguments:
        syn_id: A Synapse ID to validate.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        True if the Synapse ID is valid.

    Example: Validating a Synapse ID
        Check if a Synapse ID exists:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import is_synapse_id_async

        async def main():
            syn = Synapse()
            syn.login()

            if await is_synapse_id_async("syn123456"):
                print("Valid Synapse ID")
            else:
                print("Invalid or non-existent Synapse ID")

        asyncio.run(main())
        ```

    Example: Validating multiple IDs concurrently
        Check multiple Synapse IDs concurrently:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import is_synapse_id_async

        async def main():
            syn = Synapse()
            syn.login()

            ids_to_check = ["syn123456", "syn999999", "syn789012"]
            results = await asyncio.gather(
                *[is_synapse_id_async(synapse_id) for synapse_id in ids_to_check]
            )
            for synapse_id, is_valid in zip(ids_to_check, results):
                if is_valid:
                    print(f"{synapse_id} is valid")
                else:
                    print(f"{synapse_id} is invalid or does not exist")

        asyncio.run(main())
        ```
    """
    from synapseclient.api.entity_services import is_synapse_id as api_is_synapse_id

    return await api_is_synapse_id(
        syn_id=syn_id,
        synapse_client=synapse_client,
    )

synapseclient.operations.onweb_async async

onweb_async(entity: Union[str, Dataset, DatasetCollection, EntityView, File, Folder, Link, MaterializedView, Project, RecordSet, SubmissionView, Table, VirtualTable], subpage_id: Optional[str] = None, *, synapse_client: Optional[Synapse] = None) -> str

Open up a browser window to the entity page or wiki-subpage asynchronously.

PARAMETER DESCRIPTION
entity

Either an Entity object (Dataset, DatasetCollection, EntityView, File, Folder, Link, MaterializedView, Project, RecordSet, SubmissionView, Table, VirtualTable) or a Synapse ID string.

TYPE: Union[str, Dataset, DatasetCollection, EntityView, File, Folder, Link, MaterializedView, Project, RecordSet, SubmissionView, Table, VirtualTable]

subpage_id

(Optional) ID of one of the wiki's sub-pages.

TYPE: Optional[str] DEFAULT: None

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
str

The URL that was opened in the browser.

Opening an entity in browser

Open an entity's page in the default web browser:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import onweb_async

async def main():
    syn = Synapse()
    syn.login()

    # Open by Synapse ID
    url = await onweb_async("syn123456")
    print(f"Opened: {url}")

asyncio.run(main())
Opening with an entity object

Open an entity using an entity object:

import asyncio
from synapseclient import Synapse
from synapseclient.models import File
from synapseclient.operations import onweb_async, get_async

async def main():
    syn = Synapse()
    syn.login()

    file = await get_async(synapse_id="syn123456")
    url = await onweb_async(file)
    print(f"Opened file: {url}")

asyncio.run(main())
Source code in synapseclient/operations/utility_operations.py
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
async def onweb_async(
    entity: Union[
        str,
        "Dataset",
        "DatasetCollection",
        "EntityView",
        "File",
        "Folder",
        "Link",
        "MaterializedView",
        "Project",
        "RecordSet",
        "SubmissionView",
        "Table",
        "VirtualTable",
    ],
    subpage_id: Optional[str] = None,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> str:
    """
    Open up a browser window to the entity page or wiki-subpage asynchronously.

    Arguments:
        entity: Either an Entity object (Dataset, DatasetCollection, EntityView,
            File, Folder, Link, MaterializedView, Project, RecordSet,
            SubmissionView, Table, VirtualTable) or a Synapse ID string.
        subpage_id: (Optional) ID of one of the wiki's sub-pages.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        The URL that was opened in the browser.

    Example: Opening an entity in browser
        Open an entity's page in the default web browser:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import onweb_async

        async def main():
            syn = Synapse()
            syn.login()

            # Open by Synapse ID
            url = await onweb_async("syn123456")
            print(f"Opened: {url}")

        asyncio.run(main())
        ```

    Example: Opening with an entity object
        Open an entity using an entity object:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import File
        from synapseclient.operations import onweb_async, get_async

        async def main():
            syn = Synapse()
            syn.login()

            file = await get_async(synapse_id="syn123456")
            url = await onweb_async(file)
            print(f"Opened file: {url}")

        asyncio.run(main())
        ```
    """
    from synapseclient.api.web_services import open_entity_in_browser

    return await open_entity_in_browser(
        entity=entity,
        subpage_id=subpage_id,
        synapse_client=synapse_client,
    )

synapseclient.operations.md5_query_async async

md5_query_async(md5: str, *, synapse_client: Optional[Synapse] = None) -> List[dict]

Find the Entities which have attached file(s) which have the given MD5 hash asynchronously.

PARAMETER DESCRIPTION
md5

The MD5 hash to query for (hexadecimal string).

TYPE: str

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
List[dict]

A list of Entity headers matching the MD5 hash.

Finding entities by MD5 hash

Search for entities with a specific MD5 hash:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import md5_query_async

async def main():
    syn = Synapse()
    syn.login()

    md5_hash = "1234567890abcdef1234567890abcdef"
    results = await md5_query_async(md5_hash)

    print(f"Found {len(results)} entities with MD5: {md5_hash}")
    for entity in results:
        print(f"- {entity['id']}: {entity['name']}")

asyncio.run(main())
Checking multiple MD5 hashes concurrently

Query multiple MD5 hashes at the same time:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import md5_query_async

async def main():
    syn = Synapse()
    syn.login()

    md5_hashes = [
        "1234567890abcdef1234567890abcdef",
        "abcdef1234567890abcdef1234567890",
        "567890abcdef1234567890abcdef1234"
    ]

    # Query all MD5 hashes concurrently
    results = await asyncio.gather(
        *[md5_query_async(md5) for md5 in md5_hashes]
    )

    for md5, entities in zip(md5_hashes, results):
        print(f"MD5 {md5}: {len(entities)} matching entities")

asyncio.run(main())
Source code in synapseclient/operations/utility_operations.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
async def md5_query_async(
    md5: str,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> List[dict]:
    """
    Find the Entities which have attached file(s) which have the given MD5 hash asynchronously.

    Arguments:
        md5: The MD5 hash to query for (hexadecimal string).
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        A list of Entity headers matching the MD5 hash.

    Example: Finding entities by MD5 hash
        Search for entities with a specific MD5 hash:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import md5_query_async

        async def main():
            syn = Synapse()
            syn.login()

            md5_hash = "1234567890abcdef1234567890abcdef"
            results = await md5_query_async(md5_hash)

            print(f"Found {len(results)} entities with MD5: {md5_hash}")
            for entity in results:
                print(f"- {entity['id']}: {entity['name']}")

        asyncio.run(main())
        ```

    Example: Checking multiple MD5 hashes concurrently
        Query multiple MD5 hashes at the same time:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import md5_query_async

        async def main():
            syn = Synapse()
            syn.login()

            md5_hashes = [
                "1234567890abcdef1234567890abcdef",
                "abcdef1234567890abcdef1234567890",
                "567890abcdef1234567890abcdef1234"
            ]

            # Query all MD5 hashes concurrently
            results = await asyncio.gather(
                *[md5_query_async(md5) for md5 in md5_hashes]
            )

            for md5, entities in zip(md5_hashes, results):
                print(f"MD5 {md5}: {len(entities)} matching entities")

        asyncio.run(main())
        ```
    """
    from synapseclient.api import get_entities_by_md5

    response = await get_entities_by_md5(
        md5=md5,
        synapse_client=synapse_client,
    )
    return response.get("results", [])

synapseclient.operations.print_entity_async async

print_entity_async(entity: Union[str, dict, Dataset, DatasetCollection, EntityView, File, Folder, Link, MaterializedView, Project, RecordSet, SubmissionView, Table, VirtualTable], ensure_ascii: bool = True, *, synapse_client: Optional[Synapse] = None) -> None

Pretty print an Entity as JSON asynchronously.

PARAMETER DESCRIPTION
entity

Either an Entity object (Dataset, DatasetCollection, EntityView, File, Folder, Link, MaterializedView, Project, RecordSet, SubmissionView, Table, VirtualTable), a Synapse ID string, or a dictionary representation of an entity.

TYPE: Union[str, dict, Dataset, DatasetCollection, EntityView, File, Folder, Link, MaterializedView, Project, RecordSet, SubmissionView, Table, VirtualTable]

ensure_ascii

If True, escapes all non-ASCII characters in the output. Defaults to True.

TYPE: bool DEFAULT: True

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
None

None. Prints the entity to the logger.

Printing an entity by ID

Print an entity using its Synapse ID:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import print_entity_async

async def main():
    syn = Synapse()
    syn.login()

    # Print entity by Synapse ID
    await print_entity_async("syn123456")

asyncio.run(main())
Printing multiple entities concurrently

Print multiple entities at the same time:

import asyncio
from synapseclient import Synapse
from synapseclient.operations import print_entity_async

async def main():
    syn = Synapse()
    syn.login()

    entity_ids = ["syn123456", "syn789012", "syn345678"]

    # Print all entities concurrently
    await asyncio.gather(
        *[print_entity_async(entity_id) for entity_id in entity_ids]
    )

asyncio.run(main())
Source code in synapseclient/operations/utility_operations.py
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
async def print_entity_async(
    entity: Union[
        str,
        dict,
        "Dataset",
        "DatasetCollection",
        "EntityView",
        "File",
        "Folder",
        "Link",
        "MaterializedView",
        "Project",
        "RecordSet",
        "SubmissionView",
        "Table",
        "VirtualTable",
    ],
    ensure_ascii: bool = True,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> None:
    """
    Pretty print an Entity as JSON asynchronously.

    Arguments:
        entity: Either an Entity object (Dataset, DatasetCollection, EntityView,
            File, Folder, Link, MaterializedView, Project, RecordSet,
            SubmissionView, Table, VirtualTable), a Synapse ID string, or a
            dictionary representation of an entity.
        ensure_ascii: If True, escapes all non-ASCII characters in the output.
            Defaults to True.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor.

    Returns:
        None. Prints the entity to the logger.

    Example: Printing an entity by ID
        Print an entity using its Synapse ID:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import print_entity_async

        async def main():
            syn = Synapse()
            syn.login()

            # Print entity by Synapse ID
            await print_entity_async("syn123456")

        asyncio.run(main())
        ```

    Example: Printing multiple entities concurrently
        Print multiple entities at the same time:

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.operations import print_entity_async

        async def main():
            syn = Synapse()
            syn.login()

            entity_ids = ["syn123456", "syn789012", "syn345678"]

            # Print all entities concurrently
            await asyncio.gather(
                *[print_entity_async(entity_id) for entity_id in entity_ids]
            )

        asyncio.run(main())
        ```
    """
    from synapseclient import Synapse
    from synapseclient.core import utils
    from synapseclient.operations.factory_operations import FileOptions, get_async

    syn = Synapse.get_client(synapse_client=synapse_client)
    logger = logging.getLogger(syn.logger.name)

    # If entity is a Synapse ID string, fetch the entity using get_async
    if isinstance(entity, str) and utils.is_synapse_id_str(entity):
        entity = await get_async(
            synapse_id=entity,
            file_options=FileOptions(download_file=False),
            synapse_client=synapse_client,
        )

    # Convert entity to dict if it's a dataclass (model object)
    if hasattr(entity, "__dataclass_fields__"):
        import dataclasses

        def filter_repr_fields(obj):
            """Recursively convert dataclass to dict, respecting repr=True fields only."""
            if hasattr(obj, "__dataclass_fields__"):
                # Filter fields to only those with repr=True
                filtered_fields = [
                    (field_obj.name, getattr(obj, field_obj.name))
                    for field_obj in dataclasses.fields(obj)
                    if field_obj.repr
                ]
                # Recursively process nested values
                return {
                    name: filter_repr_fields(value) for name, value in filtered_fields
                }
            elif isinstance(obj, list):
                return [filter_repr_fields(item) for item in obj]
            elif isinstance(obj, dict):
                return {k: filter_repr_fields(v) for k, v in obj.items()}
            else:
                return obj

        entity = filter_repr_fields(entity)

    # Try to print as JSON, fall back to string representation
    try:
        logger.info(
            json.dumps(entity, sort_keys=True, indent=2, ensure_ascii=ensure_ascii)
        )
    except TypeError:
        logger.info(str(entity))