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

""" 

Lazy attributes 

  

AUTHORS: 

  

- Nicolas Thiery (2008): Initial version 

- Nils Bruin (2013-05): Cython version 

""" 

  

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

# Copyright (C) 2008 Nicolas M. Thiery <nthiery at users.sf.net> 

# 

# Distributed under the terms of the GNU General Public License (GPL) 

# 

# This code is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 

# General Public License for more details. 

# 

# The full text of the GPL is available at: 

# 

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

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

from __future__ import print_function 

  

cdef class _lazy_attribute(object): 

""" 

Cython base class for lazy attributes. 

  

EXAMPLES: 

  

Only Python subclasses of this class are supposed to be instantiated:: 

  

sage: from sage.misc.lazy_attribute import _lazy_attribute 

sage: _lazy_attribute(lambda x:1) 

Traceback (most recent call last): 

... 

NotImplementedError: Only instantiate wrapper python class 

  

""" 

  

cdef public f 

cdef public str __name__ 

  

def __init__(self, f): 

r""" 

Constructor for lazy attributes. 

  

EXAMPLES:: 

  

sage: def f(x): 

....: "doc of f" 

....: return 1 

....: 

sage: x = lazy_attribute(f); x 

<sage.misc.lazy_attribute.lazy_attribute object at ...> 

sage: x.__doc__ 

'doc of f' 

sage: x.__name__ 

'f' 

sage: x.__module__ 

'__main__' 

  

TESTS: 

  

We check that :trac:`9251` is solved:: 

  

sage: Parent.element_class 

<sage.misc.lazy_attribute.lazy_attribute object at 0x...> 

sage: Parent.element_class.__doc__[91:147] 

'The (default) class for the elements of this parent\n\n ' 

sage: Parent.element_class.__name__ 

'element_class' 

sage: Parent.element_class.__module__ 

'sage.misc.lazy_attribute' 

""" 

raise NotImplementedError("Only instantiate wrapper python class") 

  

def _sage_src_lines_(self): 

r""" 

Returns the source code location for the wrapped function. 

  

EXAMPLES:: 

  

sage: from sage.misc.sageinspect import sage_getsourcelines 

sage: g = lazy_attribute(banner) 

sage: (src, lines) = sage_getsourcelines(g) 

sage: src[0] 

'def banner():\n' 

sage: lines 

81 

""" 

from sage.misc.sageinspect import sage_getsourcelines 

return sage_getsourcelines(self.f) 

  

  

def __get__(self, a, cls): 

""" 

Implements the attribute access protocol. 

  

EXAMPLES:: 

  

sage: class A: pass 

sage: def f(x): return 1 

... 

sage: f = lazy_attribute(f) 

sage: f.__get__(A(), A) 

1 

""" 

cdef CM 

cdef result 

if a is None: # when doing cls.x for cls a class and x a lazy attribute 

return self 

try: 

# __cached_methods is supposed to be a public Cython attribute. 

# Apparently, these are *not* subject to name mangling. 

CM = getattr(a, '__cached_methods') 

if CM is None: 

CM = {} 

setattr(a, '__cached_methods', CM) 

except AttributeError as msg: 

CM = None 

if CM is not None: 

try: 

return CM[self.__name__] 

except KeyError: 

pass 

result = self.f(a) 

if result is NotImplemented: 

# Workaround: we make sure that cls is the class 

# where the lazy attribute self is actually defined. 

# This avoids running into an infinite loop 

# See About descriptor specifications 

for supercls in cls.__mro__: 

if self.__name__ in supercls.__dict__ and self is supercls.__dict__[self.__name__]: 

cls = supercls 

return getattr(super(cls, a),self.__name__) 

try: 

setattr(a, self.__name__, result) 

except AttributeError: 

if CM is not None: 

CM[self.__name__] = result 

return result 

raise 

return result 

  

class lazy_attribute(_lazy_attribute): 

r""" 

A lazy attribute for an object is like a usual attribute, except 

that, instead of being computed when the object is constructed 

(i.e. in ``__init__``), it is computed on the fly the first time it 

is accessed. 

  

For constant values attached to an object, lazy attributes provide 

a shorter syntax and automatic caching (unlike methods), while 

playing well with inheritance (like methods): a subclass can 

easily override a given attribute; you don't need to call the 

super class constructor, etc. 

  

Technically, a :class:`lazy_attribute` is a non-data descriptor (see 

Invoking Descriptors in the Python reference manual). 

  

EXAMPLES: 

  

We create a class whose instances have a lazy attribute ``x``:: 

  

sage: class A(object): 

....: def __init__(self): 

....: self.a=2 # just to have some data to calculate from 

....: 

....: @lazy_attribute 

....: def x(self): 

....: print("calculating x in A") 

....: return self.a + 1 

....: 

  

For an instance ``a`` of ``A``, ``a.x`` is calculated the first time it 

is accessed, and then stored as a usual attribute:: 

  

sage: a = A() 

sage: a.x 

calculating x in A 

3 

sage: a.x 

3 

  

.. rubric:: Implementation details 

  

We redo the same example, but opening the hood to see what happens to 

the internal dictionary of the object:: 

  

sage: a = A() 

sage: a.__dict__ 

{'a': 2} 

sage: a.x 

calculating x in A 

3 

sage: a.__dict__ 

{'a': 2, 'x': 3} 

sage: a.x 

3 

sage: timeit('a.x') # random 

625 loops, best of 3: 89.6 ns per loop 

  

This shows that, after the first calculation, the attribute ``x`` 

becomes a usual attribute; in particular, there is no time penalty 

to access it. 

  

A lazy attribute may be set as usual, even before its first access, 

in which case the lazy calculation is completely ignored:: 

  

sage: a = A() 

sage: a.x = 4 

sage: a.x 

4 

sage: a.__dict__ 

{'a': 2, 'x': 4} 

  

Class binding results in the lazy attribute itself:: 

  

sage: A.x 

<sage.misc.lazy_attribute.lazy_attribute object at ...> 

  

.. rubric:: Conditional definitions 

  

The function calculating the attribute may return NotImplemented 

to declare that, after all, it is not able to do it. In that case, 

the attribute lookup proceeds in the super class hierarchy:: 

  

sage: class B(A): 

....: @lazy_attribute 

....: def x(self): 

....: if hasattr(self, "y"): 

....: print("calculating x from y in B") 

....: return self.y 

....: else: 

....: print("y not there; B does not define x") 

....: return NotImplemented 

....: 

sage: b = B() 

sage: b.x 

y not there; B does not define x 

calculating x in A 

3 

sage: b = B() 

sage: b.y = 1 

sage: b.x 

calculating x from y in B 

1 

  

.. rubric:: Attribute existence testing 

  

Testing for the existence of an attribute with hasattr currently 

always triggers its full calculation, which may not be desirable 

when the calculation is expensive:: 

  

sage: a = A() 

sage: hasattr(a, "x") 

calculating x in A 

True 

  

It would be great if we could take over the control somehow, if at 

all possible without a special implementation of hasattr, so as to 

allow for something like:: 

  

sage: class A (object): 

....: @lazy_attribute 

....: def x(self, existence_only=False): 

....: if existence_only: 

....: print("testing for x existence") 

....: return True 

....: else: 

....: print("calculating x in A") 

....: return 3 

....: 

sage: a = A() 

sage: hasattr(a, "x") # todo: not implemented 

testing for x existence 

sage: a.x 

calculating x in A 

3 

sage: a.x 

3 

  

Here is a full featured example, with both conditional definition 

and existence testing:: 

  

sage: class B(A): 

....: @lazy_attribute 

....: def x(self, existence_only=False): 

....: if hasattr(self, "y"): 

....: if existence_only: 

....: print("testing for x existence in B") 

....: return True 

....: else: 

....: print("calculating x from y in B") 

....: return self.y 

....: else: 

....: print("y not there; B does not define x") 

....: return NotImplemented 

....: 

sage: b = B() 

sage: hasattr(b, "x") # todo: not implemented 

y not there; B does not define x 

testing for x existence 

True 

sage: b.x 

y not there; B does not define x 

calculating x in A 

3 

sage: b = B() 

sage: b.y = 1 

sage: hasattr(b, "x") # todo: not implemented 

testing for x existence in B 

True 

sage: b.x 

calculating x from y in B 

1 

  

  

.. rubric:: lazy attributes and introspection 

  

.. TODO:: 

  

Make the following work nicely:: 

  

sage: b.x? # todo: not implemented 

sage: b.x?? # todo: not implemented 

  

Right now, the first one includes the doc of this class, and the 

second one brings up the code of this class, both being not very 

useful. 

  

TESTS: 

  

.. rubric:: Partial support for old style classes 

  

Old style and new style classes play a bit differently with 

@property and attribute setting:: 

  

sage: class A: 

....: @property 

....: def x(self): 

....: print("calculating x") 

....: return 3 

....: 

sage: a = A() 

sage: a.x = 4 

sage: a.__dict__ 

{'x': 4} 

sage: a.x 

4 

sage: a.__dict__['x']=5 

sage: a.x 

5 

  

sage: class A (object): 

....: @property 

....: def x(self): 

....: print("calculating x") 

....: return 3 

....: 

sage: a = A() 

sage: a.x = 4 

Traceback (most recent call last): 

... 

AttributeError: can't set attribute 

sage: a.__dict__ 

{} 

sage: a.x 

calculating x 

3 

sage: a.__dict__['x']=5 

sage: a.x 

calculating x 

3 

  

In particular, lazy_attributes need to be implemented as non-data 

descriptors for new style classes, so as to leave access to 

setattr. We now check that this implementation also works for old 

style classes (conditional definition does not work yet):: 

  

sage: class A: 

....: def __init__(self): 

....: self.a=2 # just to have some data to calculate from 

....: 

....: @lazy_attribute 

....: def x(self): 

....: print("calculating x") 

....: return self.a + 1 

....: 

sage: a = A() 

sage: a.__dict__ 

{'a': 2} 

sage: a.x 

calculating x 

3 

sage: a.__dict__ 

{'a': 2, 'x': 3} 

sage: a.x 

3 

sage: timeit('a.x') # random 

625 loops, best of 3: 115 ns per loop 

  

sage: a = A() 

sage: a.x = 4 

sage: a.x 

4 

sage: a.__dict__ 

{'a': 2, 'x': 4} 

  

sage: class B(A): 

....: @lazy_attribute 

....: def x(self): 

....: if hasattr(self, "y"): 

....: print("calculating x from y in B") 

....: return self.y 

....: else: 

....: print("y not there; B does not define x") 

....: return NotImplemented 

....: 

sage: b = B() 

sage: b.x # todo: not implemented 

y not there; B does not define x 

calculating x in A 

3 

sage: b = B() 

sage: b.y = 1 

sage: b.x 

calculating x from y in B 

1 

  

.. rubric:: Lazy attributes and Cython 

  

This attempts to check that lazy attributes work with built-in 

functions like cpdef methods:: 

  

sage: class A: 

....: def __len__(x): 

....: return int(5) 

....: len = lazy_attribute(len) 

....: 

sage: A().len 

5 

  

Since :trac:`11115`, extension classes derived from 

:class:`~sage.structure.parent.Parent` can inherit a lazy attribute, 

such as ``element_class``:: 

  

sage: cython_code = ["from sage.structure.parent cimport Parent", 

....: "from sage.structure.element cimport Element", 

....: "cdef class MyElement(Element): pass", 

....: "cdef class MyParent(Parent):", 

....: " Element = MyElement"] 

sage: cython('\n'.join(cython_code)) 

sage: P = MyParent(category=Rings()) 

sage: P.element_class # indirect doctest 

<type '...MyElement'> 

  

.. rubric:: About descriptor specifications 

  

The specifications of descriptors (see 3.4.2.3 Invoking 

Descriptors in the Python reference manual) are incomplete 

w.r.t. inheritance, and maybe even ill-implemented. We illustrate 

this on a simple class hierarchy, with an instrumented descriptor:: 

  

sage: class descriptor(object): 

....: def __get__(self, obj, cls): 

....: print(cls) 

....: return 1 

sage: class A(object): 

....: x = descriptor() 

sage: class B(A): 

....: pass 

....: 

  

This is fine:: 

  

sage: A.x 

<class '__main__.A'> 

1 

  

The behaviour for the following case is not specified (see Instance Binding) 

when ``x`` is not in the dictionary of ``B`` but in that of some super 

category:: 

  

sage: B().x 

<class '__main__.B'> 

1 

  

It would seem more natural (and practical!) to get ``A`` rather than ``B``. 

  

From the specifications for Super Binding, it would be expected to 

get ``A`` and not ``B`` as cls parameter:: 

  

sage: super(B, B()).x 

<class '__main__.B'> 

1 

  

Due to this, the natural implementation runs into an infinite loop 

in the following example:: 

  

sage: class A(object): 

....: @lazy_attribute 

....: def unimplemented_A(self): 

....: return NotImplemented 

....: @lazy_attribute 

....: def unimplemented_AB(self): 

....: return NotImplemented 

....: @lazy_attribute 

....: def unimplemented_B_implemented_A(self): 

....: return 1 

....: 

sage: class B(A): 

....: @lazy_attribute 

....: def unimplemented_B(self): 

....: return NotImplemented 

....: @lazy_attribute 

....: def unimplemented_AB(self): 

....: return NotImplemented 

....: @lazy_attribute 

....: def unimplemented_B_implemented_A(self): 

....: return NotImplemented 

....: 

sage: class C(B): 

....: pass 

....: 

  

This is the simplest case where, without workaround, we get an 

infinite loop:: 

  

sage: hasattr(B(), "unimplemented_A") # todo: not implemented 

False 

  

.. TODO:: 

  

Improve the error message:: 

  

sage: B().unimplemented_A # todo: not implemented 

Traceback (most recent call last): 

... 

AttributeError: 'super' object has no attribute 'unimplemented_A' 

  

We now make some systematic checks:: 

  

sage: B().unimplemented_A 

Traceback (most recent call last): 

... 

AttributeError: '...' object has no attribute 'unimplemented_A' 

sage: B().unimplemented_B 

Traceback (most recent call last): 

... 

AttributeError: '...' object has no attribute 'unimplemented_B' 

sage: B().unimplemented_AB 

Traceback (most recent call last): 

... 

AttributeError: '...' object has no attribute 'unimplemented_AB' 

sage: B().unimplemented_B_implemented_A 

1 

  

sage: C().unimplemented_A() 

Traceback (most recent call last): 

... 

AttributeError: '...' object has no attribute 'unimplemented_A' 

sage: C().unimplemented_B() 

Traceback (most recent call last): 

... 

AttributeError: '...' object has no attribute 'unimplemented_B' 

sage: C().unimplemented_AB() 

Traceback (most recent call last): 

... 

AttributeError: '...' object has no attribute 'unimplemented_AB' 

sage: C().unimplemented_B_implemented_A # todo: not implemented 

1 

""" 

def __init__(self, f): 

""" 

Initialize ``self``. 

  

EXAMPLES:: 

  

sage: def f(x): 

....: "doc of f" 

....: return 1 

....: 

sage: x = lazy_attribute(f); x 

<sage.misc.lazy_attribute.lazy_attribute object at ...> 

sage: x.__doc__ 

'doc of f' 

sage: x.__name__ 

'f' 

sage: x.__module__ 

'__main__' 

""" 

self.f = f 

if hasattr(f, "__doc__"): 

self.__doc__ = f.__doc__ 

elif hasattr(f, "__doc__"): # Needed to handle Cython methods 

self.__doc__ = f.__doc__ 

if hasattr(f, "__name__"): 

self.__name__ = f.__name__ 

elif hasattr(f, "__name__"): # Needed to handle Cython methods 

self.__name__ = f.__name__ 

if hasattr(f, "__module__"): 

self.__module__ = f.__module__ 

  

class lazy_class_attribute(lazy_attribute): 

""" 

A lazy class attribute for an class is like a usual class attribute, 

except that, instead of being computed when the class is constructed, it 

is computed on the fly the first time it is accessed, either through the 

class itself or trough on of its objects. 

  

This is very similar to :class:`lazy_attribute` except that the attribute 

is a class attribute. More precisely, once computed, the lazy class 

attribute is stored in the class rather than in the object. The lazy class 

attribute is only computed once for all the objects:: 

  

sage: class Cl(object): 

....: @lazy_class_attribute 

....: def x(cls): 

....: print("computing x") 

....: return 1 

sage: Cl.x 

computing x 

1 

sage: Cl.x 

1 

  

As for a any usual class attribute it is also possible to access it from 

an object:: 

  

sage: b = Cl() 

sage: b.x 

1 

  

First access from an object also porperly triggers the computation:: 

  

sage: class Cl1(object): 

....: @lazy_class_attribute 

....: def x(cls): 

....: print("computing x") 

....: return 1 

sage: Cl1().x 

computing x 

1 

sage: Cl1().x 

1 

  

.. WARNING:: 

  

The behavior of lazy class attributes with respect to inheritance is 

not specified. It currently depends on the evaluation order:: 

  

sage: class A(object): 

....: @lazy_class_attribute 

....: def x(cls): 

....: print("computing x") 

....: return str(cls) 

....: @lazy_class_attribute 

....: def y(cls): 

....: print("computing y") 

....: return str(cls) 

sage: class B(A): 

....: pass 

  

sage: A.x 

computing x 

"<class '__main__.A'>" 

sage: B.x 

"<class '__main__.A'>" 

  

sage: B.y 

computing y 

"<class '__main__.B'>" 

sage: A.y 

computing y 

"<class '__main__.A'>" 

sage: B.y 

"<class '__main__.B'>" 

  

TESTS:: 

  

sage: "x" in b.__dict__ 

False 

""" 

def __get__(self, _, cls): 

""" 

Implements the attribute access protocol. 

  

EXAMPLES:: 

  

sage: class A: pass 

sage: def f(x): return 1 

....: 

sage: f = lazy_class_attribute(f) 

sage: f.__get__(A(), A) 

1 

""" 

result = self.f(cls) 

if result is NotImplemented: 

return getattr(super(cls, cls),self.__name__) 

setattr(cls, self.__name__, result) 

return result