Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

""" 

Decorators 

 

Python decorators for use in Sage. 

 

AUTHORS: 

 

- Tim Dumol (5 Dec 2009) -- initial version. 

- Johan S. R. Nielsen (2010) -- collect decorators from various modules. 

- Johan S. R. Nielsen (8 apr 2011) -- improve introspection on decorators. 

- Simon King (2011-05-26) -- improve introspection of sage_wraps. Put this 

file into the reference manual. 

- Julian Rueth (2014-03-19): added ``decorator_keywords`` decorator 

 

""" 

#***************************************************************************** 

# Copyright (C) 2009 Tim Dumol 

# 2010,2011 Johan S. R. Nielsen 

# 2011 Simon King <simon.king@uni-jena.de> 

# 2014 Julian Rueth <julian.rueth@fsfe.org> 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 2 of the License, or 

# (at your option) any later version. 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

from __future__ import print_function 

 

from functools import (partial, update_wrapper, WRAPPER_ASSIGNMENTS, 

WRAPPER_UPDATES) 

from copy import copy 

from sage.misc.sageinspect import (sage_getsource, sage_getsourcelines, 

sage_getargspec) 

from inspect import ArgSpec 

 

 

def sage_wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES): 

r""" 

Decorator factory which should be used in decorators for making sure that 

meta-information on the decorated callables are retained through the 

decorator, such that the introspection functions of 

``sage.misc.sageinspect`` retrieves them correctly. This includes 

documentation string, source, and argument specification. This is an 

extension of the Python standard library decorator functools.wraps. 

 

That the argument specification is retained from the decorated functions 

implies, that if one uses ``sage_wraps`` in a decorator which intentionally 

changes the argument specification, one should add this information to 

the special attribute ``_sage_argspec_`` of the wrapping function (for an 

example, see e.g. ``@options`` decorator in this module). 

 

EXAMPLES: 

 

Demonstrate that documentation string and source are retained from the 

decorated function:: 

 

sage: def square(f): 

....: @sage_wraps(f) 

....: def new_f(x): 

....: return f(x)*f(x) 

....: return new_f 

sage: @square 

....: def g(x): 

....: "My little function" 

....: return x 

sage: g(2) 

4 

sage: g(x) 

x^2 

sage: g.__doc__ 

'My little function' 

sage: from sage.misc.sageinspect import sage_getsource, sage_getsourcelines, sage_getfile 

sage: sage_getsource(g) 

'@square...def g(x)...' 

 

Demonstrate that the argument description are retained from the 

decorated function through the special method (when left 

unchanged) (see :trac:`9976`):: 

 

sage: def diff_arg_dec(f): 

....: @sage_wraps(f) 

....: def new_f(y, some_def_arg=2): 

....: return f(y+some_def_arg) 

....: return new_f 

sage: @diff_arg_dec 

....: def g(x): 

....: return x 

sage: g(1) 

3 

sage: g(1, some_def_arg=4) 

5 

sage: from sage.misc.sageinspect import sage_getargspec 

sage: sage_getargspec(g) 

ArgSpec(args=['x'], varargs=None, keywords=None, defaults=None) 

 

Demonstrate that it correctly gets the source lines and the source 

file, which is essential for interactive code edition; note that we 

do not test the line numbers, as they may easily change:: 

 

sage: P.<x,y> = QQ[] 

sage: I = P*[x,y] 

sage: sage_getfile(I.interreduced_basis) 

'.../sage/interfaces/singular.py' 

sage: sage_getsourcelines(I.interreduced_basis) 

([' @singular_gb_standard_options\n', 

' @libsingular_gb_standard_options\n', 

' def interreduced_basis(self):\n', 

... 

' return self.basis.reduced()\n'], ...) 

 

The ``f`` attribute of the decorated function refers to the 

original function:: 

 

sage: foo = object() 

sage: @sage_wraps(foo) 

....: def func(): 

....: pass 

sage: wrapped = sage_wraps(foo)(func) 

sage: wrapped.f is foo 

True 

 

Demonstrate that sage_wraps works for non-function callables 

(:trac:`9919`):: 

 

sage: def square_for_met(f): 

....: @sage_wraps(f) 

....: def new_f(self, x): 

....: return f(self,x)*f(self,x) 

....: return new_f 

sage: class T: 

....: @square_for_met 

....: def g(self, x): 

....: "My little method" 

....: return x 

sage: t = T() 

sage: t.g(2) 

4 

sage: t.g.__doc__ 

'My little method' 

 

The bug described in :trac:`11734` is fixed:: 

 

sage: def square(f): 

....: @sage_wraps(f) 

....: def new_f(x): 

....: return f(x)*f(x) 

....: return new_f 

sage: f = lambda x:x^2 

sage: g = square(f) 

sage: g(3) # this line used to fail for some people if these command were manually entered on the sage prompt 

81 

 

""" 

#TRAC 9919: Workaround for bug in @update_wrapper when used with 

#non-function callables. 

assigned = set(assigned).intersection(set(dir(wrapped))) 

#end workaround 

 

def f(wrapper): 

update_wrapper(wrapper, wrapped, assigned=assigned, updated=updated) 

wrapper.f = wrapped 

wrapper._sage_src_ = lambda: sage_getsource(wrapped) 

wrapper._sage_src_lines_ = lambda: sage_getsourcelines(wrapped) 

#Getting the signature right in documentation by Sphinx (Trac 9976) 

#The attribute _sage_argspec_() is read by Sphinx if present and used 

#as the argspec of the function instead of using reflection. 

wrapper._sage_argspec_ = lambda: sage_getargspec(wrapped) 

return wrapper 

return f 

 

 

# Infix operator decorator 

class infix_operator(object): 

""" 

A decorator for functions which allows for a hack that makes 

the function behave like an infix operator. 

 

This decorator exists as a convenience for interactive use. 

 

EXAMPLES: 

 

An infix dot product operator:: 

 

sage: def dot(a,b): return a.dot_product(b) 

sage: dot=infix_operator('multiply')(dot) 

sage: u=vector([1,2,3]) 

sage: v=vector([5,4,3]) 

sage: u *dot* v 

22 

 

An infix element-wise addition operator:: 

 

sage: def eadd(a,b): 

....: return a.parent([i+j for i,j in zip(a,b)]) 

sage: eadd=infix_operator('add')(eadd) 

sage: u=vector([1,2,3]) 

sage: v=vector([5,4,3]) 

sage: u +eadd+ v 

(6, 6, 6) 

sage: 2*u +eadd+ v 

(7, 8, 9) 

 

A hack to simulate a postfix operator:: 

 

sage: def thendo(a,b): return b(a) 

sage: thendo=infix_operator('or')(thendo) 

sage: x |thendo| cos |thendo| (lambda x: x^2) 

cos(x)^2 

""" 

 

def __init__(self, precedence): 

""" 

A decorator for functions which allows for a hack that makes 

the function behave like an infix operator. 

 

This decorator exists as a convenience for interactive use. 

 

EXAMPLES:: 

 

sage: def dot(a,b): return a.dot_product(b) 

sage: dot=infix_operator('multiply')(dot) 

sage: u=vector([1,2,3]) 

sage: v=vector([5,4,3]) 

sage: u *dot* v 

22 

 

sage: from sage.misc.decorators import infix_operator 

sage: def eadd(a,b): 

....: return a.parent([i+j for i,j in zip(a,b)]) 

sage: eadd=infix_operator('add')(eadd) 

sage: u=vector([1,2,3]) 

sage: v=vector([5,4,3]) 

sage: u +eadd+ v 

(6, 6, 6) 

sage: 2*u +eadd+ v 

(7, 8, 9) 

 

sage: from sage.misc.decorators import infix_operator 

sage: def thendo(a,b): return b(a) 

sage: thendo=infix_operator('or')(thendo) 

sage: x |thendo| cos |thendo| (lambda x: x^2) 

cos(x)^2 

""" 

self.precedence = precedence 

 

operators = {'add': {'left': '__add__', 'right': '__radd__'}, 

'multiply': {'left': '__mul__', 'right': '__rmul__'}, 

'or': {'left': '__or__', 'right': '__ror__'}, 

} 

 

def __call__(self, func): 

""" 

Returns a function which acts as an inline operator. 

 

EXAMPLES:: 

 

sage: from sage.misc.decorators import infix_operator 

sage: def dot(a,b): return a.dot_product(b) 

sage: dot=infix_operator('multiply')(dot) 

sage: u=vector([1,2,3]) 

sage: v=vector([5,4,3]) 

sage: u *dot* v 

22 

 

sage: def eadd(a,b): 

....: return a.parent([i+j for i,j in zip(a,b)]) 

sage: eadd=infix_operator('add')(eadd) 

sage: u=vector([1,2,3]) 

sage: v=vector([5,4,3]) 

sage: u +eadd+ v 

(6, 6, 6) 

sage: 2*u +eadd+ v 

(7, 8, 9) 

 

sage: def thendo(a,b): return b(a) 

sage: thendo=infix_operator('or')(thendo) 

sage: x |thendo| cos |thendo| (lambda x: x^2) 

cos(x)^2 

""" 

def left_func(self, right): 

""" 

The function for the operation on the left (e.g., __add__). 

 

EXAMPLES:: 

 

sage: def dot(a,b): return a.dot_product(b) 

sage: dot=infix_operator('multiply')(dot) 

sage: u=vector([1,2,3]) 

sage: v=vector([5,4,3]) 

sage: u *dot* v 

22 

""" 

 

if self.left is None: 

if self.right is None: 

new = copy(self) 

new.right = right 

return new 

else: 

raise SyntaxError("Infix operator already has its " 

"right argument") 

else: 

return self.function(self.left, right) 

 

def right_func(self, left): 

""" 

The function for the operation on the right (e.g., __radd__). 

 

EXAMPLES:: 

 

sage: def dot(a,b): return a.dot_product(b) 

sage: dot=infix_operator('multiply')(dot) 

sage: u=vector([1,2,3]) 

sage: v=vector([5,4,3]) 

sage: u *dot* v 

22 

""" 

if self.right is None: 

if self.left is None: 

new = copy(self) 

new.left = left 

return new 

else: 

raise SyntaxError("Infix operator already has its " 

"left argument") 

else: 

return self.function(left, self.right) 

 

@sage_wraps(func) 

class wrapper: 

def __init__(self, left=None, right=None): 

""" 

Initialize the actual infix object, with possibly a 

specified left and/or right operand. 

 

EXAMPLES:: 

 

sage: def dot(a,b): return a.dot_product(b) 

sage: dot=infix_operator('multiply')(dot) 

sage: u=vector([1,2,3]) 

sage: v=vector([5,4,3]) 

sage: u *dot* v 

22 

""" 

 

self.function = func 

self.left = left 

self.right = right 

 

def __call__(self, *args, **kwds): 

""" 

Call the passed function. 

 

EXAMPLES:: 

 

sage: def dot(a,b): return a.dot_product(b) 

sage: dot=infix_operator('multiply')(dot) 

sage: u=vector([1,2,3]) 

sage: v=vector([5,4,3]) 

sage: dot(u,v) 

22 

""" 

return self.function(*args, **kwds) 

 

setattr(wrapper, self.operators[self.precedence]['left'], left_func) 

setattr(wrapper, self.operators[self.precedence]['right'], right_func) 

 

wrapper._sage_src_ = lambda: sage_getsource(func) 

 

return wrapper() 

 

 

def decorator_defaults(func): 

""" 

This function allows a decorator to have default arguments. 

 

Normally, a decorator can be called with or without arguments. 

However, the two cases call for different types of return values. 

If a decorator is called with no parentheses, it should be run 

directly on the function. However, if a decorator is called with 

parentheses (i.e., arguments), then it should return a function 

that is then in turn called with the defined function as an 

argument. 

 

This decorator allows us to have these default arguments without 

worrying about the return type. 

 

EXAMPLES:: 

 

sage: from sage.misc.decorators import decorator_defaults 

sage: @decorator_defaults 

....: def my_decorator(f,*args,**kwds): 

....: print(kwds) 

....: print(args) 

....: print(f.__name__) 

 

sage: @my_decorator 

....: def my_fun(a,b): 

....: return a,b 

{} 

() 

my_fun 

sage: @my_decorator(3,4,c=1,d=2) 

....: def my_fun(a,b): 

....: return a,b 

{'c': 1, 'd': 2} 

(3, 4) 

my_fun 

""" 

@sage_wraps(func) 

def my_wrap(*args, **kwds): 

if len(kwds) == 0 and len(args) == 1: 

# call without parentheses 

return func(*args) 

else: 

return lambda f: func(f, *args, **kwds) 

return my_wrap 

 

 

class suboptions(object): 

def __init__(self, name, **options): 

""" 

A decorator for functions which collects all keywords 

starting with ``name+'_'`` and collects them into a dictionary 

which will be passed on to the wrapped function as a 

dictionary called ``name_options``. 

 

The keyword arguments passed into the constructor are taken 

to be default for the ``name_options`` dictionary. 

 

EXAMPLES:: 

 

sage: from sage.misc.decorators import suboptions 

sage: s = suboptions('arrow', size=2) 

sage: s.name 

'arrow_' 

sage: s.options 

{'size': 2} 

""" 

self.name = name + "_" 

self.options = options 

 

def __call__(self, func): 

""" 

Returns a wrapper around func 

 

EXAMPLES:: 

 

sage: from sage.misc.decorators import suboptions 

sage: def f(*args, **kwds): print(list(sorted(kwds.items()))) 

sage: f = suboptions('arrow', size=2)(f) 

sage: f(size=2) 

[('arrow_options', {'size': 2}), ('size', 2)] 

sage: f(arrow_size=3) 

[('arrow_options', {'size': 3})] 

sage: f(arrow_options={'size':4}) 

[('arrow_options', {'size': 4})] 

sage: f(arrow_options={'size':4}, arrow_size=5) 

[('arrow_options', {'size': 5})] 

 

Demonstrate that the introspected argument specification of the 

wrapped function is updated (see :trac:`9976`). 

 

sage: from sage.misc.sageinspect import sage_getargspec 

sage: sage_getargspec(f) 

ArgSpec(args=['arrow_size'], varargs='args', keywords='kwds', defaults=(2,)) 

""" 

@sage_wraps(func) 

def wrapper(*args, **kwds): 

suboptions = copy(self.options) 

suboptions.update(kwds.pop(self.name+"options", {})) 

 

#Collect all the relevant keywords in kwds 

#and put them in suboptions 

for key, value in kwds.items(): 

if key.startswith(self.name): 

suboptions[key[len(self.name):]] = value 

del kwds[key] 

 

kwds[self.name + "options"] = suboptions 

 

return func(*args, **kwds) 

 

#Add the options specified by @options to the signature of the wrapped 

#function in the Sphinx-generated documentation (Trac 9976), using the 

#special attribute _sage_argspec_ (see e.g. sage.misc.sageinspect) 

def argspec(): 

argspec = sage_getargspec(func) 

 

def listForNone(l): 

return l if not l is None else [] 

newArgs = [self.name + opt for opt in self.options.keys()] 

args = (argspec.args if not argspec.args is None else []) + newArgs 

defaults = (argspec.defaults if not argspec.defaults is None else ()) \ 

+ tuple(self.options.values()) 

#Note: argspec.defaults is not always a tuple for some reason 

return ArgSpec(args, argspec.varargs, argspec.keywords, defaults) 

wrapper._sage_argspec_ = argspec 

 

return wrapper 

 

 

class options(object): 

def __init__(self, **options): 

""" 

A decorator for functions which allows for default options to be 

set and reset by the end user. Additionally, if one needs to, one 

can get at the original keyword arguments passed into the 

decorator. 

 

TESTS:: 

 

sage: from sage.misc.decorators import options 

sage: o = options(rgbcolor=(0,0,1)) 

sage: o.options 

{'rgbcolor': (0, 0, 1)} 

sage: o = options(rgbcolor=(0,0,1), __original_opts=True) 

sage: o.original_opts 

True 

sage: loads(dumps(o)).options 

{'rgbcolor': (0, 0, 1)} 

 

Demonstrate that the introspected argument specification of the wrapped 

function is updated (see :trac:`9976`):: 

 

sage: from sage.misc.decorators import options 

sage: o = options(rgbcolor=(0,0,1)) 

sage: def f(*args, **kwds): 

....: print("{} {}".format(args, list(sorted(kwds.items())))) 

sage: f1 = o(f) 

sage: from sage.misc.sageinspect import sage_getargspec 

sage: sage_getargspec(f1) 

ArgSpec(args=['rgbcolor'], varargs='args', keywords='kwds', defaults=((0, 0, 1),)) 

""" 

self.options = options 

self.original_opts = options.pop('__original_opts', False) 

 

def __call__(self, func): 

""" 

EXAMPLES:: 

 

sage: from sage.misc.decorators import options 

sage: o = options(rgbcolor=(0,0,1)) 

sage: def f(*args, **kwds): 

....: print("{} {}".format(args, list(sorted(kwds.items())))) 

sage: f1 = o(f) 

sage: f1() 

() [('rgbcolor', (0, 0, 1))] 

sage: f1(rgbcolor=1) 

() [('rgbcolor', 1)] 

sage: o = options(rgbcolor=(0,0,1), __original_opts=True) 

sage: f2 = o(f) 

sage: f2(alpha=1) 

() [('__original_opts', {'alpha': 1}), ('alpha', 1), ('rgbcolor', (0, 0, 1))] 

 

""" 

@sage_wraps(func) 

def wrapper(*args, **kwds): 

options = copy(wrapper.options) 

if self.original_opts: 

options['__original_opts'] = kwds 

options.update(kwds) 

return func(*args, **options) 

 

#Add the options specified by @options to the signature of the wrapped 

#function in the Sphinx-generated documentation (Trac 9976), using the 

#special attribute _sage_argspec_ (see e.g. sage.misc.sageinspect) 

def argspec(): 

argspec = sage_getargspec(func) 

args = (argspec.args if not argspec.args is None else []) + self.options.keys() 

defaults = tuple(argspec.defaults if not argspec.defaults is None else ()) + tuple(self.options.values()) 

#Note: argspec.defaults is not always a tuple for some reason 

return ArgSpec(args, argspec.varargs, argspec.keywords, defaults) 

wrapper._sage_argspec_ = argspec 

 

def defaults(): 

""" 

Return the default options. 

 

EXAMPLES:: 

 

sage: from sage.misc.decorators import options 

sage: o = options(rgbcolor=(0,0,1)) 

sage: def f(*args, **kwds): 

....: print("{} {}".format(args, list(sorted(kwds.items())))) 

sage: f = o(f) 

sage: f.options['rgbcolor']=(1,1,1) 

sage: f.defaults() 

{'rgbcolor': (0, 0, 1)} 

""" 

return copy(self.options) 

 

def reset(): 

""" 

Reset the options to the defaults. 

 

EXAMPLES:: 

 

sage: from sage.misc.decorators import options 

sage: o = options(rgbcolor=(0,0,1)) 

sage: def f(*args, **kwds): 

....: print("{} {}".format(args, list(sorted(kwds.items())))) 

sage: f = o(f) 

sage: f.options 

{'rgbcolor': (0, 0, 1)} 

sage: f.options['rgbcolor']=(1,1,1) 

sage: f.options 

{'rgbcolor': (1, 1, 1)} 

sage: f() 

() [('rgbcolor', (1, 1, 1))] 

sage: f.reset() 

sage: f.options 

{'rgbcolor': (0, 0, 1)} 

sage: f() 

() [('rgbcolor', (0, 0, 1))] 

""" 

wrapper.options = copy(self.options) 

 

wrapper.options = copy(self.options) 

wrapper.reset = reset 

wrapper.reset.__doc__ = """ 

Reset the options to the defaults. 

 

Defaults: 

%s 

""" % self.options 

 

wrapper.defaults = defaults 

wrapper.defaults.__doc__ = """ 

Return the default options. 

 

Defaults: 

%s 

""" % self.options 

 

return wrapper 

 

 

class rename_keyword(object): 

def __init__(self, deprecated=None, deprecation=None, **renames): 

""" 

A decorator which renames keyword arguments and optionally 

deprecates the new keyword. 

 

INPUT: 

 

- ``deprecation`` -- integer. The trac ticket number where the 

deprecation was introduced. 

 

- the rest of the arguments is a list of keyword arguments in the 

form ``renamed_option='existing_option'``. This will have the 

effect of renaming ``renamed_option`` so that the function only 

sees ``existing_option``. If both ``renamed_option`` and 

``existing_option`` are passed to the function, ``existing_option`` 

will override the ``renamed_option`` value. 

 

EXAMPLES:: 

 

sage: from sage.misc.decorators import rename_keyword 

sage: r = rename_keyword(color='rgbcolor') 

sage: r.renames 

{'color': 'rgbcolor'} 

sage: loads(dumps(r)).renames 

{'color': 'rgbcolor'} 

 

To deprecate an old keyword:: 

 

sage: r = rename_keyword(deprecation=13109, color='rgbcolor') 

""" 

assert deprecated is None, 'Use @rename_keyword(deprecation=<trac_number>, ...)' 

self.renames = renames 

self.deprecation = deprecation 

 

def __call__(self, func): 

""" 

Rename keywords. 

 

EXAMPLES:: 

 

sage: from sage.misc.decorators import rename_keyword 

sage: r = rename_keyword(color='rgbcolor') 

sage: def f(*args, **kwds): 

....: print("{} {}".format(args, kwds)) 

sage: f = r(f) 

sage: f() 

() {} 

sage: f(alpha=1) 

() {'alpha': 1} 

sage: f(rgbcolor=1) 

() {'rgbcolor': 1} 

sage: f(color=1) 

() {'rgbcolor': 1} 

 

We can also deprecate the renamed keyword:: 

 

sage: r = rename_keyword(deprecation=13109, deprecated_option='new_option') 

sage: def f(*args, **kwds): 

....: print("{} {}".format(args, kwds)) 

sage: f = r(f) 

sage: f() 

() {} 

sage: f(alpha=1) 

() {'alpha': 1} 

sage: f(new_option=1) 

() {'new_option': 1} 

sage: f(deprecated_option=1) 

doctest:...: DeprecationWarning: use the option 'new_option' instead of 'deprecated_option' 

See http://trac.sagemath.org/13109 for details. 

() {'new_option': 1} 

""" 

@sage_wraps(func) 

def wrapper(*args, **kwds): 

for old_name, new_name in self.renames.items(): 

if old_name in kwds and new_name not in kwds: 

if self.deprecation is not None: 

from sage.misc.superseded import deprecation 

deprecation(self.deprecation, "use the option " 

"%r instead of %r" % (new_name, old_name)) 

kwds[new_name] = kwds[old_name] 

del kwds[old_name] 

return func(*args, **kwds) 

 

return wrapper 

 

class specialize: 

r""" 

A decorator generator that returns a decorator that in turn 

returns a specialized function for function ``f``. In other words, 

it returns a function that acts like ``f`` with arguments 

``*args`` and ``**kwargs`` supplied. 

 

INPUT: 

 

- ``*args``, ``**kwargs`` -- arguments to specialize the function for. 

 

OUTPUT: 

 

- a decorator that accepts a function ``f`` and specializes it 

with ``*args`` and ``**kwargs`` 

 

EXAMPLES:: 

 

sage: f = specialize(5)(lambda x, y: x+y) 

sage: f(10) 

15 

sage: f(5) 

10 

sage: @specialize("Bon Voyage") 

....: def greet(greeting, name): 

....: print("{0}, {1}!".format(greeting, name)) 

sage: greet("Monsieur Jean Valjean") 

Bon Voyage, Monsieur Jean Valjean! 

sage: greet(name = 'Javert') 

Bon Voyage, Javert! 

""" 

def __init__(self, *args, **kwargs): 

self.args = args 

self.kwargs = kwargs 

 

def __call__(self, f): 

return sage_wraps(f)(partial(f, *self.args, **self.kwargs)) 

 

def decorator_keywords(func): 

r""" 

A decorator for decorators with optional keyword arguments. 

 

EXAMPLES:: 

 

sage: from sage.misc.decorators import decorator_keywords 

sage: @decorator_keywords 

....: def preprocess(f=None, processor=None): 

....: def wrapper(*args, **kwargs): 

....: if processor is not None: 

....: args, kwargs = processor(*args, **kwargs) 

....: return f(*args, **kwargs) 

....: return wrapper 

 

This decorator can be called with and without arguments:: 

 

sage: @preprocess 

....: def foo(x): return x 

sage: foo(None) 

sage: foo(1) 

1 

 

sage: def normalize(x): return ((0,),{}) if x is None else ((x,),{}) 

sage: @preprocess(processor=normalize) 

....: def foo(x): return x 

sage: foo(None) 

0 

sage: foo(1) 

1 

""" 

@sage_wraps(func) 

def wrapped(f=None, **kwargs): 

if f is None: 

return sage_wraps(func)(lambda f:func(f, **kwargs)) 

else: 

return func(f, **kwargs) 

return wrapped