or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-traitlets

A pure Python library providing typed attributes with validation, change notifications, and configuration management for the IPython/Jupyter ecosystem.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/traitlets@4.3.x

To install, run

npx @tessl/cli install tessl/pypi-traitlets@4.3.0

0

# Traitlets

1

2

A pure Python library providing a lightweight trait system for typed attributes with validation, change notifications, and configuration management. Traitlets serves as the foundational configuration system for the IPython and Jupyter ecosystems, enabling robust attribute management with automatic validation, coercion, and change tracking.

3

4

## Package Information

5

6

- **Package Name**: traitlets

7

- **Language**: Python

8

- **Installation**: `pip install traitlets`

9

- **Dependencies**: `ipython_genutils`, `six`, `decorator`

10

11

## Core Imports

12

13

```python

14

import traitlets

15

```

16

17

Common imports for trait types and classes:

18

19

```python

20

from traitlets import HasTraits, TraitType, Unicode, Int, Float, Bool, List, Dict

21

```

22

23

For configuration:

24

25

```python

26

from traitlets.config import Application, Configurable

27

```

28

29

## Basic Usage

30

31

```python

32

from traitlets import HasTraits, Unicode, Int, Float, observe

33

34

class Person(HasTraits):

35

name = Unicode()

36

age = Int(min=0, max=150)

37

height = Float(min=0.0)

38

39

@observe('name')

40

def _name_changed(self, change):

41

print(f"Name changed from {change['old']} to {change['new']}")

42

43

# Create and use the class

44

person = Person(name="Alice", age=30, height=5.6)

45

person.name = "Bob" # Triggers observer

46

person.age = 25 # Validates range

47

48

# Access trait metadata

49

print(person.traits())

50

print(person.trait_names())

51

```

52

53

## Architecture

54

55

Traitlets implements a descriptor-based trait system with several key components:

56

57

- **HasTraits**: Base class providing trait functionality and change notifications

58

- **TraitType**: Base descriptor class for all trait types with validation and metadata

59

- **Trait Types**: Specific validators for different data types (Int, Unicode, Bool, etc.)

60

- **Observers**: Decorators and handlers for responding to trait changes

61

- **Configuration System**: Application framework with file-based configuration support

62

- **Linking**: Mechanisms to synchronize traits between different objects

63

64

This design enables type-safe attribute management with automatic validation, change notifications, and sophisticated configuration capabilities that scale from simple classes to complex applications.

65

66

## Capabilities

67

68

### Core Trait System

69

70

The foundational trait system providing HasTraits base class, TraitType descriptors, and change notification mechanisms. This forms the core of traitlets' typed attribute functionality.

71

72

```python { .api }

73

class HasTraits:

74

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

75

def observe(self, handler, names=All, type='change'): ...

76

def traits(self, **metadata): ...

77

78

class TraitType:

79

def __init__(self, default_value=Undefined, allow_none=False, **kwargs): ...

80

def tag(self, **metadata): ...

81

def validate(self, obj, value): ...

82

```

83

84

[Core Trait System](./core-traits.md)

85

86

### Basic Trait Types

87

88

Fundamental trait types for common Python data types including integers, floats, strings, booleans, and complex numbers, with optional validation parameters.

89

90

```python { .api }

91

class Int(TraitType):

92

def __init__(self, default_value=0, min=None, max=None, **kwargs): ...

93

94

class Unicode(TraitType):

95

def __init__(self, default_value=u'', **kwargs): ...

96

97

class Float(TraitType):

98

def __init__(self, default_value=0.0, min=None, max=None, **kwargs): ...

99

100

class Bool(TraitType):

101

def __init__(self, default_value=False, **kwargs): ...

102

```

103

104

[Basic Trait Types](./basic-types.md)

105

106

### Container Trait Types

107

108

Container trait types for Python collections including lists, dictionaries, sets, and tuples, with element type validation and size constraints.

109

110

```python { .api }

111

class List(Container):

112

def __init__(self, trait=None, default_value=Undefined, minlen=0, maxlen=sys.maxsize, **kwargs): ...

113

114

class Dict(TraitType):

115

def __init__(self, trait=None, traits=None, default_value=Undefined, **kwargs): ...

116

117

class Set(Container):

118

def __init__(self, trait=None, default_value=Undefined, minlen=0, maxlen=sys.maxsize, **kwargs): ...

119

120

class Tuple(TraitType):

121

def __init__(self, *traits, **kwargs): ...

122

```

123

124

[Container Trait Types](./container-types.md)

125

126

### Advanced Trait Types

127

128

Specialized trait types including class-based types, enums, unions, and network addresses for complex validation scenarios.

129

130

```python { .api }

131

class Instance(TraitType):

132

def __init__(self, klass=None, args=None, kw=None, **kwargs): ...

133

134

class Type(TraitType):

135

def __init__(self, klass=None, **kwargs): ...

136

137

class Union(TraitType):

138

def __init__(self, trait_types, **kwargs): ...

139

140

class Enum(TraitType):

141

def __init__(self, values, **kwargs): ...

142

```

143

144

[Advanced Trait Types](./advanced-types.md)

145

146

### Observers and Decorators

147

148

Decorators and handlers for observing trait changes, validating values, and providing dynamic defaults.

149

150

```python { .api }

151

def observe(*names, type='change'):

152

"""Decorator to observe trait changes"""

153

154

def validate(*names):

155

"""Decorator to register cross-validator"""

156

157

def default(name):

158

"""Decorator for dynamic default value generator"""

159

```

160

161

[Observers and Decorators](./observers.md)

162

163

### Trait Linking

164

165

Functions for linking traits between objects, enabling synchronization of trait values across different instances.

166

167

```python { .api }

168

class link:

169

def __init__(self, source, target): ...

170

def unlink(self): ...

171

172

class directional_link:

173

def __init__(self, source, target, transform=None): ...

174

def unlink(self): ...

175

176

# Alias for directional_link

177

dlink = directional_link

178

```

179

180

[Trait Linking](./linking.md)

181

182

### Configuration System

183

184

Application framework and configuration management including configurable base classes, config file loading, and command-line argument processing.

185

186

```python { .api }

187

class Application(SingletonConfigurable):

188

def initialize(self, argv=None): ...

189

def start(self): ...

190

def parse_command_line(self, argv=None): ...

191

192

class Configurable(HasTraits):

193

def __init__(self, config=None, parent=None, **kwargs): ...

194

195

class Config(dict):

196

def merge(self, other): ...

197

```

198

199

[Configuration System](./configuration.md)

200

201

## Types

202

203

### Core Types

204

205

```python { .api }

206

# Sentinel values

207

Undefined = Sentinel('Undefined', 'traitlets', 'Used to specify no default value')

208

All = Sentinel('All', 'traitlets', 'Used to listen to all trait notifications')

209

210

# Deprecated alias

211

NoDefaultSpecified = Undefined # Deprecated: use Undefined instead

212

213

# Exception classes

214

class TraitError(Exception):

215

"""Exception for trait-related errors"""

216

217

# Type checking

218

def is_trait(t):

219

"""Returns whether the given value is an instance or subclass of TraitType"""

220

```

221

222

### Event Objects

223

224

```python { .api }

225

# Event handler classes

226

class EventHandler:

227

"""Base class for event handlers"""

228

229

class ObserveHandler(EventHandler):

230

"""Handler for observe decorator"""

231

232

class ValidateHandler(EventHandler):

233

"""Handler for validate decorator"""

234

235

class DefaultHandler(EventHandler):

236

"""Handler for default decorator"""

237

```