phi.python_builder module
PythonBuilder
helps you integrate Python's built-in functions and keywords into the DSL and it also includes a bunch of useful helpers for common stuff. phi
's global P
object is an instance of this class.
""" `PythonBuilder` helps you integrate Python's built-in functions and keywords into the DSL and it also includes a bunch of useful helpers for common stuff. `phi`'s global `P` object is an instance of this class. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from .builder import Builder from . import utils import inspect class PythonBuilder(Builder): """ This class has two types of methods: 1. Methods that start with a lowercase letter are core python functions automatically registered as methods (e.g. `phi.python_builder.PythonBuilder.map` or `phi.python_builder.PythonBuilder.sum`). 2. Methods that start with a capytal letter like `phi.python_builder.PythonBuilder.And`, `phi.python_builder.PythonBuilder.Not`, `phi.python_builder.PythonBuilder.Contains`, this is done because some mimimic keywords (`and`, `or`, `not`, etc) and its ilegal to give them these lowercase names, however, methods like `phi.python_builder.PythonBuilder.Contains` that could use lowercase are left capitalized to maintain uniformity. """ P = PythonBuilder() # built in functions _function_2_names = ["map", "filter", "reduce"] _functions_2 = [ (_name, f) for _name, f in __builtins__.items() if _name in _function_2_names ] for _name, f in __builtins__.items(): try: if hasattr(f, "__name__") and _name[0] is not "_" and not _name[0].isupper() and _name not in _function_2_names: PythonBuilder.Register(f, "", alias=_name) except Exception as e: print(e) for _name, f in _functions_2: PythonBuilder.Register2(f, "") #custom methods @PythonBuilder.Register("phi.python_builder.", explain=False) def Not(a): """ **Not** Not() <=> lambda a: not a Returns a function that negates the input argument. ** Examples ** from phi import P assert True == P.Pipe( 1, P + 1, # 1 + 1 == 2 P > 5, # 2 > 5 == False P.Not() # not False == True ) or shorter from phi import P assert True == P.Pipe( 1, (P + 1 > 5).Not() # not 1 + 1 > 5 == not 2 > 5 == not False == True ) or just from phi import P f = (P + 1 > 5).Not() assert f(1) == True """ return not a @PythonBuilder.Register("phi.python_builder.", explain=False) def Contains(a, b): """ **Contains** Contains(b) <=> lambda a: b in a Returns a partial function which when executed determines whether the argument partially applied is contained in the value being passed down. ** Examples ** from phi import P assert False == P.Pipe( [1,2,3,4], P .filter(P % 2 != 0) #[1, 3], keeps odds .Contains(4) #4 in [1, 3] == False ) """ return b in a @PythonBuilder.Register("phi.python_builder.", explain=False) def In(a, b): """ **In** In(b) <=> lambda a: a in b Returns a partial function which when executed determines whether the argument partially applied contains the value being passed down. ** Examples ** from phi import P assert False == P.Pipe( 3, P * 2, #3 * 2 == 6 P.In([1,2,3,4]) #6 in [1,2,3,4] == False ) """ return a in b @PythonBuilder.Register("phi.python_builder.", explain=False) def First(a): """ **First** First() <=> lambda a: a[0] Returns a function which when executed returns the first element of the iterable being passed. ** Examples ** from phi import P assert 3 == P.Pipe( range(1, 10), P #[1, 2, ..., 8, 9] .filter(P % 3 == 0) #[3, 6, 9] .First() # [3, 6, 9][0] == 3 ) """ return next(iter(a)) @PythonBuilder.Register("phi.python_builder.", explain=False) def Last(a): """ **Last** Last() <=> lambda a: a[-1] Returns a function which when executed returns the last element of the iterable being passed. ** Examples ** from phi import P assert 3 == P.Pipe( range(1, 10), P #[1, 2, ..., 8, 9] .filter(P % 3 == 0) #[3, 6, 9] .Last() # [3, 6, 9][-1] == 9 ) """ return list(a)[-1] @PythonBuilder.Register("phi.python_builder.", explain=False) def Flatten(a): return utils.flatten(a) __all__ = ["PythonBuilder"]
Classes
class PythonBuilder
This class has two types of methods:
- Methods that start with a lowercase letter are core python functions automatically registered as methods (e.g.
map
orsum
). - Methods that start with a capytal letter like
phi.python_builder.PythonBuilder.And
,Not
,Contains
, this is done because some mimimic keywords (and
,or
,not
, etc) and its ilegal to give them these lowercase names, however, methods likeContains
that could use lowercase are left capitalized to maintain uniformity.
class PythonBuilder(Builder): """ This class has two types of methods: 1. Methods that start with a lowercase letter are core python functions automatically registered as methods (e.g. `phi.python_builder.PythonBuilder.map` or `phi.python_builder.PythonBuilder.sum`). 2. Methods that start with a capytal letter like `phi.python_builder.PythonBuilder.And`, `phi.python_builder.PythonBuilder.Not`, `phi.python_builder.PythonBuilder.Contains`, this is done because some mimimic keywords (`and`, `or`, `not`, etc) and its ilegal to give them these lowercase names, however, methods like `phi.python_builder.PythonBuilder.Contains` that could use lowercase are left capitalized to maintain uniformity. """
Ancestors (in MRO)
- PythonBuilder
- phi.builder.Builder
- phi.dsl.Expression
- __builtin__.object
Static methods
def Context(
*args)
Builder Core. Also available as a global function as phi.Context
.
Returns the context object of the current dsl.With
statemente.
Arguments
- *args: By design
Context
accepts any number of arguments and completely ignores them.
This is a classmethod and it doesnt return a Builder
/Expression
by design so it can be called directly:
from phi import P, Context, Obj def read_file(z): f = Context() return f.read() lines = P.Pipe( "text.txt", P.With( open, read_file, Obj.split("\n") ) )
Here we called Context
with no arguments to get the context back, however, since you can also give this function an argument (which it will ignore) it can be passed to the DSL so we can rewrite the previous as:
from phi import P, Context, Obj lines = P.Pipe( "text.txt", P.With( open, Context, # f Obj.read() Obj.split("\n") ) )
Context
yields an exception when used outside of a With
block.
Also see
phi.builder.Builder.Obj
- dsl
@staticmethod def Context(*args): """ ilder Core**. Also available as a global function as `phi.Context`. rns the context object of the current `dsl.With` statemente. guments** *args**: By design `Context` accepts any number of arguments and completely ignores them. is a classmethod and it doesnt return a `Builder`/`Expression` by design so it can be called directly: from phi import P, Context, Obj def read_file(z): f = Context() return f.read() lines = P.Pipe( "text.txt", P.With( open, read_file, Obj.split("\\n") ) ) we called `Context` with no arguments to get the context back, however, since you can also give this function an argument (which it will ignore) it can be passed to the DSL so we can rewrite the previous as: from phi import P, Context, Obj lines = P.Pipe( "text.txt", P.With( open, Context, # f Obj.read() Obj.split("\\n") ) ) text` yields an exception when used outside of a `With` block. so see** hi.builder.Builder.Obj` sl](https://cgarciae.github.io/phi/dsl.m.html) """ if _WithContextManager.WITH_GLOBAL_CONTEXT is utils.NO_VALUE: raise Exception("Cannot use 'Context' outside of a 'With' block") return _WithContextManager.WITH_GLOBAL_CONTEXT
Instance variables
var Obj
Obj
is a property
that returns an object that defines the __getattr__
method which when called helps you create a partial that emulates a method call. The following expression
Obj.some_method(x1, x2, ...)
is equivalent to
lambda obj: obj.some_method(x1, x2, ...)
Examples
from phi import P, Obj assert "hello world" == P.Pipe( " HELLO HELLO {0} ", Obj.format("WORLD"), # " HELLO HELLO WORLD " Obj.strip(), # "HELLO HELLO WORLD" Obj.lower() # "hello hello world" Obj.split(' ') # ["hello", "hello", "world"] Obj.count("hello") # 2 )
Also see
phi.builder.Builder.Rec
- dsl.Write
phi.builder.Builder.Write
var Read
Giving names and saving parts of your computation to use then latter is useful to say the least. In Phi the expression
Write(x = expr)
creates a reference x
given the value of expr
which you can call latter. To read the previous you would use any of the following expressions
Read('x') Read.x
Example
Lets see a common situation where you would use this
from phi import P, List, Seq, Read, Write result = P.Pipe( input, Write(ref = f1), f2, List( f3 , Seq( Read('ref'), f4 ) ) )
Here you save the value outputed by fun_1
and the load it as the initial value of the second branch. In normal python the previous would be almost equivalent to
x = f1(input) ref = x x = f2(x) result = [ f3(x) , f4(ref) ]
var Rec
Rec
is a property
that returns an object that defines the __getattr__
and __getitem__
methods which when called help you create lambdas that emulates a field access. The following expression
Rec.some_field
is equivalent to
lambda rec: rec.some_field
Examples
from phi import P, Obj, Rec class Point(object): def __init__(self, x, y): self.x = x self.y = y def flip_cords(self): y = self.y self.y = self.x self.x = y assert 4 == P.Pipe( Point(1, 2), # point(x=1, y=2) Obj.flip_cords(), # point(x=2, y=1) Rec.x, # point.x = 2 P * 2 # 2 * 2 = 4 )
Also see
phi.builder.Builder.Obj
phi.builder.Builder.Read
phi.builder.Builder.Write
var Ref
Returns an object that helps you to inmediatly create and read references.
Creating Refences
You can manually create a Ref outside the DSL using Ref
and then pass to as/to a Read or Write expression. Here is a contrived example
from phi import P r = P.Ref('r') assert [600, 3, 6] == P.Pipe( 2, P + 1, {'a'}, # a = 2 + 1 = 3 P * 2, {'b'}, # b = 3 * 2 = 6 P * 100, {'c', r }, # c = r = 6 * 100 = 600 ['c', 'a', 'b'] ) assert r() == 600
Reading Refences from the Current Context
While the expression Read.a
with return a function that will discard its argument and return the value of the reference x
in the current context, the expression Ref.x
will return the value inmediatly, this is useful when using it inside pyton lambdas.
Read.x(None) <=> Ref.x
As an example
from phi import P, Obj, Ref assert {'a': 97, 'b': 98, 'c': 99} == P.Pipe( "a b c", Obj .split(' ').Write.keys # keys = ['a', 'b', 'c'] .map(ord), # [ord('a'), ord('b'), ord('c')] == [97, 98, 99] lambda it: zip(Ref.keys, it), # [('a', 97), ('b', 98), ('c', 99)] dict # {'a': 97, 'b': 98, 'c': 99} )
Methods
def __init__(
self, f=<function state_identity at 0x7fea7e92eaa0>)
def __init__(self, f=utils.state_identity): self._f = f
def Contains(
self, *args, **kwargs)
Contains
Contains(b) <=> lambda a: b in a
Returns a partial function which when executed determines whether the argument partially applied is contained in the value being passed down.
Examples
from phi import P assert False == P.Pipe( [1,2,3,4], P .filter(P % 2 != 0) #[1, 3], keeps odds .Contains(4) #4 in [1, 3] == False )
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def Dict(
self, **branches)
def Dict(self, **branches): gs = { key : _parse(value)._f for key, value in branches.items() } def h(x, state): ys = {} for key, g in gs.items(): y, state = g(x, state) ys[key] = y return _RecordObject(**ys), state return self.__then__(h)
def Elif(
self, condition, *then, **kwargs)
See phi.dsl.Expression.If
def Elif(self, condition, *then, **kwargs): """See `phi.dsl.Expression.If`""" root = self._root ast = self._ast cond_f = _parse(condition)._f then_f = E.Seq(*then)._f else_f = utils.state_identity next_else = (cond_f, then_f, else_f) ast = _add_else(ast, next_else) g = _compile_if(ast) expr = root.__then__(g, **kwargs) expr._ast = ast expr._root = root return expr
def Else(
self, *Else, **kwargs)
See phi.dsl.Expression.If
def Else(self, *Else, **kwargs): """See `phi.dsl.Expression.If`""" root = self._root ast = self._ast next_else = E.Seq(*Else)._f ast = _add_else(ast, next_else) g = _compile_if(ast) return root.__then__(g, **kwargs)
def F(
self, expr)
def F(self, expr): return self >> expr
def First(
self, *args, **kwargs)
First
First() <=> lambda a: a[0]
Returns a function which when executed returns the first element of the iterable being passed.
Examples
from phi import P assert 3 == P.Pipe( range(1, 10), P #[1, 2, ..., 8, 9] .filter(P % 3 == 0) #[3, 6, 9] .First() # [3, 6, 9][0] == 3 )
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def Flatten(
self, *args, **kwargs)
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def If(
self, condition, *then, **kwargs)
If
If(Predicate, *Then)
Having conditionals expressions a necesity in every language, Phi includes the If
expression for such a purpose.
Arguments
- Predicate : a predicate expression uses to determine if the
Then
orElse
branches should be used. - *Then : an expression to be excecuted if the
Predicate
yieldsTrue
, since this parameter is variadic you can stack expression and they will be interpreted as a tuplephi.dsl.Seq
.
This class also includes the Elif
and Else
methods which let you write branched conditionals in sequence, however the following rules apply
- If no branch is entered the whole expression behaves like the identity
Elif
can only be used after anIf
or anotherElif
expression- Many
Elif
expressions can be stacked sequentially Else
can only be used after anIf
orElif
expression
Examples
from phi import P, If assert "Between 2 and 10" == P.Pipe( 5, If(P > 10, "Greater than 10" ).Elif(P < 2, "Less than 2" ).Else( "Between 2 and 10" ) )
def If(self, condition, *then, **kwargs): """ ** If(Predicate, *Then) ng conditionals expressions a necesity in every language, Phi includes the `If` expression for such a purpose. guments** Predicate** : a predicate expression uses to determine if the `Then` or `Else` branches should be used. *Then** : an expression to be excecuted if the `Predicate` yields `True`, since this parameter is variadic you can stack expression and they will be interpreted as a tuple `phi.dsl.Seq`. class also includes the `Elif` and `Else` methods which let you write branched conditionals in sequence, however the following rules apply no branch is entered the whole expression behaves like the identity lif` can only be used after an `If` or another `Elif` expression ny `Elif` expressions can be stacked sequentially lse` can only be used after an `If` or `Elif` expression xamples ** from phi import P, If assert "Between 2 and 10" == P.Pipe( 5, If(P > 10, "Greater than 10" ).Elif(P < 2, "Less than 2" ).Else( "Between 2 and 10" ) ) """ cond_f = _parse(condition)._f then_f = E.Seq(*then)._f else_f = utils.state_identity ast = (cond_f, then_f, else_f) g = _compile_if(ast) expr = self.__then__(g, **kwargs) expr._ast = ast expr._root = self return expr
def In(
self, *args, **kwargs)
In
In(b) <=> lambda a: a in b
Returns a partial function which when executed determines whether the argument partially applied contains the value being passed down.
Examples
from phi import P assert False == P.Pipe( 3, P * 2, #3 * 2 == 6 P.In([1,2,3,4]) #6 in [1,2,3,4] == False )
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def Last(
self, *args, **kwargs)
Last
Last() <=> lambda a: a[-1]
Returns a function which when executed returns the last element of the iterable being passed.
Examples
from phi import P assert 3 == P.Pipe( range(1, 10), P #[1, 2, ..., 8, 9] .filter(P % 3 == 0) #[3, 6, 9] .Last() # [3, 6, 9][-1] == 9 )
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def List(
self, *branches, **kwargs)
While Seq
is sequential, phi.dsl.Expression.List
allows you to split the computation and get back a list with the result of each path. While the list literal should be the most incarnation of this expresion, it can actually be any iterable (implements __iter__
) that is not a tuple and yields a valid expresion.
The expression
k = List(f, g)
is equivalent to
k = lambda x: [ f(x), g(x) ]
In general, the following rules apply after compilation:
General Branching
List(f0, f1, ..., fn)
is equivalent to
lambda x: [ f0(x), f1(x), ..., fn(x) ]
Composing & Branching
It is interesting to see how braching interacts with composing. The expression
Seq(f, List(g, h))
is almost equivalent to
List( Seq(f, g), Seq(f, h) )
As you see its as if f
where distributed over the List. We say almost because their implementation is different
def _lambda(x): x = f(x) return [ g(x), h(x) ]
vs
lambda x: [ g(f(x)), h(f(x)) ]
As you see f
is only executed once in the first one. Both should yield the same result if f
is a pure function.
Examples
form phi import P, List avg_word_length = P.Pipe( "1 22 333", lambda s: s.split(' '), # ['1', '22', '333'] lambda l: map(len, l), # [1, 2, 3] List( sum # 1 + 2 + 3 == 6 , len # len([1, 2, 3]) == 3 ), lambda l: l[0] / l[1] # sum / len == 6 / 3 == 2 ) assert avg_word_length == 2
The previous could also be done more briefly like this
form phi import P, Obj, List avg_word_length = P.Pipe( "1 22 333", Obj .split(' ') # ['1', '22', '333'] .map(len) # [1, 2, 3] .List( sum #sum([1, 2, 3]) == 6 , len #len([1, 2, 3]) == 3 ), P[0] / P[1] #6 / 3 == 2 ) assert avg_word_length == 2
In the example above the last expression
P[0] / P[1]
works for a couple of reasons
- The previous expression returns a list
- In general the expression
P[x]
compiles to a function with the formlambda obj: obj[x]
-
The class
Expression
(the class from which the objectP
inherits) overrides most operators to create functions easily. For example, the expression(P * 2) / (P + 1)
compile to a function of the form
lambda x: (x * 2) / (x + 1)
Check out the documentatio for Phi lambdas.
def List(self, *branches, **kwargs): """ e `Seq` is sequential, `phi.dsl.Expression.List` allows you to split the computation and get back a list with the result of each path. While the list literal should be the most incarnation of this expresion, it can actually be any iterable (implements `__iter__`) that is not a tuple and yields a valid expresion. expression k = List(f, g) quivalent to k = lambda x: [ f(x), g(x) ] eneral, the following rules apply after compilation: neral Branching** List(f0, f1, ..., fn) quivalent to lambda x: [ f0(x), f1(x), ..., fn(x) ] mposing & Branching** s interesting to see how braching interacts with composing. The expression Seq(f, List(g, h)) almost* equivalent to List( Seq(f, g), Seq(f, h) ) ou see its as if `f` where distributed over the List. We say *almost* because their implementation is different def _lambda(x): x = f(x) return [ g(x), h(x) ] lambda x: [ g(f(x)), h(f(x)) ] ou see `f` is only executed once in the first one. Both should yield the same result if `f` is a pure function. Examples form phi import P, List avg_word_length = P.Pipe( "1 22 333", lambda s: s.split(' '), # ['1', '22', '333'] lambda l: map(len, l), # [1, 2, 3] List( sum # 1 + 2 + 3 == 6 , len # len([1, 2, 3]) == 3 ), lambda l: l[0] / l[1] # sum / len == 6 / 3 == 2 ) assert avg_word_length == 2 previous could also be done more briefly like this form phi import P, Obj, List avg_word_length = P.Pipe( "1 22 333", Obj .split(' ') # ['1', '22', '333'] .map(len) # [1, 2, 3] .List( sum #sum([1, 2, 3]) == 6 , len #len([1, 2, 3]) == 3 ), P[0] / P[1] #6 / 3 == 2 ) assert avg_word_length == 2 he example above the last expression P[0] / P[1] s for a couple of reasons he previous expression returns a list n general the expression `P[x]` compiles to a function with the form `lambda obj: obj[x]` he class `Expression` (the class from which the object `P` inherits) overrides most operators to create functions easily. For example, the expression (P * 2) / (P + 1) ile to a function of the form lambda x: (x * 2) / (x + 1) k out the documentatio for Phi [lambdas](https://cgarciae.github.io/phi/lambdas.m.html). """ gs = [ _parse(code)._f for code in branches ] def h(x, state): ys = [] for g in gs: y, state = g(x, state) ys.append(y) return (ys, state) return self.__then__(h, **kwargs)
def Not(
self, *args, **kwargs)
Not
Not() <=> lambda a: not a
Returns a function that negates the input argument.
Examples
from phi import P assert True == P.Pipe( 1, P + 1, # 1 + 1 == 2 P > 5, # 2 > 5 == False P.Not() # not False == True )
or shorter
from phi import P assert True == P.Pipe( 1, (P + 1 > 5).Not() # not 1 + 1 > 5 == not 2 > 5 == not False == True )
or just
from phi import P f = (P + 1 > 5).Not() assert f(1) == True
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def PatchAt(
cls, n, module, method_wrapper=None, module_alias=None, method_name_modifier=<function identity at 0x7fea7e92ea28>, blacklist_predicate=<function <lambda> at 0x7fea7e8e27d0>, whitelist_predicate=<function <lambda> at 0x7fea7e8e2758>, return_type_predicate=<function <lambda> at 0x7fea7e8e2848>, getmembers_predicate=<function isfunction at 0x7fea7fdff488>, admit_private=False, explanation=u'')
This classmethod lets you easily patch all of functions/callables from a module or class as methods a Builder class.
Arguments
- n : the position the the object being piped will take in the arguments when the function being patched is applied. See
RegisterMethod
andThenAt
. - module : a module or class from which the functions/methods/callables will be taken.
module_alias = None
: an optional alias for the module used for documentation purposes.method_name_modifier = lambda f_name: None
: a function that can modify the name of the method will take. IfNone
the name of the function will be used.blacklist_predicate = lambda f_name: name[0] != "_"
: A predicate that determines which functions are banned given their name. By default it excludes all function whose name start with'_'
.blacklist_predicate
can also be of type list, in which case all names contained in this list will be banned.whitelist_predicate = lambda f_name: True
: A predicate that determines which functions are admitted given their name. By default it include any function.whitelist_predicate
can also be of type list, in which case only names contained in this list will be admitted. You can use bothblacklist_predicate
andwhitelist_predicate
at the same time.return_type_predicate = lambda f_name: None
: a predicate that determines the_return_type
of the Builder. By default it will always returnNone
. Seephi.builder.Builder.ThenAt
.getmembers_predicate = inspect.isfunction
: a predicate that determines what type of elements/members will be fetched by theinspect
module, defaults to inspect.isfunction. See getmembers.
Examples
Lets patch ALL the main functions from numpy into a custom builder!
from phi import PythonBuilder #or Builder import numpy as np class NumpyBuilder(PythonBuilder): #or Builder "A Builder for numpy functions!" pass NumpyBuilder.PatchAt(1, np) N = NumpyBuilder(lambda x: x)
Thats it! Although a serious patch would involve filtering out functions that don't take arrays. Another common task would be to use NumpyBuilder.PatchAt(2, ...)
(PatchAt(n, ..)
in general) when convenient to send the object being pipe to the relevant argument of the function. The previous is usually done with and a combination of whitelist_predicate
s and blacklist_predicate
s on PatchAt(1, ...)
and PatchAt(2, ...)
to filter or include the approriate functions on each kind of patch. Given the previous code we could now do
import numpy as np x = np.array([[1,2],[3,4]]) y = np.array([[5,6],[7,8]]) z = N.Pipe( x, N .dot(y) .add(x) .transpose() .sum(axis=1) )
Which is strictly equivalent to
import numpy as np x = np.array([[1,2],[3,4]]) y = np.array([[5,6],[7,8]]) z = np.dot(x, y) z = np.add(z, x) z = np.transpose(z) z = np.sum(z, axis=1)
The thing to notice is that with the NumpyBuilder
we avoid the repetitive and needless passing and reassigment of the z
variable, this removes a lot of noise from our code.
@classmethod def PatchAt(cls, n, module, method_wrapper=None, module_alias=None, method_name_modifier=utils.identity, blacklist_predicate=_False, whitelist_predicate=_True, return_type_predicate=_None, getmembers_predicate=inspect.isfunction, admit_private=False, explanation=""): """ classmethod lets you easily patch all of functions/callables from a module or class as methods a Builder class. guments** n** : the position the the object being piped will take in the arguments when the function being patched is applied. See `RegisterMethod` and `ThenAt`. module** : a module or class from which the functions/methods/callables will be taken. odule_alias = None` : an optional alias for the module used for documentation purposes. ethod_name_modifier = lambda f_name: None` : a function that can modify the name of the method will take. If `None` the name of the function will be used. lacklist_predicate = lambda f_name: name[0] != "_"` : A predicate that determines which functions are banned given their name. By default it excludes all function whose name start with `'_'`. `blacklist_predicate` can also be of type list, in which case all names contained in this list will be banned. hitelist_predicate = lambda f_name: True` : A predicate that determines which functions are admitted given their name. By default it include any function. `whitelist_predicate` can also be of type list, in which case only names contained in this list will be admitted. You can use both `blacklist_predicate` and `whitelist_predicate` at the same time. eturn_type_predicate = lambda f_name: None` : a predicate that determines the `_return_type` of the Builder. By default it will always return `None`. See `phi.builder.Builder.ThenAt`. etmembers_predicate = inspect.isfunction` : a predicate that determines what type of elements/members will be fetched by the `inspect` module, defaults to [inspect.isfunction](https://docs.python.org/2/library/inspect.html#inspect.isfunction). See [getmembers](https://docs.python.org/2/library/inspect.html#inspect.getmembers). amples** patch ALL the main functions from numpy into a custom builder! from phi import PythonBuilder #or Builder import numpy as np class NumpyBuilder(PythonBuilder): #or Builder "A Builder for numpy functions!" pass NumpyBuilder.PatchAt(1, np) N = NumpyBuilder(lambda x: x) s it! Although a serious patch would involve filtering out functions that don't take arrays. Another common task would be to use `NumpyBuilder.PatchAt(2, ...)` (`PatchAt(n, ..)` in general) when convenient to send the object being pipe to the relevant argument of the function. The previous is usually done with and a combination of `whitelist_predicate`s and `blacklist_predicate`s on `PatchAt(1, ...)` and `PatchAt(2, ...)` to filter or include the approriate functions on each kind of patch. Given the previous code we could now do import numpy as np x = np.array([[1,2],[3,4]]) y = np.array([[5,6],[7,8]]) z = N.Pipe( x, N .dot(y) .add(x) .transpose() .sum(axis=1) ) h is strictly equivalent to import numpy as np x = np.array([[1,2],[3,4]]) y = np.array([[5,6],[7,8]]) z = np.dot(x, y) z = np.add(z, x) z = np.transpose(z) z = np.sum(z, axis=1) thing to notice is that with the `NumpyBuilder` we avoid the repetitive and needless passing and reassigment of the `z` variable, this removes a lot of noise from our code. """ _rtp = return_type_predicate return_type_predicate = (lambda x: _rtp) if inspect.isclass(_rtp) and issubclass(_rtp, Builder) else _rtp module_name = module_alias if module_alias else module.__name__ + '.' patch_members = _get_patch_members(module, blacklist_predicate=blacklist_predicate, whitelist_predicate=whitelist_predicate, getmembers_predicate=getmembers_predicate, admit_private=admit_private) if type(whitelist_predicate) is list and "convolution2d" in whitelist_predicate: import ipdb #ipdb.set_trace() for name, f in patch_members: wrapped = None if method_wrapper: g = method_wrapper(f) wrapped = f else: g = f cls.RegisterAt(n, g, module_name, wrapped=wrapped, _return_type=return_type_predicate(name), alias=method_name_modifier(name), explanation=explanation)
def Pipe(
self, *sequence, **kwargs)
Pipe
runs any phi.dsl.Expression
. Its highly inspired by Elixir's |> (pipe) operator.
Arguments
- *sequence: any variable amount of expressions. All expressions inside of
sequence
will be composed together usingphi.dsl.Expression.Seq
. - **kwargs:
Pipe
forwards allkwargs
tophi.builder.Builder.Seq
, visit its documentation for more info.
The expression
Pipe(*sequence, **kwargs)
is equivalent to
Seq(*sequence, **kwargs)(None)
Normally the first argument or Pipe
is a value, that is reinterpreted as a phi.dsl.Expression.Val
, therfore, the input None
is discarded.
Examples
from phi import P def add1(x): return x + 1 def mul3(x): return x * 3 x = P.Pipe( 1, #input add1, #1 + 1 == 2 mul3 #2 * 3 == 6 ) assert x == 6
The previous using lambdas to create the functions
from phi import P x = P.Pipe( 1, #input P + 1, #1 + 1 == 2 P * 3 #2 * 3 == 6 ) assert x == 6
Also see
def Pipe(self, *sequence, **kwargs): """ e` runs any `phi.dsl.Expression`. Its highly inspired by Elixir's [|> (pipe)](https://hexdocs.pm/elixir/Kernel.html#%7C%3E/2) operator. guments** *sequence**: any variable amount of expressions. All expressions inside of `sequence` will be composed together using `phi.dsl.Expression.Seq`. **kwargs**: `Pipe` forwards all `kwargs` to `phi.builder.Builder.Seq`, visit its documentation for more info. expression Pipe(*sequence, **kwargs) quivalent to Seq(*sequence, **kwargs)(None) ally the first argument or `Pipe` is a value, that is reinterpreted as a `phi.dsl.Expression.Val`, therfore, the input `None` is discarded. amples** from phi import P def add1(x): return x + 1 def mul3(x): return x * 3 x = P.Pipe( 1, #input add1, #1 + 1 == 2 mul3 #2 * 3 == 6 ) assert x == 6 previous using [lambdas](https://cgarciae.github.io/phi/lambdas.m.html) to create the functions from phi import P x = P.Pipe( 1, #input P + 1, #1 + 1 == 2 P * 3 #2 * 3 == 6 ) assert x == 6 so see** hi.builder.Builder.Seq` sl](https://cgarciae.github.io/phi/dsl.m.html) ompile](https://cgarciae.github.io/phi/dsl.m.html#phi.dsl.Compile) ambdas](https://cgarciae.github.io/phi/lambdas.m.html) """ state = kwargs.pop("refs", {}) return self.Seq(*sequence, **kwargs)(None, **state)
def ReadList(
self, *branches, **kwargs)
Same as phi.dsl.Expression.List
but any string argument x
is translated to Read(x)
.
def ReadList(self, *branches, **kwargs): """ as `phi.dsl.Expression.List` but any string argument `x` is translated to `Read(x)`. """ branches = map(lambda x: E.Read(x) if isinstance(x, str) else x, branches) return self.List(*branches, **kwargs)
def Register(
cls, *args, **kwargs)
Register(...)
is a shortcut for RegisterAt(1, ...)
Also See
phi.builder.Builder.RegisterAt
phi.builder.Builder.RegisterMethod
@classmethod def Register(cls, *args, **kwargs): """ ister(...)` is a shortcut for `RegisterAt(1, ...)` so See** hi.builder.Builder.RegisterAt` hi.builder.Builder.RegisterMethod` """ return cls.RegisterAt(1, *args, **kwargs)
def Register0(
cls, *args, **kwargs)
Register0(...)
is a shortcut for RegisterAt(0, ...)
Also See
phi.builder.Builder.RegisterAt
phi.builder.Builder.RegisterMethod
@classmethod def Register0(cls, *args, **kwargs): """ ister0(...)` is a shortcut for `RegisterAt(0, ...)` so See** hi.builder.Builder.RegisterAt` hi.builder.Builder.RegisterMethod` """ return cls.RegisterAt(0, *args, **kwargs)
def Register2(
cls, *args, **kwargs)
Register2(...)
is a shortcut for RegisterAt(2, ...)
Also See
phi.builder.Builder.RegisterAt
phi.builder.Builder.RegisterMethod
@classmethod def Register2(cls, *args, **kwargs): """ ister2(...)` is a shortcut for `RegisterAt(2, ...)` so See** hi.builder.Builder.RegisterAt` hi.builder.Builder.RegisterMethod` """ return cls.RegisterAt(2, *args, **kwargs)
def Register3(
cls, *args, **kwargs)
Register3(...)
is a shortcut for RegisterAt(3, ...)
Also See
phi.builder.Builder.RegisterAt
phi.builder.Builder.RegisterMethod
@classmethod def Register3(cls, *args, **kwargs): """ ister3(...)` is a shortcut for `RegisterAt(3, ...)` so See** hi.builder.Builder.RegisterAt` hi.builder.Builder.RegisterMethod` """ return cls.RegisterAt(3, *args, **kwargs)
def Register4(
cls, *args, **kwargs)
Register4(...)
is a shortcut for RegisterAt(4, ...)
Also See
phi.builder.Builder.RegisterAt
phi.builder.Builder.RegisterMethod
@classmethod def Register4(cls, *args, **kwargs): """ ister4(...)` is a shortcut for `RegisterAt(4, ...)` so See** hi.builder.Builder.RegisterAt` hi.builder.Builder.RegisterMethod` """ return cls.RegisterAt(4, *args, **kwargs)
def Register5(
cls, *args, **kwargs)
Register5(...)
is a shortcut for RegisterAt(5, ...)
Also See
phi.builder.Builder.RegisterAt
phi.builder.Builder.RegisterMethod
@classmethod def Register5(cls, *args, **kwargs): """ ister5(...)` is a shortcut for `RegisterAt(5, ...)` so See** hi.builder.Builder.RegisterAt` hi.builder.Builder.RegisterMethod` """ return cls.RegisterAt(5, *args, **kwargs)
def RegisterAt(
cls, *args, **kwargs)
RegisterAt
RegisterAt(n, f, library_path, alias=None, original_name=None, doc=None, wrapped=None, explanation="", method_type=utils.identity, explain=True, _return_type=None)
Most of the time you don't want to register an method as such, that is, you don't care about the self
builder object, instead you want to register a function that transforms the value being piped down the DSL. For this you can use RegisterAt
so e.g.
def some_fun(obj, arg1, arg2): # code @MyBuilder.RegisterMethod("my_lib.") def some_fun_wrapper(self, arg1, arg2): return self.ThenAt(1, some_fun, arg1, arg2)
can be written directly as
@MyBuilder.RegisterAt(1, "my_lib.") def some_fun(obj, arg1, arg2): # code
For this case you can just use Register
which is a shortcut for RegisterAt(1, ...)
@MyBuilder.Register("my_lib.") def some_fun(obj, arg1, arg2): # code
Also See
phi.builder.Builder.RegisterMethod
@classmethod def RegisterAt(cls, *args, **kwargs): """ gisterAt** RegisterAt(n, f, library_path, alias=None, original_name=None, doc=None, wrapped=None, explanation="", method_type=utils.identity, explain=True, _return_type=None) of the time you don't want to register an method as such, that is, you don't care about the `self` builder object, instead you want to register a function that transforms the value being piped down the DSL. For this you can use `RegisterAt` so e.g. def some_fun(obj, arg1, arg2): # code @MyBuilder.RegisterMethod("my_lib.") def some_fun_wrapper(self, arg1, arg2): return self.ThenAt(1, some_fun, arg1, arg2) be written directly as @MyBuilder.RegisterAt(1, "my_lib.") def some_fun(obj, arg1, arg2): # code this case you can just use `Register` which is a shortcut for `RegisterAt(1, ...)` @MyBuilder.Register("my_lib.") def some_fun(obj, arg1, arg2): # code so See** hi.builder.Builder.RegisterMethod` """ unpack_error = True try: n, f, library_path = args unpack_error = False cls._RegisterAt(n, f, library_path, **kwargs) except: if not unpack_error: raise def register_decorator(f): n, library_path = args cls._RegisterAt(n, f, library_path, **kwargs) return f return register_decorator
def RegisterMethod(
cls, *args, **kwargs)
RegisterMethod
RegisterMethod(f, library_path, alias=None, original_name=None, doc=None, wrapped=None, explanation="", method_type=utils.identity, explain=True)
classmethod
for registering functions as methods of this class.
Arguments
- f : the particular function being registered as a method
- library_path : library from where
f
comes from, unless you pass an empty string, put a period"."
at the end of the library name. alias=None
: alias for the name/method being registeredoriginal_name=None
: name of the original function, used for documentation purposes.doc=None
: complete documentation of the method being registeredwrapped=None
: if you are registering a function which wraps around another function, pass this other function throughwrapped
to get better documentation, this is specially useful is you register a bunch of functions in a for loop. Please include anexplanation
to tell how the actual function differs from the wrapped one.explanation=""
: especify any additional information for the documentation of the method being registered, you can use any of the following format tags within this string and they will be replace latter on:{original_name}
,{name}
,{fn_docs}
,{library_path}
,{builder_class}
.method_type=identity
: by default its applied but does nothing, you might also want to register functions asproperty
,classmethod
,staticmethod
explain=True
: decide whether or not to show any kind of explanation, its useful to set it toFalse
if you are using aRegister*
decorator and will only use the function as a registered method.
A main feature of phi
is that it enables you to integrate your library or even an existing library with the DSL. You can achieve three levels of integration
- Passing your functions to the DSL. This a very general machanism -since you could actually do everything with python lamdas- but in practice functions often receive multiple parameters.
- Creating partials with the
Then*
method family. Using this you could integrate any function, but it will add a lot of noise if you use heavily on it. - Registering functions as methods of a
Builder
derived class. This produces the most readable code and its the approach you should take if you want to create a Phi-based library or a helper class.
While point 3 is the most desirable it has a cost: you need to create your own phi.builder.Builder
-derived class. This is because SHOULD NOT register functions to existing builders e.g. the phi.builder.Builder
or PythonBuilder provided by phi because that would pollute the P
object. Instead you should create a custom class that derives from phi.builder.Builder
, PythonBuilder or another custom builder depending on your needs and register your functions to that class.
Examples
Say you have a function on a library called "my_lib"
def some_fun(obj, arg1, arg2): # code
You could use it with the dsl like this
from phi import P, Then P.Pipe( input, ... Then(some_fun, arg1, arg2) ... )
assuming the first parameter obj
is being piped down. However if you do this very often or you are creating a library, you are better off creating a custom class derived from Builder
or PythonBuilder
from phi import Builder #or PythonBuilder class MyBuilder(Builder): # or PythonBuilder pass
and registering your function as a method. The first way you could do this is by creating a wrapper function for some_fun
and registering it as a method
def some_fun_wrapper(self, arg1, arg2): return self.Then(some_fun, arg1, arg2) MyBuilder.RegisterMethod(some_fun_wrapper, "my_lib.", wrapped=some_fun)
Here we basically created a shortcut for the original expression Then(some_fun, arg1, arg2)
. You could also do this using a decorator
@MyBuilder.RegisterMethod("my_lib.", wrapped=some_fun) def some_fun_wrapper(self, arg1, arg2): return self.Then(some_fun, arg1, arg2)
However, this is such a common task that we've created the method Register
to avoid you from having to create the wrapper. With it you could register the function some_fun
directly as a method like this
MyBuilder.Register(some_fun, "my_lib.")
or by using a decorator over the original function definition
@MyBuilder.Register("my_lib.") def some_fun(obj, arg1, arg2): # code
Once done you've done any of the previous approaches you can create a custom global object e.g. M
and use it instead of/along with P
M = MyBuilder(lambda x: x) M.Pipe( input, ... M.some_fun(arg1, args) ... )
Argument position
phi.builder.Builder.Register
internally uses phi.builder.Builder.Then
, this is only useful if the object being piped is intended to be passed as the first argument of the function being registered, if this is not the case you could use phi.builder.Builder.Register2
, phi.builder.Builder.Register3
, ..., phi.builder.Builder.Register5
or phi.builder.Builder.RegisterAt
to set an arbitrary position, these functions will internally use phi.builder.Builder.Then2
, phi.builder.Builder.Then3
, ..., phi.builder.Builder.Then5
or phi.builder.Builder.ThenAt
respectively.
Wrapping functions
Sometimes you have an existing function that you would like to modify slightly so it plays nicely with the DSL, what you normally do is create a function that wraps around it and passes the arguments to it in a way that is convenient
import some_lib @MyBuilder.Register("some_lib.") def some_fun(a, n): return some_lib.some_fun(a, n - 1) # forward the args, n slightly modified
When you do this -as a side effect- you loose the original documentation, to avoid this you can use the Registers wrapped
argument along with the explanation
argument to clarity the situation
import some_lib some_fun_explanation = "However, it differs in that `n` is automatically subtracted `1`" @MyBuilder.Register("some_lib.", wrapped=some_lib.some_fun, explanation=some_fun_explanation) def some_fun(a, n): return some_lib.some_fun(a, n - 1) # forward the args, n slightly modified
Now the documentation for MyBuilder.some_fun
will be a little bit nicer since it includes the original documentation from some_lib.some_fun
. This behaviour is specially useful if you are wrapping an entire 3rd party library, you usually automate the process iterating over all the funcitions in a for loop. The phi.builder.Builder.PatchAt
method lets you register and entire module using a few lines of code, however, something you have to do thing more manually and do the iteration yourself.
See Also
phi.builder.Builder.PatchAt
phi.builder.Builder.RegisterAt
@classmethod def RegisterMethod(cls, *args, **kwargs): """ gisterMethod** RegisterMethod(f, library_path, alias=None, original_name=None, doc=None, wrapped=None, explanation="", method_type=utils.identity, explain=True) ssmethod` for registering functions as methods of this class. guments** f** : the particular function being registered as a method library_path** : library from where `f` comes from, unless you pass an empty string, put a period `"."` at the end of the library name. lias=None` : alias for the name/method being registered riginal_name=None` : name of the original function, used for documentation purposes. oc=None` : complete documentation of the method being registered rapped=None` : if you are registering a function which wraps around another function, pass this other function through `wrapped` to get better documentation, this is specially useful is you register a bunch of functions in a for loop. Please include an `explanation` to tell how the actual function differs from the wrapped one. xplanation=""` : especify any additional information for the documentation of the method being registered, you can use any of the following format tags within this string and they will be replace latter on: `{original_name}`, `{name}`, `{fn_docs}`, `{library_path}`, `{builder_class}`. ethod_type=identity` : by default its applied but does nothing, you might also want to register functions as `property`, `classmethod`, `staticmethod` xplain=True` : decide whether or not to show any kind of explanation, its useful to set it to `False` if you are using a `Register*` decorator and will only use the function as a registered method. in feature of `phi` is that it enables you to integrate your library or even an existing library with the DSL. You can achieve three levels of integration assing your functions to the DSL. This a very general machanism -since you could actually do everything with python lamdas- but in practice functions often receive multiple parameters. reating partials with the `Then*` method family. Using this you could integrate any function, but it will add a lot of noise if you use heavily on it. egistering functions as methods of a `Builder` derived class. This produces the most readable code and its the approach you should take if you want to create a Phi-based library or a helper class. e point 3 is the most desirable it has a cost: you need to create your own `phi.builder.Builder`-derived class. This is because SHOULD NOT register functions to existing builders e.g. the `phi.builder.Builder` or [PythonBuilder](https://cgarciae.github.io/phi/builder.m.html#phi.python_builder.PythonBuilder) provided by phi because that would pollute the `P` object. Instead you should create a custom class that derives from `phi.builder.Builder`, [PythonBuilder](https://cgarciae.github.io/phi/builder.m.html#phi.python_builder.PythonBuilder) or another custom builder depending on your needs and register your functions to that class. amples** you have a function on a library called `"my_lib"` def some_fun(obj, arg1, arg2): # code could use it with the dsl like this from phi import P, Then P.Pipe( input, ... Then(some_fun, arg1, arg2) ... ) ming the first parameter `obj` is being piped down. However if you do this very often or you are creating a library, you are better off creating a custom class derived from `Builder` or `PythonBuilder` from phi import Builder #or PythonBuilder class MyBuilder(Builder): # or PythonBuilder pass registering your function as a method. The first way you could do this is by creating a wrapper function for `some_fun` and registering it as a method def some_fun_wrapper(self, arg1, arg2): return self.Then(some_fun, arg1, arg2) MyBuilder.RegisterMethod(some_fun_wrapper, "my_lib.", wrapped=some_fun) we basically created a shortcut for the original expression `Then(some_fun, arg1, arg2)`. You could also do this using a decorator @MyBuilder.RegisterMethod("my_lib.", wrapped=some_fun) def some_fun_wrapper(self, arg1, arg2): return self.Then(some_fun, arg1, arg2) ver, this is such a common task that we've created the method `Register` to avoid you from having to create the wrapper. With it you could register the function `some_fun` directly as a method like this MyBuilder.Register(some_fun, "my_lib.") y using a decorator over the original function definition @MyBuilder.Register("my_lib.") def some_fun(obj, arg1, arg2): # code done you've done any of the previous approaches you can create a custom global object e.g. `M` and use it instead of/along with `P` M = MyBuilder(lambda x: x) M.Pipe( input, ... M.some_fun(arg1, args) ... ) gument position** .builder.Builder.Register` internally uses `phi.builder.Builder.Then`, this is only useful if the object being piped is intended to be passed as the first argument of the function being registered, if this is not the case you could use `phi.builder.Builder.Register2`, `phi.builder.Builder.Register3`, ..., `phi.builder.Builder.Register5` or `phi.builder.Builder.RegisterAt` to set an arbitrary position, these functions will internally use `phi.builder.Builder.Then2`, `phi.builder.Builder.Then3`, ..., `phi.builder.Builder.Then5` or `phi.builder.Builder.ThenAt` respectively. apping functions** times you have an existing function that you would like to modify slightly so it plays nicely with the DSL, what you normally do is create a function that wraps around it and passes the arguments to it in a way that is convenient import some_lib @MyBuilder.Register("some_lib.") def some_fun(a, n): return some_lib.some_fun(a, n - 1) # forward the args, n slightly modified you do this -as a side effect- you loose the original documentation, to avoid this you can use the Registers `wrapped` argument along with the `explanation` argument to clarity the situation import some_lib some_fun_explanation = "However, it differs in that `n` is automatically subtracted `1`" @MyBuilder.Register("some_lib.", wrapped=some_lib.some_fun, explanation=some_fun_explanation) def some_fun(a, n): return some_lib.some_fun(a, n - 1) # forward the args, n slightly modified the documentation for `MyBuilder.some_fun` will be a little bit nicer since it includes the original documentation from `some_lib.some_fun`. This behaviour is specially useful if you are wrapping an entire 3rd party library, you usually automate the process iterating over all the funcitions in a for loop. The `phi.builder.Builder.PatchAt` method lets you register and entire module using a few lines of code, however, something you have to do thing more manually and do the iteration yourself. e Also** hi.builder.Builder.PatchAt` hi.builder.Builder.RegisterAt` """ unpack_error = True try: f, library_path = args unpack_error = False cls._RegisterMethod(f, library_path, **kwargs) except: if not unpack_error: raise def register_decorator(f): library_path, = args cls._RegisterMethod(f, library_path, **kwargs) return f return register_decorator
def Seq(
self, *sequence, **kwargs)
Seq
is used to express function composition. The expression
Seq(f, g)
be equivalent to
lambda x: g(f(x))
As you see, its a little different from the mathematical definition. Excecution order flow from left to right, this makes reading and reasoning about code way more easy. This bahaviour is based upon the |>
(pipe) operator found in languages like F#, Elixir and Elm. You can pack as many expressions as you like and they will be applied in order to the data that is passed through them when compiled an excecuted.
In general, the following rules apply for Seq:
General Sequence
Seq(f0, f1, ..., fn-1, fn)
is equivalent to
lambda x: fn(fn-1(...(f1(f0(x)))))
Single Function
Seq(f)
is equivalent to
f
Identity
The empty Seq
Seq()
is equivalent to
lambda x: x
Examples
from phi import P, Seq f = Seq( P * 2, P + 1, P ** 2 ) assert f(1) == 9 # ((1 * 2) + 1) ** 2
The previous example using P.Pipe
from phi import P assert 9 == P.Pipe( 1, P * 2, #1 * 2 == 2 P + 1, #2 + 1 == 3 P ** 2 #3 ** 2 == 9 )
def Seq(self, *sequence, **kwargs): """ ` is used to express function composition. The expression Seq(f, g) quivalent to lambda x: g(f(x)) ou see, its a little different from the mathematical definition. Excecution order flow from left to right, this makes reading and reasoning about code way more easy. This bahaviour is based upon the `|>` (pipe) operator found in languages like F#, Elixir and Elm. You can pack as many expressions as you like and they will be applied in order to the data that is passed through them when compiled an excecuted. eneral, the following rules apply for Seq: neral Sequence** Seq(f0, f1, ..., fn-1, fn) quivalent to lambda x: fn(fn-1(...(f1(f0(x))))) ngle Function** Seq(f) quivalent to f entity** empty Seq Seq() quivalent to lambda x: x Examples from phi import P, Seq f = Seq( P * 2, P + 1, P ** 2 ) assert f(1) == 9 # ((1 * 2) + 1) ** 2 previous example using `P.Pipe` from phi import P assert 9 == P.Pipe( 1, P * 2, #1 * 2 == 2 P + 1, #2 + 1 == 3 P ** 2 #3 ** 2 == 9 ) """ fs = [ _parse(elem)._f for elem in sequence ] def g(x, state): return functools.reduce(lambda args, f: f(*args), fs, (x, state)) return self.__then__(g, **kwargs)
def Set(
self, *expressions, **kwargs)
def Set(self, *expressions, **kwargs): return self.List(*expressions) >> set
def Then(
self, f, *args, **kwargs)
Then(f, ...)
is equivalent to ThenAt(1, f, ...)
. Checkout phi.builder.Builder.ThenAt
for more information.
def Then(self, f, *args, **kwargs): """ n(f, ...)` is equivalent to `ThenAt(1, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. """ return self.ThenAt(1, f, *args, **kwargs)
def Then0(
self, f, *args, **kwargs)
Then0(f, ...)
is equivalent to ThenAt(0, f, ...)
. Checkout phi.builder.Builder.ThenAt
for more information.
def Then0(self, f, *args, **kwargs): """ n0(f, ...)` is equivalent to `ThenAt(0, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. """ return self.ThenAt(0, f, *args, **kwargs)
def Then1(
self, f, *args, **kwargs)
Then(f, ...)
is equivalent to ThenAt(1, f, ...)
. Checkout phi.builder.Builder.ThenAt
for more information.
def Then(self, f, *args, **kwargs): """ n(f, ...)` is equivalent to `ThenAt(1, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. """ return self.ThenAt(1, f, *args, **kwargs)
def Then2(
self, f, arg1, *args, **kwargs)
Then2(f, ...)
is equivalent to ThenAt(2, f, ...)
. Checkout phi.builder.Builder.ThenAt
for more information.
def Then2(self, f, arg1, *args, **kwargs): """ n2(f, ...)` is equivalent to `ThenAt(2, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. """ args = (arg1,) + args return self.ThenAt(2, f, *args, **kwargs)
def Then3(
self, f, arg1, arg2, *args, **kwargs)
Then3(f, ...)
is equivalent to ThenAt(3, f, ...)
. Checkout phi.builder.Builder.ThenAt
for more information.
def Then3(self, f, arg1, arg2, *args, **kwargs): """ n3(f, ...)` is equivalent to `ThenAt(3, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. """ args = (arg1, arg2) + args return self.ThenAt(3, f, *args, **kwargs)
def Then4(
self, f, arg1, arg2, arg3, *args, **kwargs)
Then4(f, ...)
is equivalent to ThenAt(4, f, ...)
. Checkout phi.builder.Builder.ThenAt
for more information.
def Then4(self, f, arg1, arg2, arg3, *args, **kwargs): """ n4(f, ...)` is equivalent to `ThenAt(4, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. """ args = (arg1, arg2, arg3) + args return self.ThenAt(4, f, *args, **kwargs)
def Then5(
self, f, arg1, arg2, arg3, arg4, *args, **kwargs)
Then5(f, ...)
is equivalent to ThenAt(5, f, ...)
. Checkout phi.builder.Builder.ThenAt
for more information.
def Then5(self, f, arg1, arg2, arg3, arg4, *args, **kwargs): """ n5(f, ...)` is equivalent to `ThenAt(5, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. """ args = (arg1, arg2, arg3, arg4) + args return self.ThenAt(5, f, *args, **kwargs)
def ThenAt(
self, n, f, *_args, **kwargs)
ThenAt
enables you to create a partially apply many arguments to a function, the returned partial expects a single arguments which will be applied at the n
th position of the original function.
Arguments
- n: position at which the created partial will apply its awaited argument on the original function.
- f: function which the partial will be created.
- _args & kwargs: all
*_args
and**kwargs
will be passed to the functionf
. _return_type = None
: type of the returnedbuilder
, ifNone
it will return the same type of the currentbuilder
. This special kwarg will NOT be passed tof
.
You can think of n
as the position that the value being piped down will pass through the f
. Say you have the following expression
D == fun(A, B, C)
all the following are equivalent
from phi import P, Pipe, ThenAt D == Pipe(A, ThenAt(1, fun, B, C)) D == Pipe(B, ThenAt(2, fun, A, C)) D == Pipe(C, ThenAt(3, fun, A, B))
you could also use the shortcuts Then
, Then2
,..., Then5
, which are more readable
from phi import P, Pipe D == Pipe(A, P.Then(fun, B, C)) D == Pipe(B, P.Then2(fun, A, C)) D == Pipe(C, P.Then3(fun, A, B))
There is a special case not discussed above: n = 0
. When this happens only the arguments given will be applied to f
, this method it will return a partial that expects a single argument but completely ignores it
from phi import P D == Pipe(None, P.ThenAt(0, fun, A, B, C)) D == Pipe(None, P.Then0(fun, A, B, C))
Examples
Max of 6 and the argument:
from phi import P assert 6 == P.Pipe( 2, P.Then(max, 6) )
Previous is equivalent to
assert 6 == max(2, 6)
Open a file in read mode ('r'
)
from phi import P f = P.Pipe( "file.txt", P.Then(open, 'r') )
Previous is equivalent to
f = open("file.txt", 'r')
Split a string by whitespace and then get the length of each word
from phi import P assert [5, 5, 5] == P.Pipe( "Again hello world", P.Then(str.split, ' ') .Then2(map, len) )
Previous is equivalent to
x = "Again hello world" x = str.split(x, ' ') x = map(len, x) assert [5, 5, 5] == x
As you see, Then2
was very useful because map
accepts and iterable
as its 2nd
parameter. You can rewrite the previous using the PythonBuilder and the phi.builder.Builder.Obj
object
from phi import P, Obj assert [5, 5, 5] == P.Pipe( "Again hello world", Obj.split(' '), P.map(len) )
Also see
phi.builder.Builder.Obj
- PythonBuilder
phi.builder.Builder.RegisterAt
def ThenAt(self, n, f, *_args, **kwargs): """ nAt` enables you to create a partially apply many arguments to a function, the returned partial expects a single arguments which will be applied at the `n`th position of the original function. guments** n**: position at which the created partial will apply its awaited argument on the original function. f**: function which the partial will be created. _args & kwargs**: all `*_args` and `**kwargs` will be passed to the function `f`. return_type = None`: type of the returned `builder`, if `None` it will return the same type of the current `builder`. This special kwarg will NOT be passed to `f`. can think of `n` as the position that the value being piped down will pass through the `f`. Say you have the following expression D == fun(A, B, C) the following are equivalent from phi import P, Pipe, ThenAt D == Pipe(A, ThenAt(1, fun, B, C)) D == Pipe(B, ThenAt(2, fun, A, C)) D == Pipe(C, ThenAt(3, fun, A, B)) could also use the shortcuts `Then`, `Then2`,..., `Then5`, which are more readable from phi import P, Pipe D == Pipe(A, P.Then(fun, B, C)) D == Pipe(B, P.Then2(fun, A, C)) D == Pipe(C, P.Then3(fun, A, B)) e is a special case not discussed above: `n = 0`. When this happens only the arguments given will be applied to `f`, this method it will return a partial that expects a single argument but completely ignores it from phi import P D == Pipe(None, P.ThenAt(0, fun, A, B, C)) D == Pipe(None, P.Then0(fun, A, B, C)) amples** of 6 and the argument: from phi import P assert 6 == P.Pipe( 2, P.Then(max, 6) ) ious is equivalent to assert 6 == max(2, 6) a file in read mode (`'r'`) from phi import P f = P.Pipe( "file.txt", P.Then(open, 'r') ) ious is equivalent to f = open("file.txt", 'r') t a string by whitespace and then get the length of each word from phi import P assert [5, 5, 5] == P.Pipe( "Again hello world", P.Then(str.split, ' ') .Then2(map, len) ) ious is equivalent to x = "Again hello world" x = str.split(x, ' ') x = map(len, x) assert [5, 5, 5] == x ou see, `Then2` was very useful because `map` accepts and `iterable` as its `2nd` parameter. You can rewrite the previous using the [PythonBuilder](https://cgarciae.github.io/phi/python_builder.m.html) and the `phi.builder.Builder.Obj` object from phi import P, Obj assert [5, 5, 5] == P.Pipe( "Again hello world", Obj.split(' '), P.map(len) ) so see** hi.builder.Builder.Obj` ythonBuilder](https://cgarciae.github.io/phi/python_builder.m.html) hi.builder.Builder.RegisterAt` """ _return_type = None n_args = n - 1 if '_return_type' in kwargs: _return_type = kwargs['_return_type'] del kwargs['_return_type'] @utils.lift def g(x): new_args = _args[0:n_args] + (x,) + _args[n_args:] if n_args >= 0 else _args return f(*new_args, **kwargs) return self.__then__(g, _return_type=_return_type)
def Tuple(
self, *expressions, **kwargs)
def Tuple(self, *expressions, **kwargs): return self.List(*expressions) >> tuple
def Val(
self, val, **kwargs)
The expression
Val(a)
is equivalent to the constant function
lambda x: a
All expression in this module interprete values that are not functions as constant functions using Val
, for example
Seq(1, P + 1)
is equivalent to
Seq(Val(1), P + 1)
The previous expression as a whole is a constant function since it will return 2
no matter what input you give it.
def Val(self, val, **kwargs): """ expression Val(a) quivalent to the constant function lambda x: a expression in this module interprete values that are not functions as constant functions using `Val`, for example Seq(1, P + 1) quivalent to Seq(Val(1), P + 1) previous expression as a whole is a constant function since it will return `2` no matter what input you give it. """ f = utils.lift(lambda z: val) return self.__then__(f, **kwargs)
def With(
self, context_manager, *body, **kwargs)
With
def With(context_manager, *body):
Arguments
- context_manager: a context manager object or valid expression from the DSL that returns a context manager.
- *body: any valid expression of the DSL to be evaluated inside the context.
*body
is interpreted as a tuple so all expression contained are composed.
As with normal python programs you sometimes might want to create a context for a block of code. You normally give a context manager to the with statemente, in Phi you use P.With
or phi.With
Context
Python's with
statemente returns a context object through as
keyword, in the DSL this object can be obtained using the P.Context
method or the phi.Context
function.
Examples
from phi import P, Obj, Context, With, Pipe text = Pipe( "text.txt", With( open, Context, Obj.read() ) )
The previous is equivalent to
with open("text.txt") as f: text = f.read()
def With(self, context_manager, *body, **kwargs): """ th** def With(context_manager, *body): guments** context_manager**: a [context manager](https://docs.python.org/2/reference/datamodel.html#context-managers) object or valid expression from the DSL that returns a context manager. *body**: any valid expression of the DSL to be evaluated inside the context. `*body` is interpreted as a tuple so all expression contained are composed. ith normal python programs you sometimes might want to create a context for a block of code. You normally give a [context manager](https://docs.python.org/2/reference/datamodel.html#context-managers) to the [with](https://docs.python.org/2/reference/compound_stmts.html#the-with-statement) statemente, in Phi you use `P.With` or `phi.With` ntext** on's `with` statemente returns a context object through `as` keyword, in the DSL this object can be obtained using the `P.Context` method or the `phi.Context` function. Examples from phi import P, Obj, Context, With, Pipe text = Pipe( "text.txt", With( open, Context, Obj.read() ) ) previous is equivalent to with open("text.txt") as f: text = f.read() """ context_f = _parse(context_manager)._f body_f = E.Seq(*body)._f def g(x, state): context, state = context_f(x, state) with context as scope: with _WithContextManager(scope): return body_f(x, state) return self.__then__(g, **kwargs)
def Write(
self, *state_args, **state_dict)
See phi.dsl.Expression.Read
def Write(self, *state_args, **state_dict): """See `phi.dsl.Expression.Read`""" if len(state_dict) + len(state_args) < 1: raise Exception("Please include at-least 1 state variable, got {0} and {1}".format(state_args, state_dict)) if len(state_dict) > 1: raise Exception("Please include at-most 1 keyword argument expression, got {0}".format(state_dict)) if len(state_dict) > 0: state_key = next(iter(state_dict.keys())) write_expr = state_dict[state_key] state_args += (state_key,) expr = self >> write_expr else: expr = self def g(x, state): update = { key: x for key in state_args } state = utils.merge(state, update) #side effect for convenience _StateContextManager.REFS.update(state) return x, state return expr.__then__(g)
def abs(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.abs(*args, **kwargs)
It accepts the same arguments as abs
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
abs(x1, *args, **kwargs)
is equivalent to
PythonBuilder.abs(*args, **kwargs)(x1)
abs
abs(number) -> number
Return the absolute value of the argument.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def all(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.all(*args, **kwargs)
It accepts the same arguments as all
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
all(x1, *args, **kwargs)
is equivalent to
PythonBuilder.all(*args, **kwargs)(x1)
all
all(iterable) -> bool
Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def any(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.any(*args, **kwargs)
It accepts the same arguments as any
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
any(x1, *args, **kwargs)
is equivalent to
PythonBuilder.any(*args, **kwargs)(x1)
any
any(iterable) -> bool
Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def apply(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.apply(*args, **kwargs)
It accepts the same arguments as apply
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
apply(x1, *args, **kwargs)
is equivalent to
PythonBuilder.apply(*args, **kwargs)(x1)
apply
apply(object[, args[, kwargs]]) -> value
Call a callable object with positional arguments taken from the tuple args, and keyword arguments taken from the optional dictionary kwargs. Note that classes are callable, as are instances with a call() method.
Deprecated since release 2.3. Instead, use the extended call syntax: function(args, *keywords).
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def basestring(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.basestring(*args, **kwargs)
It accepts the same arguments as basestring
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
basestring(x1, *args, **kwargs)
is equivalent to
PythonBuilder.basestring(*args, **kwargs)(x1)
basestring
Type basestring cannot be instantiated; it is the base for str and unicode.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def bin(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.bin(*args, **kwargs)
It accepts the same arguments as bin
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
bin(x1, *args, **kwargs)
is equivalent to
PythonBuilder.bin(*args, **kwargs)(x1)
bin
bin(number) -> string
Return the binary representation of an integer or long integer.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def bool(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.bool(*args, **kwargs)
It accepts the same arguments as bool
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
bool(x1, *args, **kwargs)
is equivalent to
PythonBuilder.bool(*args, **kwargs)(x1)
bool
bool(x) -> bool
Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def buffer(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.buffer(*args, **kwargs)
It accepts the same arguments as buffer
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
buffer(x1, *args, **kwargs)
is equivalent to
PythonBuilder.buffer(*args, **kwargs)(x1)
buffer
buffer(object [, offset[, size]])
Create a new buffer object which references the given object. The buffer will reference a slice of the target object from the start of the object (or at the specified offset). The slice will extend to the end of the target object (or with the specified size).
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def bytearray(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.bytearray(*args, **kwargs)
It accepts the same arguments as bytearray
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
bytearray(x1, *args, **kwargs)
is equivalent to
PythonBuilder.bytearray(*args, **kwargs)(x1)
bytearray
bytearray(iterable_of_ints) -> bytearray.
bytearray(string, encoding[, errors]) -> bytearray. bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray. bytearray(memory_view) -> bytearray.
Construct a mutable bytearray object from: - an iterable yielding integers in range(256) - a text string encoded using the specified encoding - a bytes or a bytearray object - any object implementing the buffer API.
bytearray(int) -> bytearray.
Construct a zero-initialized bytearray of the given length.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def bytes(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.bytes(*args, **kwargs)
It accepts the same arguments as bytes
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
bytes(x1, *args, **kwargs)
is equivalent to
PythonBuilder.bytes(*args, **kwargs)(x1)
bytes
str(object='') -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def callable(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.callable(*args, **kwargs)
It accepts the same arguments as callable
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
callable(x1, *args, **kwargs)
is equivalent to
PythonBuilder.callable(*args, **kwargs)(x1)
callable
callable(object) -> bool
Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances with a call() method.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def chr(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.chr(*args, **kwargs)
It accepts the same arguments as chr
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
chr(x1, *args, **kwargs)
is equivalent to
PythonBuilder.chr(*args, **kwargs)(x1)
chr
chr(i) -> character
Return a string of one character with ordinal i; 0 <= i < 256.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def classmethod(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.classmethod(*args, **kwargs)
It accepts the same arguments as classmethod
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
classmethod(x1, *args, **kwargs)
is equivalent to
PythonBuilder.classmethod(*args, **kwargs)(x1)
classmethod
classmethod(function) -> method
Convert a function to be a class method.
A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:
class C: def f(cls, arg1, arg2, ...): ... f = classmethod(f)
It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def cmp(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.cmp(*args, **kwargs)
It accepts the same arguments as cmp
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
cmp(x1, *args, **kwargs)
is equivalent to
PythonBuilder.cmp(*args, **kwargs)(x1)
cmp
cmp(x, y) -> integer
Return negative if x
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def coerce(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.coerce(*args, **kwargs)
It accepts the same arguments as coerce
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
coerce(x1, *args, **kwargs)
is equivalent to
PythonBuilder.coerce(*args, **kwargs)(x1)
coerce
coerce(x, y) -> (x1, y1)
Return a tuple consisting of the two numeric arguments converted to a common type, using the same rules as used by arithmetic operations. If coercion is not possible, raise TypeError.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def compile(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.compile(*args, **kwargs)
It accepts the same arguments as compile
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
compile(x1, *args, **kwargs)
is equivalent to
PythonBuilder.compile(*args, **kwargs)(x1)
compile
compile(source, filename, mode[, flags[, dont_inherit]]) -> code object
Compile the source string (a Python module, statement or expression) into a code object that can be executed by the exec statement or eval(). The filename will be used for run-time error messages. The mode must be 'exec' to compile a module, 'single' to compile a single (interactive) statement, or 'eval' to compile an expression. The flags argument, if present, controls which future statements influence the compilation of the code. The dont_inherit argument, if non-zero, stops the compilation inheriting the effects of any future statements in effect in the code calling compile; if absent or zero these statements do influence the compilation, in addition to any features explicitly specified.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def complex(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.complex(*args, **kwargs)
It accepts the same arguments as complex
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
complex(x1, *args, **kwargs)
is equivalent to
PythonBuilder.complex(*args, **kwargs)(x1)
complex
complex(real[, imag]) -> complex number
Create a complex number from a real part and an optional imaginary part. This is equivalent to (real + imag*1j) where imag defaults to 0.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def delattr(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.delattr(*args, **kwargs)
It accepts the same arguments as delattr
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
delattr(x1, *args, **kwargs)
is equivalent to
PythonBuilder.delattr(*args, **kwargs)(x1)
delattr
delattr(object, name)
Delete a named attribute on an object; delattr(x, 'y') is equivalent to ``del x.y''.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def dict(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.dict(*args, **kwargs)
It accepts the same arguments as dict
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
dict(x1, *args, **kwargs)
is equivalent to
PythonBuilder.dict(*args, **kwargs)(x1)
dict
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def dir(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.dir(*args, **kwargs)
It accepts the same arguments as dir
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
dir(x1, *args, **kwargs)
is equivalent to
PythonBuilder.dir(*args, **kwargs)(x1)
dir
dir([object]) -> list of strings
If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. If the object supplies a method named dir, it will be used; otherwise the default dir() logic is used and returns: for a module object: the module's attributes. for a class object: its attributes, and recursively the attributes of its bases. for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def divmod(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.divmod(*args, **kwargs)
It accepts the same arguments as divmod
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
divmod(x1, *args, **kwargs)
is equivalent to
PythonBuilder.divmod(*args, **kwargs)(x1)
divmod
divmod(x, y) -> (quotient, remainder)
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def enumerate(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.enumerate(*args, **kwargs)
It accepts the same arguments as enumerate
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
enumerate(x1, *args, **kwargs)
is equivalent to
PythonBuilder.enumerate(*args, **kwargs)(x1)
enumerate
enumerate(iterable[, start]) -> iterator for index, value of iterable
Return an enumerate object. iterable must be another object that supports iteration. The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument. enumerate is useful for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def eval(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.eval(*args, **kwargs)
It accepts the same arguments as eval
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
eval(x1, *args, **kwargs)
is equivalent to
PythonBuilder.eval(*args, **kwargs)(x1)
eval
eval(source[, globals[, locals]]) -> value
Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def execfile(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.execfile(*args, **kwargs)
It accepts the same arguments as execfile
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
execfile(x1, *args, **kwargs)
is equivalent to
PythonBuilder.execfile(*args, **kwargs)(x1)
execfile
execfile(filename[, globals[, locals]])
Read and execute a Python script from a file. The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def file(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.file(*args, **kwargs)
It accepts the same arguments as file
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
file(x1, *args, **kwargs)
is equivalent to
PythonBuilder.file(*args, **kwargs)(x1)
file
file(name[, mode[, buffering]]) -> file object
Open a file. The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Add a 'b' to the mode for binary files. Add a '+' to the mode to allow simultaneous reading and writing. If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. The preferred way to open a file is with the builtin open() function. Add a 'U' to mode to open the file for input with universal newline support. Any line ending in the input file will be seen as a '\n' in Python. Also, a file so opened gains the attribute 'newlines'; the value for this attribute is one of None (no newline read yet), '\r', '\n', '\r\n' or a tuple containing all the newline types seen.
'U' cannot be combined with 'w' or '+' mode.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def filter(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.filter(*args, **kwargs)
It accepts the same arguments as filter
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
filter(x1, x2, *args, **kwargs)
is equivalent to
PythonBuilder.filter(x1, *args, **kwargs)(x2)
filter
filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def float(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.float(*args, **kwargs)
It accepts the same arguments as float
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
float(x1, *args, **kwargs)
is equivalent to
PythonBuilder.float(*args, **kwargs)(x1)
float
float(x) -> floating point number
Convert a string or number to a floating point number, if possible.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def format(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.format(*args, **kwargs)
It accepts the same arguments as format
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
format(x1, *args, **kwargs)
is equivalent to
PythonBuilder.format(*args, **kwargs)(x1)
format
format(value[, format_spec]) -> string
Returns value.format(format_spec) format_spec defaults to ""
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def frozenset(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.frozenset(*args, **kwargs)
It accepts the same arguments as frozenset
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
frozenset(x1, *args, **kwargs)
is equivalent to
PythonBuilder.frozenset(*args, **kwargs)(x1)
frozenset
frozenset() -> empty frozenset object
frozenset(iterable) -> frozenset object
Build an immutable unordered collection of unique elements.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def getattr(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.getattr(*args, **kwargs)
It accepts the same arguments as getattr
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
getattr(x1, *args, **kwargs)
is equivalent to
PythonBuilder.getattr(*args, **kwargs)(x1)
getattr
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def globals(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.globals(*args, **kwargs)
It accepts the same arguments as globals
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
globals(x1, *args, **kwargs)
is equivalent to
PythonBuilder.globals(*args, **kwargs)(x1)
globals
globals() -> dictionary
Return the dictionary containing the current scope's global variables.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def hasattr(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.hasattr(*args, **kwargs)
It accepts the same arguments as hasattr
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
hasattr(x1, *args, **kwargs)
is equivalent to
PythonBuilder.hasattr(*args, **kwargs)(x1)
hasattr
hasattr(object, name) -> bool
Return whether the object has an attribute with the given name. (This is done by calling getattr(object, name) and catching exceptions.)
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def hash(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.hash(*args, **kwargs)
It accepts the same arguments as hash
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
hash(x1, *args, **kwargs)
is equivalent to
PythonBuilder.hash(*args, **kwargs)(x1)
hash
hash(object) -> integer
Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def hex(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.hex(*args, **kwargs)
It accepts the same arguments as hex
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
hex(x1, *args, **kwargs)
is equivalent to
PythonBuilder.hex(*args, **kwargs)(x1)
hex
hex(number) -> string
Return the hexadecimal representation of an integer or long integer.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def id(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.id(*args, **kwargs)
It accepts the same arguments as id
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
id(x1, *args, **kwargs)
is equivalent to
PythonBuilder.id(*args, **kwargs)(x1)
id
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.)
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def input(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.input(*args, **kwargs)
It accepts the same arguments as input
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
input(x1, *args, **kwargs)
is equivalent to
PythonBuilder.input(*args, **kwargs)(x1)
input
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def int(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.int(*args, **kwargs)
It accepts the same arguments as int
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
int(x1, *args, **kwargs)
is equivalent to
PythonBuilder.int(*args, **kwargs)(x1)
int
int(x=0) -> int or long
int(x, base=10) -> int or long
Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead.
If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal.
int('0b100', base=0) 4
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def intern(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.intern(*args, **kwargs)
It accepts the same arguments as intern
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
intern(x1, *args, **kwargs)
is equivalent to
PythonBuilder.intern(*args, **kwargs)(x1)
intern
intern(string) -> string
``Intern'' the given string. This enters the string in the (global) table of interned strings whose purpose is to speed up dictionary lookups. Return the string itself or the previously interned string object with the same value.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def isinstance(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.isinstance(*args, **kwargs)
It accepts the same arguments as isinstance
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
isinstance(x1, *args, **kwargs)
is equivalent to
PythonBuilder.isinstance(*args, **kwargs)(x1)
isinstance
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object's type. The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for isinstance(x, A) or isinstance(x, B) or ... (etc.).
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def issubclass(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.issubclass(*args, **kwargs)
It accepts the same arguments as issubclass
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
issubclass(x1, *args, **kwargs)
is equivalent to
PythonBuilder.issubclass(*args, **kwargs)(x1)
issubclass
issubclass(C, B) -> bool
Return whether class C is a subclass (i.e., a derived class) of class B. When using a tuple as the second argument issubclass(X, (A, B, ...)), is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def iter(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.iter(*args, **kwargs)
It accepts the same arguments as iter
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
iter(x1, *args, **kwargs)
is equivalent to
PythonBuilder.iter(*args, **kwargs)(x1)
iter
iter(collection) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def len(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.len(*args, **kwargs)
It accepts the same arguments as len
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
len(x1, *args, **kwargs)
is equivalent to
PythonBuilder.len(*args, **kwargs)(x1)
len
len(object) -> integer
Return the number of items of a sequence or collection.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def list(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.list(*args, **kwargs)
It accepts the same arguments as list
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
list(x1, *args, **kwargs)
is equivalent to
PythonBuilder.list(*args, **kwargs)(x1)
list
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def locals(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.locals(*args, **kwargs)
It accepts the same arguments as locals
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
locals(x1, *args, **kwargs)
is equivalent to
PythonBuilder.locals(*args, **kwargs)(x1)
locals
locals() -> dictionary
Update and return a dictionary containing the current scope's local variables.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def long(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.long(*args, **kwargs)
It accepts the same arguments as long
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
long(x1, *args, **kwargs)
is equivalent to
PythonBuilder.long(*args, **kwargs)(x1)
long
long(x=0) -> long
long(x, base=10) -> long
Convert a number or string to a long integer, or return 0L if no arguments are given. If x is floating point, the conversion truncates towards zero.
If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal.
int('0b100', base=0) 4L
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def map(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.map(*args, **kwargs)
It accepts the same arguments as map
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
map(x1, x2, *args, **kwargs)
is equivalent to
PythonBuilder.map(x1, *args, **kwargs)(x2)
map
map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function to the items of the argument sequence(s). If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence).
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def max(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.max(*args, **kwargs)
It accepts the same arguments as max
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
max(x1, *args, **kwargs)
is equivalent to
PythonBuilder.max(*args, **kwargs)(x1)
max
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def memoryview(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.memoryview(*args, **kwargs)
It accepts the same arguments as memoryview
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
memoryview(x1, *args, **kwargs)
is equivalent to
PythonBuilder.memoryview(*args, **kwargs)(x1)
memoryview
memoryview(object)
Create a new memoryview object which references the given object.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def min(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.min(*args, **kwargs)
It accepts the same arguments as min
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
min(x1, *args, **kwargs)
is equivalent to
PythonBuilder.min(*args, **kwargs)(x1)
min
min(iterable[, key=func]) -> value
min(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its smallest item. With two or more arguments, return the smallest argument.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def next(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.next(*args, **kwargs)
It accepts the same arguments as next
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
next(x1, *args, **kwargs)
is equivalent to
PythonBuilder.next(*args, **kwargs)(x1)
next
next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def object(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.object(*args, **kwargs)
It accepts the same arguments as object
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
object(x1, *args, **kwargs)
is equivalent to
PythonBuilder.object(*args, **kwargs)(x1)
object
The most base type
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def oct(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.oct(*args, **kwargs)
It accepts the same arguments as oct
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
oct(x1, *args, **kwargs)
is equivalent to
PythonBuilder.oct(*args, **kwargs)(x1)
oct
oct(number) -> string
Return the octal representation of an integer or long integer.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def open(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.open(*args, **kwargs)
It accepts the same arguments as open
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
open(x1, *args, **kwargs)
is equivalent to
PythonBuilder.open(*args, **kwargs)(x1)
open
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object. This is the preferred way to open a file. See file.doc for further information.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def ord(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.ord(*args, **kwargs)
It accepts the same arguments as ord
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
ord(x1, *args, **kwargs)
is equivalent to
PythonBuilder.ord(*args, **kwargs)(x1)
ord
ord(c) -> integer
Return the integer ordinal of a one-character string.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def pow(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.pow(*args, **kwargs)
It accepts the same arguments as pow
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
pow(x1, *args, **kwargs)
is equivalent to
PythonBuilder.pow(*args, **kwargs)(x1)
pow
pow(x, y[, z]) -> number
With two arguments, equivalent to xy. With three arguments, equivalent to (xy) % z, but may be more efficient (e.g. for longs).
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def print(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.print(*args, **kwargs)
It accepts the same arguments as print
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
print(x1, *args, **kwargs)
is equivalent to
PythonBuilder.print(*args, **kwargs)(x1)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def property(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.property(*args, **kwargs)
It accepts the same arguments as property
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
property(x1, *args, **kwargs)
is equivalent to
PythonBuilder.property(*args, **kwargs)(x1)
property
property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
fget is a function to be used for getting an attribute value, and likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x:
class C(object): def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.")
Decorators make defining new properties or modifying existing ones easy:
class C(object): @property def x(self): "I am the 'x' property." return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def range(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.range(*args, **kwargs)
It accepts the same arguments as range
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
range(x1, *args, **kwargs)
is equivalent to
PythonBuilder.range(*args, **kwargs)(x1)
range
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def raw_input(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.raw_input(*args, **kwargs)
It accepts the same arguments as raw_input
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
raw_input(x1, *args, **kwargs)
is equivalent to
PythonBuilder.raw_input(*args, **kwargs)(x1)
raw_input
raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def reduce(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.reduce(*args, **kwargs)
It accepts the same arguments as reduce
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
reduce(x1, x2, *args, **kwargs)
is equivalent to
PythonBuilder.reduce(x1, *args, **kwargs)(x2)
reduce
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def reload(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.reload(*args, **kwargs)
It accepts the same arguments as reload
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
reload(x1, *args, **kwargs)
is equivalent to
PythonBuilder.reload(*args, **kwargs)(x1)
reload
reload(module) -> module
Reload the module. The module must have been successfully imported before.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def repr(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.repr(*args, **kwargs)
It accepts the same arguments as repr
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
repr(x1, *args, **kwargs)
is equivalent to
PythonBuilder.repr(*args, **kwargs)(x1)
repr
repr(object) -> string
Return the canonical string representation of the object. For most object types, eval(repr(object)) == object.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def reversed(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.reversed(*args, **kwargs)
It accepts the same arguments as reversed
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
reversed(x1, *args, **kwargs)
is equivalent to
PythonBuilder.reversed(*args, **kwargs)(x1)
reversed
reversed(sequence) -> reverse iterator over values of the sequence
Return a reverse iterator
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def round(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.round(*args, **kwargs)
It accepts the same arguments as round
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
round(x1, *args, **kwargs)
is equivalent to
PythonBuilder.round(*args, **kwargs)(x1)
round
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def set(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.set(*args, **kwargs)
It accepts the same arguments as set
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
set(x1, *args, **kwargs)
is equivalent to
PythonBuilder.set(*args, **kwargs)(x1)
set
set() -> new empty set object
set(iterable) -> new set object
Build an unordered collection of unique elements.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def setattr(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.setattr(*args, **kwargs)
It accepts the same arguments as setattr
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
setattr(x1, *args, **kwargs)
is equivalent to
PythonBuilder.setattr(*args, **kwargs)(x1)
setattr
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ``x.y = v''.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def slice(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.slice(*args, **kwargs)
It accepts the same arguments as slice
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
slice(x1, *args, **kwargs)
is equivalent to
PythonBuilder.slice(*args, **kwargs)(x1)
slice
slice(stop)
slice(start, stop[, step])
Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def sorted(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.sorted(*args, **kwargs)
It accepts the same arguments as sorted
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
sorted(x1, *args, **kwargs)
is equivalent to
PythonBuilder.sorted(*args, **kwargs)(x1)
sorted
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def staticmethod(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.staticmethod(*args, **kwargs)
It accepts the same arguments as staticmethod
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
staticmethod(x1, *args, **kwargs)
is equivalent to
PythonBuilder.staticmethod(*args, **kwargs)(x1)
staticmethod
staticmethod(function) -> method
Convert a function to be a static method.
A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C: def f(arg1, arg2, ...): ... f = staticmethod(f)
It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class.
Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see the classmethod builtin.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def str(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.str(*args, **kwargs)
It accepts the same arguments as str
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
str(x1, *args, **kwargs)
is equivalent to
PythonBuilder.str(*args, **kwargs)(x1)
str
str(object='') -> string
Return a nice string representation of the object. If the argument is a string, the return value is the same object.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def sum(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.sum(*args, **kwargs)
It accepts the same arguments as sum
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
sum(x1, *args, **kwargs)
is equivalent to
PythonBuilder.sum(*args, **kwargs)(x1)
sum
sum(sequence[, start]) -> value
Return the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the sequence is empty, return start.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def super(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.super(*args, **kwargs)
It accepts the same arguments as super
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
super(x1, *args, **kwargs)
is equivalent to
PythonBuilder.super(*args, **kwargs)(x1)
super
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type) -> unbound super object super(type, type2) -> bound super object; requires issubclass(type2, type) Typical use to call a cooperative superclass method: class C(B): def meth(self, arg): super(C, self).meth(arg)
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def tuple(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.tuple(*args, **kwargs)
It accepts the same arguments as tuple
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
tuple(x1, *args, **kwargs)
is equivalent to
PythonBuilder.tuple(*args, **kwargs)(x1)
tuple
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items
If the argument is a tuple, the return value is the same object.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def type(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.type(*args, **kwargs)
It accepts the same arguments as type
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
type(x1, *args, **kwargs)
is equivalent to
PythonBuilder.type(*args, **kwargs)(x1)
type
type(object) -> the object's type
type(name, bases, dict) -> a new type
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def unichr(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.unichr(*args, **kwargs)
It accepts the same arguments as unichr
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
unichr(x1, *args, **kwargs)
is equivalent to
PythonBuilder.unichr(*args, **kwargs)(x1)
unichr
unichr(i) -> Unicode character
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def unicode(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.unicode(*args, **kwargs)
It accepts the same arguments as unicode
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
unicode(x1, *args, **kwargs)
is equivalent to
PythonBuilder.unicode(*args, **kwargs)(x1)
unicode
unicode(object='') -> unicode object
unicode(string[, encoding[, errors]]) -> unicode object
Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding. errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def vars(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.vars(*args, **kwargs)
It accepts the same arguments as vars
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
vars(x1, *args, **kwargs)
is equivalent to
PythonBuilder.vars(*args, **kwargs)(x1)
vars
vars([object]) -> dictionary
Without arguments, equivalent to locals(). With an argument, equivalent to object.dict.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def xrange(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.xrange(*args, **kwargs)
It accepts the same arguments as xrange
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
xrange(x1, *args, **kwargs)
is equivalent to
PythonBuilder.xrange(*args, **kwargs)(x1)
xrange
xrange(stop) -> xrange object
xrange(start, stop[, step]) -> xrange object
Like range(), but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is slightly faster than range() and more memory efficient.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)
def zip(
self, *args, **kwargs)
THIS METHOD IS AUTOMATICALLY GENERATED
PythonBuilder.zip(*args, **kwargs)
It accepts the same arguments as zip
.
However, the 1st argument is omitted, a partial with the rest of the arguments is returned which expects the 1st argument such that
zip(x1, *args, **kwargs)
is equivalent to
PythonBuilder.zip(*args, **kwargs)(x1)
zip
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.
@functools.wraps(f) def method(self, *args, **kwargs): kwargs['_return_type'] = _return_type return self.ThenAt(n, f, *args, **kwargs)