Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Flybbertigybbets

$
0
0

“gyb” stands for “Generate Your Boilerplate”. Built in python, it’s part of Swift’s utility suite and is implemented here .

Gybbing provides a preprocessorthatautomatesinherently repetitivecode that applies, for example, to many kinds of built in math types. With gybs, you don’t have to re-implement a common task for each type, which can get very old very fast. Copying and pasting nearly-identical code is never fun.

If you hop over to the standard library source , you’ll find a couple of dozen gyb sources, from tuples to string interpolation to integers. They use a mix of GYB markup and injected Python code to generate related type code.

Here’s the help info from running gyb -h :

usage: gyb [-h] [-D NAME=VALUE] [-o TARGET] [--test] [--verbose-test] [--dump]
[--line-directive LINE_DIRECTIVE]
[file]
Generate Your Boilerplate!
positional arguments:
file Path to GYB template file (defaults to stdin)
optional arguments:
-h, --help show this help message and exit
-D NAME=VALUE Bindings to be set in the template's execution context
-o TARGET Output file (defaults to stdout)
--test Run a self-test
--verbose-test Run a verbose self-test
--dump Dump the parsed template to stdout
--line-directive LINE_DIRECTIVE
Line directive prefix; empty => no line markers
A GYB template consists of the following elements:
- Literal text which is inserted directly into the output
- %% or $$ in literal text, which insert literal '%' and '$'
symbols respectively.
- Substitutions of the form ${}. The Python
expression is converted to a string and the result is inserted
into the output.
- Python code delimited by %{...}%. Typically used to inject
definitions (functions, classes, variable bindings) into the
evaluation context of the template. Common indentation is
stripped, so you can add as much indentation to the beginning
of this code as you like
- Lines beginning with optional whitespace followed by a single
'%' and Python code. %-lines allow you to nest other
constructs inside them. To close a level of nesting, use the
"%end" construct.
- Lines beginning with optional whitespace and followed by a
single '%' and the token "end", which close open constructs in
%-lines.
Example template:
- Hello -
%{
x = 42
def succ(a):
return a+1
}%
I can assure you that ${x} < ${succ(x)} % if int(y) > 7:
% for i in range(3):
y is greater than seven!
% end
% else:
y is less than or equal to seven
% end
- The End. -
When run with "gyb -Dy=9", the output is
- Hello -
I can assure you that 42 < 43
y is greater than seven!
y is greater than seven!
y is greater than seven!
- The End. -

Viewing all articles
Browse latest Browse all 9596

Trending Articles