Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8666649
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T17:46:56+00:00 2026-06-12T17:46:56+00:00

Introduction The string module has a Template class, that lets you make substitutions in

  • 0

Introduction

The string module has a Template class, that lets you make substitutions in a string using a mapping object, for instance:

>>> string.Template('var is $var').substitute({'var': 1})
'var is 1'

The substitute method may raise a KeyError exception, if an attempt is made to substitute an element that is missing from the mapping, for instance

>>> string.Template('var is $var and foo is $foo').substitute({'var': 1})
KeyError: 'foo'

or may raise a ValueError, if the template string is invalid, e.g. it contains a $ character followed by a space:

>>> string.Template('$ var is $var').substitute({'var': 1})
ValueError: Invalid placeholder in string: line 1, col 1

The Problem

Given a template string and a mapping, I want to determine whether all place-holders in the template would be substituted. For this, I would try to make the substitution and catch any KeyError exception:

def check_substitution(template, mapping):
    try:
        string.Template(template).substitute(mapping)
    except KeyError:
        return False
    except ValueError:
        pass
    return True

But this doesn’t work, because if the template is invalid and a ValueError is raised, subsequent KeyErrors aren’t caught:

>>> check_substitution('var is $var and foo is $foo', {'var': 1})
False
>>> check_substitution('$ var is $var and foo is $foo', {'var': 1})
True

but I don’t care about ValueErrors. So, what would be the right approach to this problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T17:46:57+00:00Added an answer on June 12, 2026 at 5:46 pm

    The docs say that you can replace the pattern as long as it contains all necessary named groups:

    import re
    from string import Template
    
    
    class TemplateIgnoreInvalid(Template):
        # override pattern to make sure `invalid` never matches
        pattern = r"""
        %(delim)s(?:
          (?P<escaped>%(delim)s) |   # Escape sequence of two delimiters
          (?P<named>%(id)s)      |   # delimiter and a Python identifier
          {(?P<braced>%(id)s)}   |   # delimiter and a braced identifier
          (?P<invalid>^$)            # never matches (the regex is not multilined)
        )
        """ % dict(delim=re.escape(Template.delimiter), id=Template.idpattern)
    
    
    def check_substitution(template, **mapping):
        try:
            TemplateIgnoreInvalid(template).substitute(mapping)
        except KeyError:
            return False
        else:
            return True
    

    Tests

    f = check_substitution
    assert f('var is $var', var=1)
    assert f('$ var is $var', var=1)
    assert     f('var is $var and foo is $foo', var=1, foo=2)
    assert not f('var is $var and foo is $foo', var=1)
    assert     f('$ var is $var and foo is $foo', var=1, foo=2)
    assert not f('$ var is $var and foo is $foo', var=1)
    # support all invalid patterns
    assert f('var is $var and foo is ${foo', var=1)
    assert f('var is $var and foo is ${foo', var=1, foo=2) #NOTE: problematic API
    assert     f('var is $var and foo is ${foo and ${baz}', var=1, baz=3)
    assert not f('var is $var and foo is ${foo and ${baz}', var=1)
    

    It works for all invalid occurences of the delimiter ($).

    The examples show that ignoring invalid patterns conceals simple typos in the template so it is not a good API.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Well, here's a great question that has always disturbed me. Introduction I'm developing a
Long introduction, question is at the end: Assume I have a base class that's
I'm a TA for an Introduction to MATLAB course, and the class has not
Using the Introduction Package 4.5 (Not templa voila) The page.meta template sets the meta
I'm trying to make this: <span class=introduction> <img alt=image src=/picture.jpg /> </span> transform into
Introduction I have been so annoyed by applications that have a startup dialog which
INTRODUCTION I'm using excel downloads as a way of users downloading a score sheet,
Introduction We have an OpenID Provider which we created using the DotNetOpenAuth component. Everything
Introduction In a current project I'm working on we're using the ChartBoost SDK for
Introduction I have some sort of values that I might want to access several

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.