Skip to content

Commit

Permalink
Replace | with Union type for Python 3.9 compatibility (#1209)
Browse files Browse the repository at this point in the history
* Replace `|` with `Union` type for Python 3.9 compatibility

* Format

* Update date
  • Loading branch information
Thoralf-M authored Sep 12, 2023
1 parent 1b05eb3 commit 6dfe3a7
Show file tree
Hide file tree
Showing 19 changed files with 89 additions and 80 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/bindings-python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.10"]
python-version: ["3.9"]

steps:
- name: Checkout the Source Code
Expand Down Expand Up @@ -77,7 +77,7 @@ jobs:
matrix:
# os: [windows-latest, macos-latest, ubuntu-latest]
os: [windows-latest, ubuntu-latest]
python-version: ["3.10"]
python-version: ["3.9"]

steps:
- name: Checkout the Source Code
Expand Down
6 changes: 5 additions & 1 deletion bindings/python/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Security -->

## 1.0.2 - 2023-MM-DD
## 1.0.2 - 2023-09-12

### Added

- `ClientOptions::maxParallelApiRequests`;

### Changed

- Replaced `|` with `Union` type for Python 3.9 compatibility;

### Fixed

- `Utils::parse_bech32_address()`;
Expand Down
2 changes: 1 addition & 1 deletion bindings/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Python binding to the [iota-sdk library](/README.md).

## Requirements

- [Python 3.10+](https://www.python.org)
- [Python 3.9+](https://www.python.org)
- [pip ^21.x](https://pypi.org/project/pip)
- `Rust` and `Cargo` to compile the binding. Install
them [here](https://doc.rust-lang.org/cargo/getting-started/installation.html).
Expand Down
20 changes: 11 additions & 9 deletions bindings/python/iota_sdk/client/_high_level_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from iota_sdk.types.output import OutputWithMetadata
from iota_sdk.types.output_id import OutputId
from iota_sdk.types.common import CoinType
from typing import List, Optional
from typing import List, Optional, Union
from dacite import from_dict


Expand Down Expand Up @@ -128,7 +128,7 @@ def find_blocks(self, block_ids: List[HexStr]) -> List[Block]:
})
return [Block.from_dict(block) for block in blocks]

def retry(self, block_id: HexStr) -> List[HexStr | Block]:
def retry(self, block_id: HexStr) -> List[Union[HexStr, Block]]:
"""Retries (promotes or reattaches) a block for provided block id. Block should only be
retried only if they are valid and haven't been confirmed for a while.
Expand All @@ -143,7 +143,7 @@ def retry(self, block_id: HexStr) -> List[HexStr | Block]:
return result

def retry_until_included(
self, block_id: HexStr, interval: Optional[int] = None, max_attempts: Optional[int] = None) -> List[List[HexStr | Block]]:
self, block_id: HexStr, interval: Optional[int] = None, max_attempts: Optional[int] = None) -> List[List[Union[HexStr, Block]]]:
"""Retries (promotes or reattaches) a block for provided block id until it's included (referenced by a
milestone). Default interval is 5 seconds and max attempts is 40. Returns the included block at first
position and additional reattached blocks.
Expand All @@ -169,8 +169,8 @@ def block_class(block_id_and_block):
for block_id_and_block in result]
return blockIdsAndBlocks

def consolidate_funds(self, secret_manager: LedgerNanoSecretManager | MnemonicSecretManager | SeedSecretManager |
StrongholdSecretManager, generate_addresses_options: GenerateAddressesOptions) -> str:
def consolidate_funds(self, secret_manager: Union[LedgerNanoSecretManager, MnemonicSecretManager, SeedSecretManager,
StrongholdSecretManager], generate_addresses_options: GenerateAddressesOptions) -> str:
"""Function to consolidate all funds from a range of addresses to the address with the lowest index in that range.
Returns the address to which the funds got consolidated, if any were available.
Expand Down Expand Up @@ -198,7 +198,7 @@ def find_inputs(self, addresses: List[str], amount: int):
'amount': amount
})

def reattach(self, block_id: HexStr) -> List[HexStr | Block]:
def reattach(self, block_id: HexStr) -> List[Union[HexStr, Block]]:
"""Reattaches blocks for a provided block id. Blocks can be reattached only if they are valid and
haven't been confirmed for a while .
Expand All @@ -214,7 +214,8 @@ def reattach(self, block_id: HexStr) -> List[HexStr | Block]:
result[1] = Block.from_dict(result[1])
return result

def reattach_unchecked(self, block_id: HexStr) -> List[HexStr | Block]:
def reattach_unchecked(
self, block_id: HexStr) -> List[Union[HexStr, Block]]:
"""Reattach a block without checking if it should be reattached.
Args:
Expand All @@ -229,7 +230,7 @@ def reattach_unchecked(self, block_id: HexStr) -> List[HexStr | Block]:
result[1] = Block.from_dict(result[1])
return result

def promote(self, block_id: HexStr) -> List[HexStr | Block]:
def promote(self, block_id: HexStr) -> List[Union[HexStr, Block]]:
"""Promotes a block. The method should validate if a promotion is necessary through get_block.
If not, the method should error out and should not allow unnecessary promotions.
Expand All @@ -245,7 +246,8 @@ def promote(self, block_id: HexStr) -> List[HexStr | Block]:
result[1] = Block.from_dict(result[1])
return result

def promote_unchecked(self, block_id: HexStr) -> List[HexStr | Block]:
def promote_unchecked(
self, block_id: HexStr) -> List[Union[HexStr, Block]]:
"""Promote a block without checking if it should be promoted.
Args:
Expand Down
9 changes: 5 additions & 4 deletions bindings/python/iota_sdk/client/_node_core_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from iota_sdk.types.output_id import OutputId
from iota_sdk.types.payload import MilestonePayload
from iota_sdk.types.utxo_changes import UtxoChanges
from typing import List
from typing import List, Union
from dacite import from_dict


Expand Down Expand Up @@ -97,7 +97,8 @@ def post_block_raw(self, block_bytes: List[int]) -> HexStr:
'blockBytes': block_bytes
})

def get_output(self, output_id: OutputId | HexStr) -> OutputWithMetadata:
def get_output(
self, output_id: Union[OutputId, HexStr]) -> OutputWithMetadata:
"""Get the output corresponding to the given output id.
Returns:
Expand All @@ -109,8 +110,8 @@ def get_output(self, output_id: OutputId | HexStr) -> OutputWithMetadata:
'outputId': output_id_str
}))

def get_output_metadata(self, output_id: OutputId |
HexStr) -> OutputMetadata:
def get_output_metadata(
self, output_id: Union[OutputId, HexStr]) -> OutputMetadata:
"""Get the output metadata corresponding to the given output id.
Returns:
Expand Down
20 changes: 10 additions & 10 deletions bindings/python/iota_sdk/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from json import dumps, loads
import humps
from datetime import timedelta
from typing import Any, Dict, List, Optional
from typing import Any, Dict, List, Optional, Union
from dacite import from_dict


Expand All @@ -39,7 +39,7 @@ class Client(NodeCoreAPI, NodeIndexerAPI, HighLevelAPI, ClientUtils):

def __init__(
self,
nodes: Optional[str | List[str]] = None,
nodes: Optional[Union[str, List[str]]] = None,
primary_node: Optional[str] = None,
primary_pow_node: Optional[str] = None,
permanode: Optional[str] = None,
Expand Down Expand Up @@ -359,8 +359,8 @@ def build_nft_output(self,
}))

def build_and_post_block(self,
secret_manager: Optional[LedgerNanoSecretManager | MnemonicSecretManager |
SeedSecretManager | StrongholdSecretManager] = None,
secret_manager: Optional[Union[LedgerNanoSecretManager, MnemonicSecretManager,
SeedSecretManager, StrongholdSecretManager]] = None,
account_index: Optional[int] = None,
coin_type: Optional[int] = None,
custom_remainder_address: Optional[str] = None,
Expand All @@ -371,7 +371,7 @@ def build_and_post_block(self,
inputs: Optional[List[Dict[str, Any]]] = None,
output: Optional[AddressAndAmount] = None,
outputs: Optional[List[Any]] = None,
tag: Optional[HexStr] = None) -> List[HexStr | Block]:
tag: Optional[HexStr] = None) -> List[Union[HexStr, Block]]:
"""Build and post a block.
**Arguments**
Expand Down Expand Up @@ -471,8 +471,8 @@ def unhealthy_nodes(self) -> List[Dict[str, Any]]:
return self._call_method('unhealthyNodes')

def prepare_transaction(self,
secret_manager: Optional[LedgerNanoSecretManager | MnemonicSecretManager |
SeedSecretManager | StrongholdSecretManager] = None,
secret_manager: Optional[Union[LedgerNanoSecretManager, MnemonicSecretManager,
SeedSecretManager, StrongholdSecretManager]] = None,
options=None):
"""Prepare a transaction for signing.
Expand All @@ -485,8 +485,8 @@ def prepare_transaction(self,
'options': options
}))

def sign_transaction(self, secret_manager: LedgerNanoSecretManager | MnemonicSecretManager | SeedSecretManager |
StrongholdSecretManager, prepared_transaction_data: PreparedTransactionData) -> TransactionPayload:
def sign_transaction(self, secret_manager: Union[LedgerNanoSecretManager, MnemonicSecretManager,
SeedSecretManager, StrongholdSecretManager], prepared_transaction_data: PreparedTransactionData) -> TransactionPayload:
"""Sign a transaction.
Args:
Expand All @@ -498,7 +498,7 @@ def sign_transaction(self, secret_manager: LedgerNanoSecretManager | MnemonicSec
'preparedTransactionData': prepared_transaction_data
}))

def submit_payload(self, payload: Payload) -> List[HexStr | Block]:
def submit_payload(self, payload: Payload) -> List[Union[HexStr, Block]]:
"""Submit a payload in a block.
Args:
Expand Down
6 changes: 3 additions & 3 deletions bindings/python/iota_sdk/secret_manager/secret_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from iota_sdk.types.payload import TransactionPayload
from json import dumps, loads
import humps
from typing import Optional
from typing import Optional, Union
from dacite import from_dict


Expand Down Expand Up @@ -82,8 +82,8 @@ class SecretManagerError(Exception):


class SecretManager():
def __init__(self, secret_manager: Optional[LedgerNanoSecretManager | MnemonicSecretManager |
SeedSecretManager | StrongholdSecretManager] = None, secret_manager_handle=None):
def __init__(self, secret_manager: Optional[Union[LedgerNanoSecretManager, MnemonicSecretManager,
SeedSecretManager, StrongholdSecretManager]] = None, secret_manager_handle=None):
"""Initialize a secret manager.
Args:
Expand Down
6 changes: 3 additions & 3 deletions bindings/python/iota_sdk/types/block.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from __future__ import annotations
from dataclasses import dataclass
from typing import Dict, List, Optional
from typing import Dict, List, Optional, Union
from iota_sdk.types.common import HexStr
from iota_sdk.types.payload import TaggedDataPayload, TransactionPayload, MilestonePayload
from iota_sdk.utils import Utils
Expand All @@ -25,8 +25,8 @@ class Block:
protocolVersion: int
parents: List[HexStr]
nonce: str
payload: Optional[TaggedDataPayload |
TransactionPayload | MilestonePayload] = None
payload: Optional[Union[TaggedDataPayload,
TransactionPayload, MilestonePayload]] = None

@classmethod
def from_dict(cls, block_dict: Dict) -> Block:
Expand Down
5 changes: 3 additions & 2 deletions bindings/python/iota_sdk/types/feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from iota_sdk.types.common import HexStr
from dataclasses import dataclass, field
from enum import IntEnum
from typing import Union


class FeatureType(IntEnum):
Expand Down Expand Up @@ -41,7 +42,7 @@ class SenderFeature(Feature):
Attributes:
address: A given sender address.
"""
address: Ed25519Address | AliasAddress | NFTAddress
address: Union[Ed25519Address, AliasAddress, NFTAddress]
type: int = field(
default_factory=lambda: int(
FeatureType.Sender),
Expand All @@ -54,7 +55,7 @@ class IssuerFeature(Feature):
Attributes:
address: A given issuer address.
"""
address: Ed25519Address | AliasAddress | NFTAddress
address: Union[Ed25519Address, AliasAddress, NFTAddress]
type: int = field(
default_factory=lambda: int(
FeatureType.Issuer),
Expand Down
38 changes: 19 additions & 19 deletions bindings/python/iota_sdk/types/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
from enum import IntEnum
from typing import Dict, Optional, List
from typing import Dict, Optional, List, Union
from dacite import from_dict
from iota_sdk.types.common import HexStr
from iota_sdk.types.feature import SenderFeature, IssuerFeature, MetadataFeature, TagFeature
Expand Down Expand Up @@ -89,10 +89,10 @@ class BasicOutput(Output):
The type of output.
"""
amount: str
unlockConditions: List[AddressUnlockCondition | ExpirationUnlockCondition | StorageDepositReturnUnlockCondition |
TimelockUnlockCondition]
features: Optional[List[SenderFeature |
MetadataFeature | TagFeature]] = None
unlockConditions: List[Union[AddressUnlockCondition, ExpirationUnlockCondition, StorageDepositReturnUnlockCondition,
TimelockUnlockCondition]]
features: Optional[List[Union[SenderFeature,
MetadataFeature, TagFeature]]] = None
nativeTokens: Optional[List[NativeToken]] = None
type: int = field(
default_factory=lambda: int(
Expand Down Expand Up @@ -129,12 +129,12 @@ class AliasOutput(Output):
aliasId: HexStr
stateIndex: int
foundryCounter: int
unlockConditions: List[StateControllerAddressUnlockCondition |
GovernorAddressUnlockCondition]
features: Optional[List[SenderFeature |
MetadataFeature]] = None
immutableFeatures: Optional[List[IssuerFeature |
MetadataFeature]] = None
unlockConditions: List[Union[StateControllerAddressUnlockCondition,
GovernorAddressUnlockCondition]]
features: Optional[List[Union[SenderFeature,
MetadataFeature]]] = None
immutableFeatures: Optional[List[Union[IssuerFeature,
MetadataFeature]]] = None
stateMetadata: Optional[HexStr] = None
nativeTokens: Optional[List[NativeToken]] = None
type: int = field(
Expand Down Expand Up @@ -198,12 +198,12 @@ class NftOutput(Output):
"""
amount: str
nftId: HexStr
unlockConditions: List[AddressUnlockCondition | ExpirationUnlockCondition |
StorageDepositReturnUnlockCondition | TimelockUnlockCondition]
features: Optional[List[SenderFeature |
MetadataFeature | TagFeature]] = None
immutableFeatures: Optional[List[
IssuerFeature | MetadataFeature]] = None
unlockConditions: List[Union[AddressUnlockCondition, ExpirationUnlockCondition,
StorageDepositReturnUnlockCondition, TimelockUnlockCondition]]
features: Optional[List[Union[SenderFeature,
MetadataFeature, TagFeature]]] = None
immutableFeatures: Optional[List[Union[
IssuerFeature, MetadataFeature]]] = None
nativeTokens: Optional[List[NativeToken]] = None
type: int = field(default_factory=lambda: int(OutputType.Nft), init=False)

Expand Down Expand Up @@ -257,7 +257,7 @@ class OutputWithMetadata:
"""

metadata: OutputMetadata
output: AliasOutput | FoundryOutput | NftOutput | BasicOutput
output: Union[AliasOutput, FoundryOutput, NftOutput, BasicOutput]

@classmethod
def from_dict(cls, dict: Dict) -> OutputWithMetadata:
Expand All @@ -277,7 +277,7 @@ def as_dict(self):


def output_from_dict(
output: Dict[str, any]) -> TreasuryOutput | BasicOutput | AliasOutput | FoundryOutput | NftOutput | Output:
output: Dict[str, any]) -> Union[TreasuryOutput, BasicOutput, AliasOutput, FoundryOutput, NftOutput, Output]:
output_type = OutputType(output['type'])

if output_type == OutputType.Treasury:
Expand Down
6 changes: 3 additions & 3 deletions bindings/python/iota_sdk/types/output_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
from typing import Optional, Union
from iota_sdk.types.address import Ed25519Address, AliasAddress, NFTAddress
from iota_sdk.types.common import HexStr
from iota_sdk.types.output import BasicOutput, AliasOutput, FoundryOutput, NftOutput, OutputMetadata
Expand All @@ -27,9 +27,9 @@ class OutputData():

outputId: HexStr
metadata: OutputMetadata
output: AliasOutput | FoundryOutput | NftOutput | BasicOutput
output: Union[AliasOutput, FoundryOutput, NftOutput, BasicOutput]
isSpent: bool
address: Ed25519Address | AliasAddress | NFTAddress
address: Union[Ed25519Address, AliasAddress, NFTAddress]
networkId: str
remainder: bool
chain: Optional[Bip44] = None
Loading

0 comments on commit 6dfe3a7

Please sign in to comment.