or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

arrays.mdchaining.mdcollections.mdfunctions.mdindex.mdnumerical.mdobjects.mdpredicates.mdstrings.mdutilities.md

functions.mddocs/

0

# Functions Module

1

2

The Functions module provides 30 functions for higher-order function manipulation and utilities. These functions enable function composition, partial application, argument transformation, and execution control patterns common in functional programming.

3

4

## Function Composition

5

6

### flow

7

8

```python { .api }

9

def flow(*funcs: Callable) -> Callable

10

```

11

12

Creates a function that is the composition of the provided functions, where each successive invocation is supplied the return value of the previous.

13

14

**Parameters:**

15

- `funcs` (`*Callable`): Functions to compose.

16

17

**Returns:**

18

- `Callable`: New composite function.

19

20

**Example:**

21

```python { .api }

22

from pydash import flow

23

24

add = lambda x, y: x + y

25

square = lambda x: x ** 2

26

add_square = flow(add, square)

27

28

add_square(1, 2) # square(add(1, 2)) = square(3) = 9

29

```

30

31

### flow_right

32

33

```python { .api }

34

def flow_right(*funcs: Callable) -> Callable

35

```

36

37

Like `flow` except that it creates a function composition where arguments are applied from right to left.

38

39

**Parameters:**

40

- `funcs` (`*Callable`): Functions to compose.

41

42

**Returns:**

43

- `Callable`: New composite function.

44

45

**Example:**

46

```python { .api }

47

from pydash import flow_right

48

49

add = lambda x, y: x + y

50

square = lambda x: x ** 2

51

square_add = flow_right(add, square)

52

53

square_add(1, 2) # add(square(1), 2) = add(1, 2) = 3

54

```

55

56

### over_args

57

58

```python { .api }

59

def over_args(func: Callable, *transforms: Callable) -> Callable

60

```

61

62

Creates a function that invokes `func` with its arguments transformed by the corresponding `transforms`.

63

64

**Parameters:**

65

- `func` (`Callable`): Function to wrap.

66

- `transforms` (`*Callable`): Argument transforms.

67

68

**Returns:**

69

- `Callable`: New function.

70

71

**Example:**

72

```python { .api }

73

from pydash import over_args

74

75

def greet(greeting, name):

76

return f"{greeting} {name}"

77

78

say_hello = over_args(greet, str.upper, str.capitalize)

79

say_hello('hello', 'world')

80

# 'HELLO World'

81

```

82

83

## Function Arity Control

84

85

### ary

86

87

```python { .api }

88

def ary(func: Callable, n: int = None) -> Callable

89

```

90

91

Creates a function that invokes `func` with up to `n` arguments, ignoring any additional arguments.

92

93

**Parameters:**

94

- `func` (`Callable`): Function to cap arguments for.

95

- `n` (`int`, optional): Arity cap.

96

97

**Returns:**

98

- `Callable`: New capped function.

99

100

**Example:**

101

```python { .api }

102

from pydash import ary

103

104

def add_three(a, b, c):

105

return a + b + c

106

107

add_two = ary(add_three, 2)

108

add_two(1, 2, 3, 4, 5) # Only uses first 2 args: 1 + 2 + undefined = 3

109

```

110

111

### unary

112

113

```python { .api }

114

def unary(func: Callable) -> Callable

115

```

116

117

Creates a function that accepts up to one argument, ignoring any additional arguments.

118

119

**Parameters:**

120

- `func` (`Callable`): Function to cap arguments for.

121

122

**Returns:**

123

- `Callable`: New capped function.

124

125

**Example:**

126

```python { .api }

127

from pydash import unary

128

129

# Useful with map when you only want the first argument

130

numbers = ['1', '2', '3']

131

list(map(unary(int), numbers)) # [1, 2, 3]

132

# Without unary, int would receive index as second argument

133

```

134

135

### negate

136

137

```python { .api }

138

def negate(predicate: Callable) -> Callable

139

```

140

141

Creates a function that negates the result of the predicate `func`.

142

143

**Parameters:**

144

- `predicate` (`Callable`): Predicate to negate.

145

146

**Returns:**

147

- `Callable`: New negated function.

148

149

**Example:**

150

```python { .api }

151

from pydash import negate

152

153

is_even = lambda x: x % 2 == 0

154

is_odd = negate(is_even)

155

156

is_odd(3) # True

157

is_odd(4) # False

158

```

159

160

### rearg

161

162

```python { .api }

163

def rearg(func: Callable, *indexes: int) -> Callable

164

```

165

166

Creates a function that invokes `func` with arguments arranged according to the specified `indexes`.

167

168

**Parameters:**

169

- `func` (`Callable`): Function to rearrange arguments for.

170

- `indexes` (`*int`): Arranged argument indexes.

171

172

**Returns:**

173

- `Callable`: New function.

174

175

**Example:**

176

```python { .api }

177

from pydash import rearg

178

179

def greet(greeting, fname, lname):

180

return f"{greeting} {fname} {lname}"

181

182

say_hello = rearg(greet, 1, 2, 0)

183

say_hello('hello', 'john', 'doe')

184

# 'john doe hello'

185

```

186

187

## Function Invocation Control

188

189

### after

190

191

```python { .api }

192

def after(n: int, func: Callable) -> Callable

193

```

194

195

Creates a function that invokes `func` once it's called `n` or more times.

196

197

**Parameters:**

198

- `n` (`int`): Number of calls before `func` is invoked.

199

- `func` (`Callable`): Function to restrict.

200

201

**Returns:**

202

- `Callable`: New restricted function.

203

204

**Example:**

205

```python { .api }

206

from pydash import after

207

208

saves = ['profile', 'settings']

209

done = after(len(saves), lambda: print('done saving!'))

210

211

# Call done for each save operation

212

for save in saves:

213

print(f'saving {save}')

214

done() # Only prints 'done saving!' after all calls

215

```

216

217

### before

218

219

```python { .api }

220

def before(n: int, func: Callable) -> Callable

221

```

222

223

Creates a function that invokes `func` while it's called less than `n` times.

224

225

**Parameters:**

226

- `n` (`int`): Number of calls at which `func` is no longer invoked.

227

- `func` (`Callable`): Function to restrict.

228

229

**Returns:**

230

- `Callable`: New restricted function.

231

232

**Example:**

233

```python { .api }

234

from pydash import before

235

236

add_one = lambda x: x + 1

237

add_one_twice = before(3, add_one)

238

239

add_one_twice(1) # 2

240

add_one_twice(1) # 2

241

add_one_twice(1) # 2 (function not called, returns last result)

242

```

243

244

### once

245

246

```python { .api }

247

def once(func: Callable) -> Callable

248

```

249

250

Creates a function that is restricted to invoking `func` once. Repeat calls to the function return the value of the first invocation.

251

252

**Parameters:**

253

- `func` (`Callable`): Function to restrict.

254

255

**Returns:**

256

- `Callable`: New restricted function.

257

258

**Example:**

259

```python { .api }

260

from pydash import once

261

262

initialize = once(lambda: print('Initialized!'))

263

initialize() # 'Initialized!'

264

initialize() # (no output, returns cached result)

265

```

266

267

### debounce

268

269

```python { .api }

270

def debounce(func: Callable, wait: int, immediate: bool = False) -> Callable

271

```

272

273

Creates a debounced function that delays invoking `func` until after `wait` milliseconds have elapsed since the last time the debounced function was invoked.

274

275

**Parameters:**

276

- `func` (`Callable`): Function to debounce.

277

- `wait` (`int`): Milliseconds to delay.

278

- `immediate` (`bool`): Specify invoking on the leading edge of timeout. Defaults to `False`.

279

280

**Returns:**

281

- `Callable`: New debounced function.

282

283

**Example:**

284

```python { .api }

285

from pydash import debounce

286

import time

287

288

# Debounce expensive operation

289

save_input = debounce(lambda x: print(f'Saving: {x}'), 1000)

290

291

save_input('a')

292

save_input('ab')

293

save_input('abc') # Only this call will execute after 1 second delay

294

```

295

296

### throttle

297

298

```python { .api }

299

def throttle(func: Callable, wait: int) -> Callable

300

```

301

302

Creates a throttled function that only invokes `func` at most once per every `wait` milliseconds.

303

304

**Parameters:**

305

- `func` (`Callable`): Function to throttle.

306

- `wait` (`int`): Milliseconds to throttle invocations to.

307

308

**Returns:**

309

- `Callable`: New throttled function.

310

311

**Example:**

312

```python { .api }

313

from pydash import throttle

314

315

# Throttle scroll handler

316

handle_scroll = throttle(lambda: print('Scrolling!'), 100)

317

318

# Even if called rapidly, only executes every 100ms

319

for i in range(10):

320

handle_scroll()

321

```

322

323

## Partial Application Functions

324

325

### curry

326

327

```python { .api }

328

def curry(func: Callable, arity: int = None) -> Callable

329

```

330

331

Creates a curried version of `func` which accepts arguments of `func` and either invokes `func` returning its result, if at least `arity` number of arguments have been provided, or returns a function that accepts the remaining arguments.

332

333

**Parameters:**

334

- `func` (`Callable`): Function to curry.

335

- `arity` (`int`, optional): Arity of `func`.

336

337

**Returns:**

338

- `Callable`: New curried function.

339

340

**Example:**

341

```python { .api }

342

from pydash import curry

343

344

def add_three(a, b, c):

345

return a + b + c

346

347

curried_add = curry(add_three)

348

349

# Can be called multiple ways:

350

curried_add(1)(2)(3) # 6

351

curried_add(1, 2)(3) # 6

352

curried_add(1)(2, 3) # 6

353

curried_add(1, 2, 3) # 6

354

```

355

356

### curry_right

357

358

```python { .api }

359

def curry_right(func: Callable, arity: int = None) -> Callable

360

```

361

362

Like `curry` except that arguments are applied to `func` in the manner of `partial_right` instead of `partial`.

363

364

**Parameters:**

365

- `func` (`Callable`): Function to curry.

366

- `arity` (`int`, optional): Arity of `func`.

367

368

**Returns:**

369

- `Callable`: New curried function.

370

371

**Example:**

372

```python { .api }

373

from pydash import curry_right

374

375

def divide(a, b):

376

return a / b

377

378

divide_by = curry_right(divide)

379

divide_by_2 = divide_by(2)

380

381

divide_by_2(10) # 10 / 2 = 5

382

```

383

384

### partial

385

386

```python { .api }

387

def partial(func: Callable, *args: Any, **kwargs: Any) -> Callable

388

```

389

390

Creates a function that invokes `func` with `args` prepended to the arguments it receives.

391

392

**Parameters:**

393

- `func` (`Callable`): Function to partially apply arguments to.

394

- `args` (`*Any`): Arguments to prepend.

395

- `kwargs` (`**Any`): Keyword arguments to prepend.

396

397

**Returns:**

398

- `Callable`: New partially applied function.

399

400

**Example:**

401

```python { .api }

402

from pydash import partial

403

404

def greet(greeting, name):

405

return f"{greeting} {name}!"

406

407

say_hello = partial(greet, 'Hello')

408

say_hello('World') # 'Hello World!'

409

410

say_hi = partial(greet, greeting='Hi')

411

say_hi('Python') # 'Hi Python!'

412

```

413

414

### partial_right

415

416

```python { .api }

417

def partial_right(func: Callable, *args: Any) -> Callable

418

```

419

420

Like `partial` except that arguments are appended to those provided to the new function.

421

422

**Parameters:**

423

- `func` (`Callable`): Function to partially apply arguments to.

424

- `args` (`*Any`): Arguments to append.

425

426

**Returns:**

427

- `Callable`: New partially applied function.

428

429

**Example:**

430

```python { .api }

431

from pydash import partial_right

432

433

def greet(greeting, name):

434

return f"{greeting} {name}!"

435

436

greet_world = partial_right(greet, 'World')

437

greet_world('Hello') # 'Hello World!'

438

```

439

440

## Function Transformation

441

442

### conjoin

443

444

```python { .api }

445

def conjoin(*predicates: Callable) -> Callable

446

```

447

448

Creates a function that is the logical AND of the provided predicates.

449

450

**Parameters:**

451

- `predicates` (`*Callable`): Predicates to check.

452

453

**Returns:**

454

- `Callable`: New conjoined function.

455

456

**Example:**

457

```python { .api }

458

from pydash import conjoin

459

460

is_positive = lambda x: x > 0

461

is_even = lambda x: x % 2 == 0

462

is_positive_even = conjoin(is_positive, is_even)

463

464

is_positive_even(4) # True (positive AND even)

465

is_positive_even(-2) # False (not positive)

466

is_positive_even(3) # False (not even)

467

```

468

469

### disjoin

470

471

```python { .api }

472

def disjoin(*predicates: Callable) -> Callable

473

```

474

475

Creates a function that is the logical OR of the provided predicates.

476

477

**Parameters:**

478

- `predicates` (`*Callable`): Predicates to check.

479

480

**Returns:**

481

- `Callable`: New disjoined function.

482

483

**Example:**

484

```python { .api }

485

from pydash import disjoin

486

487

is_string = lambda x: isinstance(x, str)

488

is_number = lambda x: isinstance(x, (int, float))

489

is_string_or_number = disjoin(is_string, is_number)

490

491

is_string_or_number('hello') # True

492

is_string_or_number(42) # True

493

is_string_or_number([]) # False

494

```

495

496

### flip

497

498

```python { .api }

499

def flip(func: Callable) -> Callable

500

```

501

502

Creates a function that invokes `func` with arguments reversed.

503

504

**Parameters:**

505

- `func` (`Callable`): Function to flip arguments for.

506

507

**Returns:**

508

- `Callable`: New flipped function.

509

510

**Example:**

511

```python { .api }

512

from pydash import flip

513

514

def divide(a, b):

515

return a / b

516

517

flipped_divide = flip(divide)

518

flipped_divide(2, 10) # 10 / 2 = 5

519

```

520

521

### spread

522

523

```python { .api }

524

def spread(func: Callable) -> Callable

525

```

526

527

Creates a function that invokes `func` with the array argument spread as individual arguments.

528

529

**Parameters:**

530

- `func` (`Callable`): Function to spread arguments for.

531

532

**Returns:**

533

- `Callable`: New function.

534

535

**Example:**

536

```python { .api }

537

from pydash import spread

538

539

def add_three(a, b, c):

540

return a + b + c

541

542

spread_add = spread(add_three)

543

spread_add([1, 2, 3]) # 6

544

```

545

546

### wrap

547

548

```python { .api }

549

def wrap(value: Any, wrapper: Callable) -> Callable

550

```

551

552

Creates a function that provides `value` to `wrapper` as its first argument. Additional arguments provided to the function are appended to those provided to the `wrapper`.

553

554

**Parameters:**

555

- `value` (`Any`): Value to wrap.

556

- `wrapper` (`Callable`): Wrapper function.

557

558

**Returns:**

559

- `Callable`: New wrapped function.

560

561

**Example:**

562

```python { .api }

563

from pydash import wrap

564

565

greet = lambda name: f"Hello {name}!"

566

wrapped_greet = wrap(greet, lambda func, name: func(name).upper())

567

568

wrapped_greet('world') # 'HELLO WORLD!'

569

```

570

571

## Advanced Function Utilities

572

573

### delay

574

575

```python { .api }

576

def delay(func: Callable, wait: int, *args: Any, **kwargs: Any) -> Any

577

```

578

579

Invokes `func` after `wait` milliseconds. Any additional arguments are provided to `func` when it's invoked.

580

581

**Parameters:**

582

- `func` (`Callable`): Function to delay.

583

- `wait` (`int`): Milliseconds to delay invocation.

584

- `args` (`*Any`): Arguments to invoke `func` with.

585

- `kwargs` (`**Any`): Keyword arguments to invoke `func` with.

586

587

**Returns:**

588

- `Any`: Timer object that can be used to cancel the delayed invocation.

589

590

**Example:**

591

```python { .api }

592

from pydash import delay

593

594

def say_hello(name):

595

print(f'Hello {name}!')

596

597

# Delay execution by 1000ms

598

timer = delay(say_hello, 1000, 'World')

599

```

600

601

### iterated

602

603

```python { .api }

604

def iterated(func: Callable, n: int) -> Callable

605

```

606

607

Creates a function that applies `func` `n` times to its argument.

608

609

**Parameters:**

610

- `func` (`Callable`): Function to iterate.

611

- `n` (`int`): Number of times to iterate function.

612

613

**Returns:**

614

- `Callable`: New iterated function.

615

616

**Example:**

617

```python { .api }

618

from pydash import iterated

619

620

add_one = lambda x: x + 1

621

add_five = iterated(add_one, 5)

622

623

add_five(0) # 5 (adds 1 five times)

624

```

625

626

### juxtapose

627

628

```python { .api }

629

def juxtapose(*funcs: Callable) -> Callable

630

```

631

632

Creates a function whose return value is a list of the results of calling each provided function with the supplied arguments.

633

634

**Parameters:**

635

- `funcs` (`*Callable`): Functions to juxtapose.

636

637

**Returns:**

638

- `Callable`: New juxtaposed function.

639

640

**Example:**

641

```python { .api }

642

from pydash import juxtapose

643

644

def add_one(x):

645

return x + 1

646

647

def multiply_two(x):

648

return x * 2

649

650

def square(x):

651

return x ** 2

652

653

multi_math = juxtapose(add_one, multiply_two, square)

654

multi_math(3) # [4, 6, 9]

655

```

656

657

## Usage Examples

658

659

### Function Composition Pipelines

660

```python { .api }

661

from pydash import flow, partial

662

663

# Data processing pipeline

664

def clean_data(data):

665

return [x.strip().lower() for x in data if x.strip()]

666

667

def validate_data(data):

668

return [x for x in data if len(x) > 2]

669

670

def transform_data(data):

671

return [x.title() for x in data]

672

673

# Create processing pipeline

674

process_data = flow(clean_data, validate_data, transform_data)

675

676

raw_data = [' hello ', '', 'WORLD', ' hi ', 'bye']

677

result = process_data(raw_data) # ['Hello', 'World']

678

```

679

680

### Event Handling with Debouncing and Throttling

681

```python { .api }

682

from pydash import debounce, throttle, once

683

684

# Debounced search (wait for user to stop typing)

685

def perform_search(query):

686

print(f"Searching for: {query}")

687

688

debounced_search = debounce(perform_search, 300)

689

690

# Throttled scroll handler (limit execution rate)

691

def update_scroll_position():

692

print("Updating scroll position")

693

694

throttled_scroll = throttle(update_scroll_position, 16) # ~60fps

695

696

# One-time initialization

697

def initialize_app():

698

print("App initialized!")

699

700

init_once = once(initialize_app)

701

```

702

703

### Currying and Partial Application

704

```python { .api }

705

from pydash import curry, partial, partial_right

706

707

# Curried logging function

708

@curry

709

def log_message(level, category, message):

710

return f"[{level}] {category}: {message}"

711

712

# Create specialized loggers

713

error_log = log_message('ERROR')

714

warn_db = log_message('WARN', 'DATABASE')

715

716

# Use them

717

error_log('AUTH', 'Invalid token') # [ERROR] AUTH: Invalid token

718

warn_db('Connection timeout') # [WARN] DATABASE: Connection timeout

719

720

# Partial application for API configuration

721

def api_request(method, endpoint, data=None, headers=None):

722

return f"{method} {endpoint} with {data} and {headers}"

723

724

# Create specialized request functions

725

get_request = partial(api_request, 'GET')

726

post_user = partial_right(api_request, headers={'Content-Type': 'application/json'})

727

```

728

729

### Predicate Composition

730

```python { .api }

731

from pydash import conjoin, disjoin, negate

732

733

# Define basic predicates

734

is_adult = lambda person: person.get('age', 0) >= 18

735

is_verified = lambda person: person.get('verified', False)

736

is_premium = lambda person: person.get('premium', False)

737

738

# Compose complex predicates

739

can_access_content = conjoin(is_adult, is_verified)

740

has_special_access = disjoin(is_premium, conjoin(is_adult, is_verified))

741

is_restricted = negate(can_access_content)

742

743

# Use composed predicates

744

user = {'age': 25, 'verified': True, 'premium': False}

745

can_access_content(user) # True

746

has_special_access(user) # True

747

is_restricted(user) # False

748

```

749

750

This Functions module provides comprehensive higher-order function utilities with 24 functions enabling sophisticated functional programming patterns including composition, partial application, execution control, and function transformation.