0
# Data Conversions
1
2
Flexible type conversion utilities supporting multiple input formats with consistent output types. Core functionality for data transformation pipelines in Ethereum applications.
3
4
## Capabilities
5
6
### Core Conversion Functions
7
8
Convert between bytes, hex strings, integers, and text with flexible input handling.
9
10
```python { .api }
11
def to_bytes(primitive=None, hexstr=None, text=None) -> bytes:
12
"""
13
Convert various formats to bytes.
14
15
Args:
16
primitive: Integer, bytes, or other primitive value
17
hexstr (str): Hex string (with or without 0x prefix)
18
text (str): UTF-8 text string
19
20
Returns:
21
bytes: Converted byte data
22
23
Raises:
24
ValidationError: If no input provided or invalid format
25
TypeError: If multiple inputs provided
26
"""
27
28
def to_hex(primitive=None, hexstr=None, text=None) -> str:
29
"""
30
Convert various formats to 0x-prefixed hex string.
31
32
Args:
33
primitive: Integer, bytes, or other primitive value
34
hexstr (str): Hex string (normalized to 0x prefix)
35
text (str): UTF-8 text string
36
37
Returns:
38
str: 0x-prefixed hex string
39
40
Raises:
41
ValidationError: If no input provided or invalid format
42
TypeError: If multiple inputs provided
43
"""
44
45
def to_int(primitive=None, hexstr=None, text=None) -> int:
46
"""
47
Convert various formats to integer.
48
49
Args:
50
primitive: Integer, bytes, or other primitive value
51
hexstr (str): Hex string (with or without 0x prefix)
52
text (str): UTF-8 text string (must be numeric)
53
54
Returns:
55
int: Converted integer value
56
57
Raises:
58
ValidationError: If no input provided or invalid format
59
TypeError: If multiple inputs provided
60
"""
61
62
def to_text(primitive=None, hexstr=None, text=None) -> str:
63
"""
64
Convert various formats to UTF-8 text string.
65
66
Args:
67
primitive: Integer, bytes, or other primitive value
68
hexstr (str): Hex string (decoded as UTF-8)
69
text (str): Text string (returned as-is)
70
71
Returns:
72
str: UTF-8 text string
73
74
Raises:
75
ValidationError: If no input provided or invalid format
76
TypeError: If multiple inputs provided
77
UnicodeDecodeError: If bytes cannot be decoded as UTF-8
78
"""
79
```
80
81
### Type-Aware Conversion Helpers
82
83
Convert values while treating strings as specific types.
84
85
```python { .api }
86
def hexstr_if_str(to_type, hexstr_or_primitive):
87
"""
88
Convert value to specified type, treating strings as hex strings.
89
90
Args:
91
to_type: Target conversion function (to_bytes, to_int, etc.)
92
hexstr_or_primitive: Value to convert
93
94
Returns:
95
Converted value of target type
96
"""
97
98
def text_if_str(to_type, text_or_primitive):
99
"""
100
Convert value to specified type, treating strings as text.
101
102
Args:
103
to_type: Target conversion function (to_bytes, to_int, etc.)
104
text_or_primitive: Value to convert
105
106
Returns:
107
Converted value of target type
108
"""
109
```
110
111
## Usage Examples
112
113
### Basic Conversions
114
115
```python
116
from eth_utils import to_bytes, to_hex, to_int, to_text
117
118
# Convert integer to different formats
119
number = 12345
120
print(to_hex(primitive=number)) # 0x3039
121
print(to_bytes(primitive=number)) # b'09'
122
print(to_text(primitive=number)) # '12345'
123
124
# Convert hex string to other formats
125
hex_str = "0x48656c6c6f"
126
print(to_bytes(hexstr=hex_str)) # b'Hello'
127
print(to_int(hexstr=hex_str)) # 310939249775
128
print(to_text(hexstr=hex_str)) # 'Hello'
129
130
# Convert text to other formats
131
text = "Hello"
132
print(to_bytes(text=text)) # b'Hello'
133
print(to_hex(text=text)) # 0x48656c6c6f
134
print(to_int(text=text)) # Raises ValidationError (not numeric)
135
```
136
137
### Working with Transaction Data
138
139
```python
140
from eth_utils import to_bytes, to_hex, to_int
141
142
# Transaction hash from different sources
143
tx_hash_hex = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
144
tx_hash_bytes = bytes.fromhex("1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef")
145
146
# Normalize to hex format
147
normalized_hash = to_hex(primitive=tx_hash_bytes)
148
print(normalized_hash) # 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
149
150
# Convert block number from hex
151
block_hex = "0x1b4" # Block 436 in hex
152
block_number = to_int(hexstr=block_hex)
153
print(block_number) # 436
154
```
155
156
### Smart Contract Data Processing
157
158
```python
159
from eth_utils import to_bytes, to_hex, to_text
160
161
# Process contract call return data
162
return_data = "0x48656c6c6f20576f726c64" # "Hello World" in hex
163
164
# Convert to readable text
165
message = to_text(hexstr=return_data)
166
print(message) # "Hello World"
167
168
# Convert to bytes for further processing
169
data_bytes = to_bytes(hexstr=return_data)
170
print(len(data_bytes)) # 11 bytes
171
172
# Ensure hex format for transmission
173
hex_data = to_hex(primitive=data_bytes)
174
print(hex_data) # 0x48656c6c6f20576f726c64
175
```
176
177
### Type-Aware Processing
178
179
```python
180
from eth_utils import hexstr_if_str, text_if_str, to_bytes, to_int
181
182
def process_hex_input(value):
183
"""Process input that might be hex string or bytes."""
184
return hexstr_if_str(to_bytes, value)
185
186
def process_text_input(value):
187
"""Process input that might be text string or bytes."""
188
return text_if_str(to_bytes, value)
189
190
# Hex string input
191
hex_input = "0x48656c6c6f"
192
result1 = process_hex_input(hex_input)
193
print(result1) # b'Hello'
194
195
# Text string input
196
text_input = "Hello"
197
result2 = process_text_input(text_input)
198
print(result2) # b'Hello'
199
200
# Bytes input works with both
201
bytes_input = b'Hello'
202
result3 = process_hex_input(bytes_input) # b'Hello'
203
result4 = process_text_input(bytes_input) # b'Hello'
204
```
205
206
### Encoding/Decoding Patterns
207
208
```python
209
from eth_utils import to_hex, to_bytes, to_text
210
211
def encode_string_to_hex(text_string):
212
"""Encode a text string to hex for storage/transmission."""
213
return to_hex(text=text_string)
214
215
def decode_hex_to_string(hex_string):
216
"""Decode hex data back to text string."""
217
return to_text(hexstr=hex_string)
218
219
# Encode message
220
message = "Hello, Ethereum!"
221
encoded = encode_string_to_hex(message)
222
print(encoded) # 0x48656c6c6f2c20457468657265756d21
223
224
# Decode message
225
decoded = decode_hex_to_string(encoded)
226
print(decoded) # "Hello, Ethereum!"
227
```
228
229
## Input Validation Rules
230
231
The conversion functions enforce strict input validation:
232
233
1. **Exactly one input**: Must provide exactly one of `primitive`, `hexstr`, or `text`
234
2. **Type validation**: Inputs must match expected types for their parameter
235
3. **Format validation**: Hex strings must be valid hex, text must be valid UTF-8
236
4. **Range validation**: Values must be within acceptable ranges for target type
237
238
## Common Error Patterns
239
240
```python
241
from eth_utils import to_bytes, ValidationError
242
243
# Multiple inputs - raises TypeError
244
try:
245
to_bytes(primitive=123, hexstr="0x123")
246
except TypeError as e:
247
print("Cannot provide multiple inputs")
248
249
# No inputs - raises ValidationError
250
try:
251
to_bytes()
252
except ValidationError as e:
253
print("Must provide exactly one input")
254
255
# Invalid hex - raises ValidationError
256
try:
257
to_bytes(hexstr="0xGGG")
258
except ValidationError as e:
259
print("Invalid hex characters")
260
```