Heredoc in python

2023-05-23 python heredoc perl

Perl contains feature to put data directly in the script. The section is introduced with __DATA__ symbol and it can contain any data. Part of my perl work are quick scripts to transform some data, do various checks, or mangle the data. An example

my %files = map { chomp; $_ => 1 } <DATA>;

__DATA__
afq80.txt
arts80.txt
af_cq40.txt
af_cp40.txt
mnt_cq05.txt

I was looking for something similar in python. Simple approach might be something like this

def files():
    return [
        'afq80.txt',
        'arts80.txt',
        'af_cq40.txt',
        'af_cp40.txt',
        'mnt_cq05.txt',
    ]

files = dict([(f,1) for f in files()])

This is good, allows easily comment out some items in the array and easily iterate over items, as demonstrated above. Other method I found is to use a longstring

def files():
    return """
afq80.txt
arts80.txt
af_cq40.txt
af_cp40.txt
mnt_cq05.txt
""".strip().split('\n')

The strip method is cutting empty lines at the front and back of the string. Result array is product of split method.