54920

Check if a string to interpolate provides expected placeholders

Consider this fictitious Python function:

def f(s): # accepts a string containing placeholders # returns an interpolated string return s % {'foo': 'OK', 'bar': 'OK'}

How can I check that the string s provides all the expected placeholders, and if not, make the function politely show the missing keys?

My solution follows. My question: is there a better solution?

import sys def f(s): d = {} notfound = [] expected = ['foo', 'bar'] while True: try: s % d break except KeyError as e: key = e.args[0] # missing key notfound.append(key) d.update({key: None}) missing = set(expected).difference(set(notfound)) if missing: sys.exit("missing keys: %s" % ", ".join(list(missing))) return s % {'foo': 'OK', 'bar': 'OK'}

Answer1:

There's a way to see all of the named placeholders using the _formatter_parser method:

>>>> y="A %{foo} is a %{bar}" >>>> for a,b,c,d in y._formatter_parser(): print b foo bar

For a "public" way:

>>>> import string >>>> x = string.Formatter() >>>> elements = x.parse(y) >>>> for a,b,c,d in elements: print b

Recommend

  • Get function callers' information in python
  • Input multiple files in python using * via the command line
  • Html Example Response with Swagger and Swashbuckle
  • CodeIgniter - strange output issue
  • WCF Rest Error Handling
  • Pygame: How do I make my image fall?
  • ASP.NET MVC ActionResult View() not changing url
  • Python: some “__magic__” attribute to reference a function from within that function
  • Do I need to seed any random number generator before using EVP_PKEY_keygen of OpenSSL?
  • Array with custom indexes in Ionic2
  • MySQL Order by column = x, column asc?
  • PHP buffered output depending on server setting?
  • Functions in global context
  • How to clear text inside text field when radio button is select
  • How to avoid particles glitching together in an elastic particle collision simulator?
  • Recording logins for password protected directories
  • All Classes Conforming to Protocol Inherit Default Implementation
  • Is there a javascript serializer for JSON.Net?
  • Splitting given String into two variables - php
  • Javascript simulate pressing enter in input box
  • Read text file and split every line in MSBuild
  • Fetching methods from BroadcastReceiver to update UI
  • Is possible to count alias result on mysql
  • Excel - Autoshape get it's name from cell (value)
  • Sending data from AppleScript to FileMaker records
  • Javascript + PHP Encryption with pidCrypt
  • Why winpcap requires both .lib and .dll to run?
  • Return words with double consecutive letters
  • RestKit - RKRequestDelegate does not exist
  • Traverse Array and Display in markup
  • VB.net deserialize, JSON Conversion from type 'Dictionary(Of String,Object)' to type '
  • Python: how to group similar lists together in a list of lists?
  • KeystoneJS: Relationships in Admin UI not updating
  • AngularJs get employee from factory
  • Load html files in TinyMce
  • Why joiner is not used after Sequence generator or Update statergy
  • Exception on Android 4.0 `android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode)`
  • File not found error Google Drive API
  • Is it possible to post an object from jquery to bottle.py?
  • Busy indicator not showing up in wpf window [duplicate]