Dave Cinege Git Repo fstr / master fstr.py
master

Tree @master (Download .tar.gz)

fstr.py @masterraw · history · blame

###
# Python fstr()
#
# Copyright (c) 2019 Dave Cinege
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###
from __future__ import print_function
import sys

__VERSION__ = (0, 1, 0, 20191107)

def _fstr (s):
	"""Function wrapper to evaluate string variables as an f-string
	literal for cPython3.6+.
	
	NOTE: this will break on string variables containing triple-single
	quotes. :-(  We can easily check for this but it will really slow
	down the performance."""
	return eval("f'''{}'''".format(s), sys._getframe(1).f_locals)

def strf (s):
	"""The poor mans' f-string function wrapper for cPython2.6 -> 3.5.
	Supports only the capabilities of str.format(). Call this directly
	in cPython 3.6+ to more limit the dangers of eval() and full f-string
	expressions used in _fstr()."""
	return s.format(**sys._getframe(1).f_locals)

if sys.version_info[0:2] >= (3,6):	# Python 3,6+ full f-strings
	fstr = _fstr
else:
	fstr = strf

if __name__ == '__main__':
	#In your program do this:
	# from fstr import fstr
	a = 'Hello'
	s = '{a}! sys.__name__ is "{sys.__name__}".'
	if sys.version_info[0:2] >= (3,6):
		n = 5
		s += ' n = {n}. n+2 == {n+2}.'
	print('string:', s)
	print('f-string:', fstr(s))