I'm using PyYAML, and would like to be able to use a string-concatenating constructor in my .yaml files.
This post shows how to add such constructors to PyYAML:
import yaml
## define custom tag handler
def join(loader, node):
seq = loader.construct_sequence(node)
return ''.join([str(i) for i in seq])
## register the tag handler
yaml.add_constructor('!join', join)
The above works when I enter it in a python terminal. However, I want to put the above in my_package
's __init__.py
file, so that I can do:
from my_package import yaml # my_package.__init__.py contains the above code
yaml.load("""
user_dir: &DIR /home/user
user_pics: !join [*DIR, /pics]
""")
However, this crashes with the message:
AttributeError Traceback (most recent call last)
<ipython-input-1-1107dafdb1d2> in <module>()
----> 1 import simplelearn.yaml
/home/mkg/projects/simplelearn/simplelearn/__init__.py in <module>()
----> 1 import yaml
2
3 def __join(loader, node):
4 '''
5 Concatenates a sequence of strings.
/home/mkg/projects/simplelearn/simplelearn/yaml.pyc in <module>()
AttributeError: 'module' object has no attribute 'add_constructor'
What's going on? Why can't python find yaml.add_constructor
?