Skip to content

Commit 2407819

Browse files
committed
[refactor/change] Explicitly provide client to public methods and CM methods
1 parent 0940169 commit 2407819

23 files changed

Lines changed: 191 additions & 238 deletions

pyatlan/cache/source_tag_cache.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ def get_name(self, asset: Asset):
154154
if not isinstance(asset, Asset):
155155
return
156156
try:
157-
source_tag_name = str(SourceTagName(asset))
157+
source_tag_name = str(SourceTagName(client=self.client, tag=asset))
158158
except AtlanError as e:
159159
LOGGER.error(
160160
"Unable to construct a source tag name for: %s", asset.qualified_name
@@ -174,24 +174,18 @@ class SourceTagName(AbstractAssetName):
174174
_TYPE_NAME = "SourceTagAttachment"
175175
_CONNECTION_DELIMITER = "@@"
176176

177-
def __init__(self, tag: Union[str, Asset]):
177+
def __init__(self, client: AtlanClient, tag: Union[str, Asset]):
178178
self.connection = None
179179
self.partial_tag_name = None
180180

181181
# NOTE: Checking if the first result is an "Asset" since in pyatlan,
182182
# "DbtTag" extends "Dbt" (unlike other tags like "SnowflakeTag" that extend the "Tag" model),
183183
# preventing Dbt tags from being excluded from caching:
184184
if isinstance(tag, Asset):
185-
from pyatlan.client.atlan import AtlanClient
186-
187185
source_tag_qn = tag.qualified_name or ""
188186
tokens = source_tag_qn.split("/")
189187
connection_qn = "/".join(tokens[:3]) if len(tokens) >= 3 else ""
190-
conn = (
191-
AtlanClient.get_current_client().connection_cache.get_by_qualified_name(
192-
connection_qn
193-
)
194-
)
188+
conn = client.connection_cache.get_by_qualified_name(connection_qn)
195189
self.connection = ConnectionName(conn)
196190
self.partial_tag_name = source_tag_qn[len(connection_qn) + 1 :] # noqa
197191

pyatlan/client/asset.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,7 @@ def save(
628628
entities.append(entity)
629629
for asset in entities:
630630
asset.validate_required()
631+
asset.flush_custom_metadata(client=self._client) # type: ignore[arg-type]
631632
request = BulkRequest[Asset](entities=entities)
632633
raw_json = self._client._call_api(BULK_UPDATE, query_params, request)
633634
response = AssetMutationResponse(**raw_json)
@@ -745,6 +746,7 @@ def save_replacing_cm(
745746
entities.append(entity)
746747
for asset in entities:
747748
asset.validate_required()
749+
asset.flush_custom_metadata(client=self._client) # type: ignore[arg-type]
748750
request = BulkRequest[Asset](entities=entities)
749751
raw_json = self._client._call_api(BULK_UPDATE, query_params, request)
750752
return AssetMutationResponse(**raw_json)
@@ -885,6 +887,7 @@ def _restore_asset(self, asset: Asset) -> AssetMutationResponse:
885887
"replaceBusinessAttributes": False,
886888
"overwriteBusinessAttributes": False,
887889
}
890+
to_restore.flush_custom_metadata(self._client) # type: ignore[arg-type]
888891
request = BulkRequest[Asset](entities=[to_restore])
889892
raw_json = self._client._call_api(BULK_UPDATE, query_params, request)
890893
return AssetMutationResponse(**raw_json)
@@ -919,7 +922,7 @@ def _modify_tags(
919922
)
920923

921924
atlan_tag = [
922-
AtlanTag(
925+
AtlanTag( # type: ignore[call-arg]
923926
type_name=AtlanTagName(display_text=name),
924927
propagate=propagate,
925928
remove_propagations_on_entity_delete=remove_propagation_on_delete,
@@ -1091,6 +1094,7 @@ def _update_asset_by_attribute(
10911094
self, asset: A, asset_type: Type[A], qualified_name: str
10921095
):
10931096
query_params = {"attr:qualifiedName": qualified_name}
1097+
asset.flush_custom_metadata(client=self._client) # type: ignore[arg-type]
10941098
raw_json = self._client._call_api(
10951099
PARTIAL_UPDATE_ENTITY_BY_ATTRIBUTE.format_path_with_params(
10961100
asset_type.__name__
@@ -1404,7 +1408,7 @@ def remove_custom_metadata(self, guid: str, cm_name: str):
14041408
:param cm_name: human-readable name of the custom metadata to remove
14051409
:raises AtlanError: on any API communication issue
14061410
"""
1407-
custom_metadata = CustomMetadataDict(name=cm_name)
1411+
custom_metadata = CustomMetadataDict(client=self._client, name=cm_name) # type: ignore[arg-type]
14081412
# invoke clear_all so all attributes are set to None and consequently removed
14091413
custom_metadata.clear_all()
14101414
custom_metadata_request = CustomMetadataRequest.create(

pyatlan/client/open_lineage.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,6 @@ def create_connection(
4545
:param admin_groups:list of admin groups to associate with this connection
4646
:return: details of the connection created
4747
"""
48-
from pyatlan.client.atlan import AtlanClient
49-
50-
client = AtlanClient.get_current_client()
51-
5248
create_credential = Credential()
5349
create_credential.auth_type = "atlan_api_key"
5450
create_credential.name = (
@@ -65,7 +61,7 @@ def create_connection(
6561
"events.topic": f"openlineage_{connector_type.value}",
6662
"events.urlPath": f"/events/openlineage/{connector_type.value}/api/v1/lineage",
6763
}
68-
response = client.credentials.creator(credential=create_credential)
64+
response = self._client.credentials.creator(credential=create_credential) # type: ignore[attr-defined]
6965
connection = Connection.creator(
7066
name=name,
7167
connector_type=connector_type,
@@ -75,7 +71,7 @@ def create_connection(
7571
)
7672

7773
connection.default_credential_guid = response.id
78-
return client.asset.save(connection)
74+
return self._client.asset.save(connection) # type: ignore[attr-defined]
7975

8076
@validate_arguments
8177
def send(

pyatlan/client/typedef.py

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -64,18 +64,6 @@ def _build_typedef_request(typedef: TypeDef) -> TypeDefResponse:
6464
return payload
6565

6666

67-
def _refresh_caches(typedef: TypeDef) -> None:
68-
from pyatlan.client.atlan import AtlanClient
69-
70-
client = AtlanClient.get_current_client()
71-
if isinstance(typedef, AtlanTagDef):
72-
client.atlan_tag_cache.refresh_cache()
73-
if isinstance(typedef, CustomMetadataDef):
74-
client.custom_metadata_cache.refresh_cache()
75-
if isinstance(typedef, EnumDef):
76-
client.enum_cache.refresh_cache()
77-
78-
7967
class TypeDefFactory:
8068
@staticmethod
8169
def create(raw_json: dict) -> TypeDef:
@@ -117,6 +105,14 @@ def __init__(self, client: ApiCaller):
117105
)
118106
self._client = client
119107

108+
def _refresh_caches(self, typedef: TypeDef) -> None:
109+
if isinstance(typedef, AtlanTagDef):
110+
self._client.atlan_tag_cache.refresh_cache() # type: ignore[attr-defined]
111+
if isinstance(typedef, CustomMetadataDef):
112+
self._client.custom_metadata_cache.refresh_cache() # type: ignore[attr-defined]
113+
if isinstance(typedef, EnumDef):
114+
self._client.enum_cache.refresh_cache() # type: ignore[attr-defined]
115+
120116
def get_all(self) -> TypeDefResponse:
121117
"""
122118
Retrieves a TypeDefResponse object that contains a list of all the type definitions in Atlan.
@@ -189,7 +185,7 @@ def create(self, typedef: TypeDef) -> TypeDefResponse:
189185
raw_json = self._client._call_api(
190186
CREATE_TYPE_DEFS, request_obj=payload, exclude_unset=True
191187
)
192-
_refresh_caches(typedef)
188+
self._refresh_caches(typedef)
193189
return TypeDefResponse(**raw_json)
194190

195191
@validate_arguments
@@ -210,7 +206,7 @@ def update(self, typedef: TypeDef) -> TypeDefResponse:
210206
raw_json = self._client._call_api(
211207
UPDATE_TYPE_DEFS, request_obj=payload, exclude_unset=True
212208
)
213-
_refresh_caches(typedef)
209+
self._refresh_caches(typedef)
214210
return TypeDefResponse(**raw_json)
215211

216212
@validate_arguments
@@ -226,29 +222,26 @@ def purge(self, name: str, typedef_type: type) -> None:
226222
:raises NotFoundError: if the typedef you are trying to delete cannot be found
227223
:raises AtlanError: on any API communication issue
228224
"""
229-
from pyatlan.client.atlan import AtlanClient
230-
231-
client = AtlanClient.get_current_client()
232225
if typedef_type == CustomMetadataDef:
233-
internal_name = client.custom_metadata_cache.get_id_for_name(name)
226+
internal_name = self._client.custom_metadata_cache.get_id_for_name(name) # type: ignore[attr-defined]
234227
elif typedef_type == EnumDef:
235228
internal_name = name
236229
elif typedef_type == AtlanTagDef:
237-
internal_name = str(client.atlan_tag_cache.get_id_for_name(name))
230+
internal_name = str(self._client.atlan_tag_cache.get_id_for_name(name)) # type: ignore[attr-defined]
238231
else:
239232
raise ErrorCode.UNABLE_TO_PURGE_TYPEDEF_OF_TYPE.exception_with_parameters(
240233
typedef_type
241234
)
242235
if internal_name:
243-
self._client._call_api(
236+
self._client._client._call_api( # type: ignore[attr-defined]
244237
DELETE_TYPE_DEF_BY_NAME.format_path_with_params(internal_name)
245238
)
246239
else:
247240
raise ErrorCode.TYPEDEF_NOT_FOUND_BY_NAME.exception_with_parameters(name)
248241

249242
if typedef_type == CustomMetadataDef:
250-
client.custom_metadata_cache.refresh_cache()
243+
self._client.custom_metadata_cache.refresh_cache() # type: ignore[attr-defined]
251244
elif typedef_type == EnumDef:
252-
client.enum_cache.refresh_cache()
245+
self._client.enum_cache.refresh_cache() # type: ignore[attr-defined]
253246
elif typedef_type == AtlanTagDef:
254-
client.atlan_tag_cache.refresh_cache()
247+
self._client.atlan_tag_cache.refresh_cache() # type: ignore[attr-defined]

pyatlan/client/user.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,15 +57,12 @@ def create(
5757
:raises AtlanError: on any API communication issue
5858
:returns: a UserResponse object which contains the list of details of created users if `return_info` is `True`, otherwise `None`
5959
"""
60-
from pyatlan.client.atlan import AtlanClient
6160

6261
cur = CreateUserRequest(users=[])
6362
for user in users:
6463
role_name = str(user.workspace_role)
6564
if (
66-
role_id := AtlanClient.get_current_client().role_cache.get_id_for_name(
67-
role_name
68-
)
65+
role_id := self._client.role_cache.get_id_for_name(role_name) # type: ignore[attr-defined]
6966
) and user.email:
7067
to_create = CreateUserRequest.CreateUser(
7168
email=user.email,

pyatlan/model/assets/badge.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from __future__ import annotations
66

7-
from typing import ClassVar, List, Optional
7+
from typing import TYPE_CHECKING, ClassVar, List, Optional
88
from warnings import warn
99

1010
from pydantic.v1 import Field, StrictStr, validator
@@ -16,6 +16,9 @@
1616

1717
from .core.asset import Asset
1818

19+
if TYPE_CHECKING:
20+
from pyatlan.client.atlan import AtlanClient
21+
1922

2023
class Badge(Asset, type_name="Badge"):
2124
"""Description"""
@@ -131,6 +134,7 @@ class Attributes(Asset.Attributes):
131134
def create(
132135
cls,
133136
*,
137+
client: AtlanClient,
134138
name: StrictStr,
135139
cm_name: str,
136140
cm_attribute: str,
@@ -140,9 +144,6 @@ def create(
140144
["name", "cm_name", "cm_attribute", "badge_conditions"],
141145
[name, cm_name, cm_attribute, badge_conditions],
142146
)
143-
from pyatlan.client.atlan import AtlanClient
144-
145-
client = AtlanClient.get_current_client()
146147
cm_id = client.custom_metadata_cache.get_id_for_name(cm_name)
147148
cm_attr_id = client.custom_metadata_cache.get_attr_id_for_name(
148149
set_name=cm_name, attr_name=cm_attribute

pyatlan/model/assets/connection.py

Lines changed: 10 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from __future__ import annotations
66

77
from datetime import datetime
8-
from typing import ClassVar, Dict, List, Optional, Set
8+
from typing import TYPE_CHECKING, ClassVar, Dict, List, Optional, Set
99
from warnings import warn
1010

1111
from pydantic.v1 import Field, validator
@@ -22,6 +22,9 @@
2222

2323
from .core.asset import Asset
2424

25+
if TYPE_CHECKING:
26+
from pyatlan.client.atlan import AtlanClient
27+
2528

2629
class Connection(Asset, type_name="Connection"):
2730
"""Description"""
@@ -31,6 +34,7 @@ class Connection(Asset, type_name="Connection"):
3134
def creator(
3235
cls,
3336
*,
37+
client: AtlanClient,
3438
name: str,
3539
connector_type: AtlanConnectorType,
3640
admin_users: Optional[List[str]] = None,
@@ -50,6 +54,9 @@ def creator(
5054
connector_name=connector_type.value,
5155
category=connector_type.category.value,
5256
)
57+
client.user_cache.validate_names(names=admin_users or [])
58+
client.role_cache.validate_idstrs(idstrs=admin_roles or [])
59+
client.group_cache.validate_aliases(aliases=admin_groups or [])
5360
attr.admin_users = set() if admin_users is None else set(admin_users)
5461
attr.admin_groups = set() if admin_groups is None else set(admin_groups)
5562
attr.admin_roles = set() if admin_roles is None else set(admin_roles)
@@ -62,6 +69,7 @@ def creator(
6269
def create(
6370
cls,
6471
*,
72+
client: AtlanClient,
6573
name: str,
6674
connector_type: AtlanConnectorType,
6775
admin_users: Optional[List[str]] = None,
@@ -77,6 +85,7 @@ def create(
7785
stacklevel=2,
7886
)
7987
return cls.creator(
88+
client=client,
8089
name=name,
8190
connector_type=connector_type,
8291
admin_users=admin_users,
@@ -724,36 +733,6 @@ class Attributes(Asset.Attributes):
724733

725734
is_loaded: bool = Field(default=True)
726735

727-
@validator("admin_users")
728-
def admin_users_valid(cls, admin_users, values):
729-
from pyatlan.client.atlan import AtlanClient
730-
731-
if values.get("is_loaded", False):
732-
AtlanClient.get_current_client().user_cache.validate_names(
733-
names=admin_users
734-
)
735-
return admin_users
736-
737-
@validator("admin_roles")
738-
def admin_roles_valid(cls, admin_roles, values):
739-
from pyatlan.client.atlan import AtlanClient
740-
741-
if values.get("is_loaded", False):
742-
AtlanClient.get_current_client().role_cache.validate_idstrs(
743-
idstrs=admin_roles
744-
)
745-
return admin_roles
746-
747-
@validator("admin_groups")
748-
def admin_groups_valid(cls, admin_groups, values):
749-
from pyatlan.client.atlan import AtlanClient
750-
751-
if values.get("is_loaded", False):
752-
AtlanClient.get_current_client().group_cache.validate_aliases(
753-
aliases=admin_groups
754-
)
755-
return admin_groups
756-
757736
attributes: Connection.Attributes = Field(
758737
default_factory=lambda: Connection.Attributes(),
759738
description=(

pyatlan/model/assets/core/data_product.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -125,18 +125,15 @@ def create_for_modification(
125125
name=name,
126126
)
127127

128-
def get_assets(self, client: Optional[AtlanClient] = None):
128+
def get_assets(self, client: AtlanClient):
129129
"""
130130
Reterieves list of all assets linked to the provided data product.
131131
132-
:param client: connectivity to an Atlan tenant (optional). If not provided, the default client will be used.
132+
:param client: connectivity to an Atlan tenant. If not provided, the default client will be used.
133133
:raises InvalidRequestError: if DataProduct asset DSL cannot be found (does not exist) in Atlan
134134
:raises AtlanError: if there is an issue interacting with the API
135135
:returns: instance of `IndexSearchResults` with list of all assets linked to the provided data product
136136
"""
137-
from pyatlan.client.atlan import AtlanClient
138-
139-
client = AtlanClient.get_current_client() if not client else client
140137
dp_dsl = self.data_product_assets_d_s_l
141138
if not dp_dsl:
142139
raise ErrorCode.MISSING_DATA_PRODUCT_ASSET_DSL.exception_with_parameters()

0 commit comments

Comments
 (0)