Package: f2format-converter
f2formatWritef-stringin Python 3.6 flavour, and letf2formatworry about back-port issues :beer:SincePEP 498, Python introducedf-stringliterals in version3.6. Though released ever sinceDecember 23, 2016, Python
3.6 is still not widely used as expected. For those who are now used tof-strings,f2formatprovides an intelligent, yet imperfect, solution of abackport compilerby convertingf-strings tostr.formatexpressions, which guarantees you to always writef-strings in Python
3.6 flavour then compile for compatibility later.f2formatis inspired and assisted by my good mate@gousaiyang.
It functions by tokenising and parsing Python code into multiple abstract syntax trees (AST),
through which it shall synthesise and extract expressions fromf-stringliterals, and then
reassemble the original string usingstr.formatmethod. Besidesconversionandformat specification,f2formatalso considered and resolvedstring concatenation.
Also, it always tries to maintain the original layout of source code, and accuracy of syntax.InstallationNote thatf2formatonly supports Python versionssince 3.3🐍For macOS users,f2formatis now available throughHomebrew:brewtapjarryshaw/tap
brewinstallf2format# or simply, a one-linerbrewinstalljarryshaw/tap/f2formatSimply run the following to install the current version from PyPI:pipinstallf2formatOr install the latest version from the git repository:gitclonehttps://github.com/JarryShaw/f2format.gitcdf2format
pipinstall-e.# and to update at any timegitpullBasic UsageCLIIt is fairly straightforward to usef2format:context in${...}changes dynamically according to runtime environmentusage: f2format [options] <python source files and folders...>

Convert f-string to str.format for Python 3 compatibility.

positional arguments:
  SOURCE                python source files and folders to be converted (${CWD})

optional arguments:
  -h, --help            show this help message and exit
  -V, --version         show program's version number and exit
  -q, --quiet           run in quiet mode

archive options:
  duplicate original files in case there's any issue

  -na, --no-archive     do not archive original files
  -p PATH, --archive-path PATH
                        path to archive original files (${CWD}/archive)

convert options:
  compatibility configuration for none-unicode files

  -c CODING, --encoding CODING
                        encoding to open source files (${LOCALE_ENCODING})
  -v VERSION, --python VERSION
                        convert against Python version (${LATEST_VERSION})f2formatwill read then convert allf-stringliterals in every Python file under this
path. In case there might be some problems with the conversion,f2formatwill duplicate all
original files it is to modify intoarchivedirectory ahead of the process, if-nnot set.For instance, the code will be converted as follows.# the original codevar=f'foo{(1+2)*3:>5}bar{"a","b"!r}boo'# after `f2format`var='foo{:>5}bar{!r}boo'.format((1+2)*3,("a","b"))DockerWell... it's not published to the Docker Hub yet ;)Consideringf2formatmay be used in scenerios where Python is not reachable.
We provide also a Docker image for those poor little guys.SeeDockerfilefor more
information.Bundled ExecutableComing soooooooooooon...For the worst case, we also provide bundled executables off2format. In such case,
you may simply download it then, voilà, it's ready for you.Special thanks toPyInstaller❤️Developer ReferenceAutomatormake-demo.shprovides a
demo script, which may help integratef2formatin your development and distribution circle.NB:make-demo.shis not an integrated automation script. It should be revised by design.It assumesall source files in/srcdirectoryusing GitHub for repository managementhavingreleasebranch under/releasedirectoryalready installedf2formatandtwinepermission to these files and folders grantedAnd it willcopysetup.pyandsrctoreleasedirectoryrunf2formatfor Python files underreleasedistribute toPyPIandTestPyPIusingtwineupload to release branch on GitHubupload original files to GitHubEnvironmentsf2formatcurrently supports three environment arguments:F2FORMAT_QUIET-- run in quiet mode (same as--quietoption in CLI)F2FORMAT_VERSION-- convert against Python version (same as--pythonoption in CLI)F2FORMAT_ENCODING-- encoding to open source files (same as--encodingoption in CLI)APIsf2format-- wrapper works for conversionf2format(filename)Args:filename--str, file to be convertedEnvs:F2FORMAT_QUIET-- run in quiet mode (same as--quietoption in CLI)F2FORMAT_ENCODING-- encoding to open source files (same as--encodingoption in CLI)F2FORMAT_VERSION-- convert against Python version (same as--pythonoption in CLI)Raises:ConvertError-- whenparso.ParserSyntaxErrorraisedconvert-- the main conversion processconvert(string,source='<unknown>')Args:string--str, context to be convertedsource--str, source of the contextEnvs:F2FORMAT_VERSION-- convert against Python version (same as--pythonoption in CLI)Returns:str-- converted stringRaises:ConvertError-- whenparso.ParserSyntaxErrorraisedConvertError--f2formatinternal exceptionclassConvertError(SyntaxError):passCodecNB: this project is now stalled, because I just cannot figure out how to play w/ codecs :)f2format-codecregisters a codec in Python
interpreter, which grants you the compatibility to write directly in Python 3.6f-stringsyntax
even through running with a previous version of Python.TestThe current test samples are under/testfolder.test_driver.pyis the main entry point for tests.For unittests, seetest.py.Known bugsSincef2formatis currently based onparsoproject,
it had encountered several compatibility and parsing issues.Parsing f-strings with nested format specifiers produces incorrect SyntaxError (#74)This issue has been resolved sinceparsoversion0.5.0.Parsing f-strings with invalid quotes in expression part does not raise SyntaxError (#86)Parsing f-strings with seeming assignment expressions produces incorrect SyntaxError (#87)ContributionContributions are very welcome, especially fixing bugs and providing test cases, which@gousaiyangis to help with, so to speak. Note that code must
remain valid and reasonable.See Alsobabelposeurwalrusvermin