Modify ↓
Ticket #48 (closed defect: wontfix)
yaml.load does not call __init__ of objects
| Reported by: | aymanbahrain@… | Owned by: | xi |
|---|---|---|---|
| Priority: | normal | Component: | pyyaml |
| Severity: | normal | Keywords: | |
| Cc: |
Description
I noticed that my init code is not called when an object is created via yaml.load. Try this one: In this example, fy.secret will raise an error about secret not an attribute of fy object.
import yaml
class Field:
def __init__(self):
print 'init called'
self.secret = 'password'
f = Field()
print f.secret
fy = yaml.load(file('fld.yaml', 'r'))
print fy.hide_value
print fy.secret
have fld.yaml contain:
!!python/object:__main__.Field
hide_value: true
Attachments
Change History
Note: See
TracTickets for help on using
tickets.

PyYAML implements the pickle protocol for serializing and deserializing class instances. That is, yaml.load(yaml.dump(instance)) is supposed to work exactly like pickle.loads(pickle.dumps(instance)). The __init__ method is never called by pickle. If you want to customize object creation, you may define a __setstate__ method instead.
For more information on the pickle protocol, check http://www.python.org/dev/peps/pep-0307/.