Skip to content

Commit 79b9748

Browse files
committed
style(python): improve code formatting across multiple files
1 parent 5005163 commit 79b9748

File tree

12 files changed

+128
-124
lines changed

12 files changed

+128
-124
lines changed

python/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@
77
__version__ = '1.0.0'
88
__author__ = 'Demo Project Team'
99

10-
from . import (algorithms, containers, exceptions, memory, random, shapes,
11-
timing)
10+
from . import algorithms, containers, exceptions, memory, random, shapes, timing
1211

1312
__all__ = [
1413
'algorithms',

python/containers.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,9 @@ def __init__(self, container_type: type[T], data: Iterable[T] | None = None):
3232
case int:
3333
self._container = _containers.IntContainer(list(data) if data else [])
3434
case float:
35-
self._container = _containers.DoubleContainer(
36-
list(data) if data else []
37-
)
35+
self._container = _containers.DoubleContainer(list(data) if data else [])
3836
case str:
39-
self._container = _containers.StringContainer(
40-
list(data) if data else []
41-
)
37+
self._container = _containers.StringContainer(list(data) if data else [])
4238
case _:
4339
raise ValueError(f'Unsupported container type: {container_type}')
4440

python/exceptions.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,7 @@ def ok(value: T) -> 'Result[T]':
201201
raise ValueError(f'Unsupported result type: {type(value)}')
202202

203203
@staticmethod
204-
def error(
205-
message: str, severity: ErrorSeverity = ErrorSeverity.ERROR
206-
) -> 'Result[Any]':
204+
def error(message: str, severity: ErrorSeverity = ErrorSeverity.ERROR) -> 'Result[Any]':
207205
"""Create an error Result.
208206
209207
Parameters

python/shapes.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,9 +97,7 @@ def create_shape(shape_type: str | ShapeType, *args: float) -> _shapes.Shape:
9797

9898
case ShapeType.RECTANGLE | 'rectangle':
9999
if len(args) != 2:
100-
raise ValueError(
101-
'Rectangle requires exactly 2 arguments (width, height)'
102-
)
100+
raise ValueError('Rectangle requires exactly 2 arguments (width, height)')
103101
return _shapes.create_rectangle(args[0], args[1])
104102

105103
case ShapeType.SQUARE | 'square':

python/timing.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -207,14 +207,10 @@ def get_statistics(self) -> dict[str, Any]:
207207
'median_ms': statistics.median(measurements_ms),
208208
'min_ms': min(measurements_ms),
209209
'max_ms': max(measurements_ms),
210-
'stdev_ms': (
211-
statistics.stdev(measurements_ms) if len(measurements_ms) > 1 else 0.0
212-
),
210+
'stdev_ms': (statistics.stdev(measurements_ms) if len(measurements_ms) > 1 else 0.0),
213211
'measurements_ns': self.measurements.copy(),
214212
'human_readable': {
215-
'mean': _timing.to_human_readable(
216-
int(statistics.mean(self.measurements))
217-
),
213+
'mean': _timing.to_human_readable(int(statistics.mean(self.measurements))),
218214
'min': _timing.to_human_readable(min(self.measurements)),
219215
'max': _timing.to_human_readable(max(self.measurements)),
220216
},

python_examples/advanced_usage.py

Lines changed: 31 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
# Add the python module to the path
1212
sys.path.insert(0, str(Path(__file__).parent.parent / 'python'))
1313

14-
from python import (algorithms, containers, exceptions, memory, random, shapes,
15-
timing)
14+
from python import algorithms, containers, exceptions, memory, random, shapes, timing
1615

1716

1817
class ShapeAnalyzer:
@@ -68,8 +67,7 @@ def create_shapes():
6867

6968
# Transform for efficiency ratios (area/perimeter)
7069
efficiency_ratios = algorithms.transform(
71-
list(zip(areas, perimeters)),
72-
lambda ap: ap[0] / ap[1] if ap[1] > 0 else 0
70+
list(zip(areas, perimeters)), lambda ap: ap[0] / ap[1] if ap[1] > 0 else 0
7371
)
7472

7573
self.operation_count += 1
@@ -81,10 +79,10 @@ def create_shapes():
8179
'statistics': {
8280
'large_shapes': large_shapes,
8381
'complex_shapes': complex_shapes,
84-
'avg_efficiency': sum(efficiency_ratios) / len(efficiency_ratios)
82+
'avg_efficiency': sum(efficiency_ratios) / len(efficiency_ratios),
8583
},
8684
'creation_time': creation_stats['human_readable']['mean'],
87-
'operation_count': self.operation_count
85+
'operation_count': self.operation_count,
8886
}
8987

9088

@@ -125,7 +123,7 @@ def safe_statistical_analysis(squares):
125123
'max': max_val,
126124
'median': squares[len(squares) // 2],
127125
'sum': sum(squares),
128-
'large_values': algorithms.count_if(squares, lambda x: x > 1000)
126+
'large_values': algorithms.count_if(squares, lambda x: x > 1000),
129127
}
130128

131129
# Execute pipeline
@@ -174,12 +172,13 @@ def benchmark_sorting_algorithms(self) -> dict:
174172
'large_random': lambda: random.RandomGenerator(42).integers(1, 1000, 1000),
175173
'already_sorted': lambda: list(range(1, 501)),
176174
'reverse_sorted': lambda: list(range(500, 0, -1)),
177-
'mostly_sorted': lambda: list(range(1, 500)) + [499, 498, 497]
175+
'mostly_sorted': lambda: list(range(1, 500)) + [499, 498, 497],
178176
}
179177

180178
results = {}
181179

182180
for scenario_name, data_gen in scenarios.items():
181+
183182
def sort_test():
184183
data = data_gen()
185184
algorithms.sort_inplace(data)
@@ -189,7 +188,7 @@ def sort_test():
189188
results[scenario_name] = {
190189
'mean_time': stats['human_readable']['mean'],
191190
'iterations': stats['iterations'],
192-
'data_size': len(data_gen())
191+
'data_size': len(data_gen()),
193192
}
194193

195194
return results
@@ -217,7 +216,7 @@ def mixed_operations():
217216
operations = {
218217
'filter': filter_operation,
219218
'transform': transform_operation,
220-
'mixed': mixed_operations
219+
'mixed': mixed_operations,
221220
}
222221

223222
results = {}
@@ -250,7 +249,7 @@ def cleanup_heavy_operations():
250249

251250
operations = {
252251
'shape_creation': create_many_shapes,
253-
'cleanup_operations': cleanup_heavy_operations
252+
'cleanup_operations': cleanup_heavy_operations,
254253
}
255254

256255
results = {}
@@ -268,7 +267,7 @@ def run_full_benchmark(self) -> dict:
268267
self.results = {
269268
'sorting': self.benchmark_sorting_algorithms(),
270269
'containers': self.benchmark_container_operations(),
271-
'memory': self.benchmark_memory_management()
270+
'memory': self.benchmark_memory_management(),
272271
}
273272

274273
return self.results
@@ -289,8 +288,7 @@ def monte_carlo_pi_estimation(samples: int = 1000000) -> exceptions.Result[float
289288

290289
# Count points inside unit circle
291290
inside_circle = algorithms.count_if(
292-
list(zip(x_coords, y_coords)),
293-
lambda p: p[0]**2 + p[1]**2 <= 1.0
291+
list(zip(x_coords, y_coords)), lambda p: p[0] ** 2 + p[1] ** 2 <= 1.0
294292
)
295293

296294
# Estimate π
@@ -311,24 +309,26 @@ def advanced_functional_programming_example():
311309
data = gen.integers(1, 100, 50)
312310

313311
# Complex functional chain with multiple transformations
314-
result = (algorithms.functional_chain(data)
315-
.filter(lambda x: x % 3 == 0) # Divisible by 3
316-
.map(lambda x: x * x) # Square them
317-
.filter(lambda x: x < 1000) # Keep reasonable size
318-
.sort(reverse=True) # Sort descending
319-
.take(10) # Take top 10
320-
.map(lambda x: x / 9) # Divide by 9
321-
.collect())
312+
result = (
313+
algorithms.functional_chain(data)
314+
.filter(lambda x: x % 3 == 0) # Divisible by 3
315+
.map(lambda x: x * x) # Square them
316+
.filter(lambda x: x < 1000) # Keep reasonable size
317+
.sort(reverse=True) # Sort descending
318+
.take(10) # Take top 10
319+
.map(lambda x: x / 9) # Divide by 9
320+
.collect()
321+
)
322322

323323
print(f'Functional chain result: {result}')
324324

325325
# Pipeline composition
326326
numerical_pipeline = algorithms.pipeline(
327-
lambda nums: [x for x in nums if x > 20], # Filter
328-
lambda nums: [x * 2 for x in nums], # Double
327+
lambda nums: [x for x in nums if x > 20], # Filter
328+
lambda nums: [x * 2 for x in nums], # Double
329329
lambda nums: algorithms.transform(nums, lambda x: x + 1), # Add 1
330-
lambda nums: sorted(nums), # Sort
331-
lambda nums: nums[:5] # Take first 5
330+
lambda nums: sorted(nums), # Sort
331+
lambda nums: nums[:5], # Take first 5
332332
)
333333

334334
pipeline_result = numerical_pipeline(gen.integers(1, 50, 20))
@@ -342,6 +342,7 @@ def safe_logarithm(x: float) -> exceptions.Result[float]:
342342
if x <= 0:
343343
return exceptions.Result.error('Logarithm of non-positive number')
344344
import math
345+
345346
return exceptions.Result.ok(math.log(x))
346347

347348
# Chain safe operations
@@ -380,7 +381,9 @@ def real_world_simulation():
380381
print(f"Environment Analysis Results:")
381382
print(f" - Total shapes: {analysis['shape_count']}")
382383
print(f" - Area range: {analysis['areas']['min']:.2f} - {analysis['areas']['max']:.2f}")
383-
print(f" - Perimeter range: {analysis['perimeters']['min']:.2f} - {analysis['perimeters']['max']:.2f}")
384+
print(
385+
f" - Perimeter range: {analysis['perimeters']['min']:.2f} - {analysis['perimeters']['max']:.2f}"
386+
)
384387
print(f" - Large shapes (area > 50): {analysis['statistics']['large_shapes']}")
385388
print(f" - Complex shapes (perimeter > 20): {analysis['statistics']['complex_shapes']}")
386389
print(f" - Average efficiency ratio: {analysis['statistics']['avg_efficiency']:.4f}")
@@ -445,6 +448,7 @@ def main():
445448
except Exception as e:
446449
print(f'Error running advanced examples: {e}')
447450
import traceback
451+
448452
traceback.print_exc()
449453
return 1
450454

python_examples/basic_usage.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@
1010
# Add the python module to the path
1111
sys.path.insert(0, str(Path(__file__).parent.parent / 'python'))
1212

13-
from python import (algorithms, containers, exceptions, memory, random, shapes,
14-
timing)
13+
from python import algorithms, containers, exceptions, memory, random, shapes, timing
1514

1615

1716
def shapes_example():
@@ -93,19 +92,19 @@ def algorithms_example():
9392
print(f'Min: {min_val}, Max: {max_val}')
9493

9594
# Functional chain
96-
result = (algorithms.functional_chain([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
97-
.filter(lambda x: x % 2 == 0)
98-
.map(lambda x: x * x)
99-
.take(3)
100-
.collect())
95+
result = (
96+
algorithms.functional_chain([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
97+
.filter(lambda x: x % 2 == 0)
98+
.map(lambda x: x * x)
99+
.take(3)
100+
.collect()
101+
)
101102

102103
print(f'Functional chain result: {result}')
103104

104105
# Pipeline
105106
process = algorithms.pipeline(
106-
lambda lst: [x for x in lst if x > 3],
107-
lambda lst: [x * 2 for x in lst],
108-
sum
107+
lambda lst: [x for x in lst if x > 3], lambda lst: [x * 2 for x in lst], sum
109108
)
110109

111110
pipeline_result = process([1, 2, 3, 4, 5, 6])
@@ -123,6 +122,7 @@ def memory_example():
123122
def cleanup_function(name: str):
124123
def cleanup():
125124
cleanup_log.append(f'Cleaned up {name}')
125+
126126
return cleanup
127127

128128
# Using resource manager as context manager
@@ -301,10 +301,7 @@ def integration_example():
301301
# Time a complex operation
302302
with timing.Timer() as timer:
303303
# Complex calculation involving all shapes
304-
total_complexity = sum(
305-
shape.get_area() * shape.get_perimeter()
306-
for shape in all_shapes
307-
)
304+
total_complexity = sum(shape.get_area() * shape.get_perimeter() for shape in all_shapes)
308305

309306
print(f'Complex calculation result: {total_complexity:.2f}')
310307
print(f'Calculation time: {timer.elapsed_string}')
@@ -339,6 +336,7 @@ def main():
339336
except Exception as e:
340337
print(f'Error running examples: {e}')
341338
import traceback
339+
342340
traceback.print_exc()
343341
return 1
344342

0 commit comments

Comments
 (0)