1

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?

Community
  • 1
  • 1
SuperElectric
  • 17,548
  • 10
  • 52
  • 69

1 Answers1

2

Your loading the module yaml from the file:

/home/mkg/projects/simplelearn/simplelearn/yaml.pyc

You either named one of your own files yaml.py, or you did have that file before and renamed it, but forgot to remove the yaml.pyc. So you are not loading the PyYAML interpreter with import yaml.

The easiest way to verify is to include a temporary line after the import:

import yaml
print(yaml.__file__)

you should see something like .../site-packages/yaml/__init__.pyc.

Anthon
  • 69,918
  • 32
  • 186
  • 246