【发布时间】:2015-11-08 17:10:13
【问题描述】:
我正在使用 PyYAML,并且希望能够在我的 .yaml 文件中使用字符串连接构造函数。
This post 展示了如何将此类构造函数添加到 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)
当我在 python 终端中输入它时,上述内容有效。但是,我想把上面的内容放在my_package的__init__.py文件中,这样我就可以做到:
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]
""")
但是,这会崩溃并显示以下消息:
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'
发生了什么事?为什么python找不到yaml.add_constructor?
【问题讨论】:
标签: python yaml packages pyyaml