64

I have this:

user_dir: /home/user
user_pics: /home/user/pics

How could I use the user_dir for user_pics? If I have to specify other properties like this, it would not be very DRY.

dreftymac
  • 29,742
  • 25
  • 114
  • 177
Geo
  • 89,506
  • 114
  • 330
  • 511

7 Answers7

57

You can use a repeated node, like this:

user_dir: &user_home /home/user
user_pics: *user_home

I don't think you can concatenate though, so this wouldn't work:

user_dir: &user_home /home/user
user_pics: *user_home/pics
Brian Wells
  • 602
  • 5
  • 4
42

It's surprising, since the purpose of YAML anchors & references is to factor duplication out of YAML data files, that there isn't a built-in way to concatenate strings using references. Your use case of building up a path name from parts is a good example -- there must be many such uses.

Fortunately there's a simple way to add string concatenation to YAML via custom tags in Python.

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)

## using your sample data
yaml.load("""
user_dir: &DIR /home/user
user_pics: !join [*DIR, /pics]
""")

Which results in:

{'user_dir': '/home/user', 'user_pics': '/home/user/pics'}

You can add more items to the array, like " " or "-", if the strings should be delimited.

Dany
  • 4,091
  • 1
  • 11
  • 29
Chris Johnson
  • 19,032
  • 5
  • 75
  • 76
  • 13
    Err… So, what does it have to do with YAML, a markup language independent of Python, Haskell, or whatever? – Hi-Angel Sep 02 '16 at 11:47
  • 10
    The YAML spec says: "Explicit typing is denoted with a tag using the exclamation point (“!”) ... Application-specific local tags may also be used." I provided an implementation of an explicit type that meets the spec. The implementation has to be in some language. I used Python because the OP said he wanted a more "DRY" approach for his YAML, and DRY is a term most often used by Python people. The same custom tag could be implemented in other languages. In other words, what the OP asked isn't available in vanilla YAML, but is available via an extension mechanism defined by YAML. – Chris Johnson Sep 02 '16 at 11:57
  • @Hi-Angel Whenever someone's using YAML they're going to be using some parser written in some specific language - a similar extension can be made in that language. This is just one example for the case of Python. – Ken Williams Mar 05 '20 at 18:22
  • 1
    @KenWilliams okay, I will bear it in mind, so the next time I encounter a proprietary app using YAML for configuration, should I be in need of string concatenation, I should ask authors to provide me with parser source code and all the necessary build system pieces. – Hi-Angel Mar 05 '20 at 18:54
  • 3
    @Hi-Angel As Chris Johnson said, this is an explicit extension mechanism defined by the YAML specification itself. And there's no need to be snarky. – Ken Williams Mar 06 '20 at 23:16
  • @KenWilliams okay, maybe I was confused, I'm sorry if this is the case. If this is true, I think Chris Johnson may get much more upvotes and much less confused comments if he showed a complete YAML example that is using that extension mechanism. Because right now when I'm looking at the answer, I basically see a suggestion to modify the YAML parser code. Maybe a link to some other SO answer which says "even if you don't have source code for the app, you still can easily extend YAML parser in a language you like as follows…" — that would've greatly helped. – Hi-Angel Mar 07 '20 at 09:29
  • 2
    The existing answer *does not* modify the YAML parser code. It does not presume you have access to the source code of the `yaml` package. It simply uses its public APIs to extend it in the way allowed by the YAML spec. – Ken Williams Mar 11 '20 at 15:26
  • Hi @Dany - Thanks for the code. It's not working when my YAML is a file though. I get: "could not determine a constructor for the tag '!join'" Could you help, please? I've also tried adding double "!" but then I get "could not determine a constructor for the tag 'tag:yaml.org,2002:join'" – Bruno Ambrozio Oct 10 '20 at 17:05
  • @BrunoAmbrozio hi! It's Chris Johnson's answer, I just edited it and it was more than a year ago, I don't remember anything about that, sorry. You should ask Chris Johnson – Dany Oct 11 '20 at 18:26
  • How can I use it in Azure DevOps pipeline? – user1700890 Dec 21 '20 at 20:00
10

If you are using python with PyYaml, joining strings is possible within the YAML file. Unfortunately this is only a python solution, not a universal one:

with os.path.join:

user_dir: &home /home/user
user_pics: !!python/object/apply:os.path.join [*home, pics]

with string.join (for completeness sake - this method has the flexibility to be used for multiple forms of string joining:

user_dir: &home /home/user
user_pics: !!python/object/apply:string.join [[*home, pics], /]
user2502636
  • 117
  • 1
  • 3
  • 6
    Be clear on what this approach means -- you are allowing the Pyyaml parser to execute arbitrary Python code from the yaml input file. This is an extremely dangerous security problem if you don't control the source of the input. Many programs will use the `yaml.safe_load()` function to avoid the security issue. In that case, your code won't work. – Chris Johnson Aug 30 '15 at 15:33
  • do you have a python3 example for string joining? `cannot find module 'str' (No module named 'str')` – Jeremy Leipzig Jun 16 '16 at 20:00
7

I would use an array, then join the string together with the current OS Separator Symbol

like this:

default: &default_path "you should not use paths in config"
pictures:
  - *default_path
  - pics
Tom Fenech
  • 69,051
  • 12
  • 96
  • 131
Adam
  • 81
  • 2
  • 3
4

Seems to me that YAML itself does not define way to do this.

Good news are that YAML consumer might be able to understand variables.
What will use Your YAML?

Community
  • 1
  • 1
Arnis Lapsa
  • 42,964
  • 28
  • 114
  • 191
  • My yaml file serves as a configuration file. What I pasted above was just as an example, to illustrate the problem. – Geo Mar 30 '11 at 09:10
  • @ArnisL. [for example this one](https://github.com/Hi-Angel/yi/blob/7dd59102a84dec6a1e52f4ddca49d5f259a76fdc/example-configs/yi-emacs-vty-static/stack.yaml) to define a path to source code directories upon building a separate module. – Hi-Angel Sep 02 '16 at 11:54
3

string.join() won't work in Python3, but you can define a !join like this:

import functools
import yaml

class StringConcatinator(yaml.YAMLObject):
    yaml_loader = yaml.SafeLoader
    yaml_tag = '!join'
    @classmethod
    def from_yaml(cls, loader, node):
        return functools.reduce(lambda a, b: a.value + b.value, node.value)

c=yaml.safe_load('''
user_dir: &user_dir /home/user
user_pics: !join [*user_dir, /pics]''')
print(c)
Dany
  • 4,091
  • 1
  • 11
  • 29
bryan
  • 112
  • 1
  • 5
3

As of August 2019:

To make Chris' solution work, you actually need to add Loader=yaml.Loader to yaml.load(). Eventually, the code would look like this:

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)

## using your sample data
yaml.load("""
user_dir: &DIR /home/user
user_pics: !join [*DIR, /pics]
""", Loader=yaml.Loader)

See this GitHub issue for further discussion.

bmiselis
  • 192
  • 2
  • 10