Python comes with many built-in functions which are always available as part of the language. We’ve already seen some of them in the previous sections. This page gives an overview of the most important ones.

Type conversions

The type() function returns the type of a given object:

>>> type('hello')
<type 'str'>
>>> type(1)
<type 'int'>
>>> type(33.3)
<type 'float'>

Python has several built-in functions to convert from one data type to another. These functions have the same name as the data types, so it’s easy to remember them:

str()

The str() function transforms something into a string, or creates a new empty string if called without any argument:

>>> a = str(10)
>>> a, type(a), len(a)
('10', <class 'str'>, 2)
>>> b = str()
>>> b, type(b), len(b)
('', <class 'str'>, 0)

list()

The list() function transforms something into a list, or creates a new list if called without any argument:

>>> list('abcdefghijklmn')
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
>>> L = list()
>>> L, type(L), len(L)
([], <class 'list'>, 0)

dict()

The dict() function can create a dictionary from different types of arguments, or a new empty dictionary if called without any arguments.

Here’s how we can create a new dictionary from a list of keyword/value tuples:

>>> dict([('hello', 1), ('world', 2)]
{'hello': 1, 'world': 2}

And here’s how we can create a new dictionary using keyword arguments:

dict(hello=1, world=2)
{'hello': 1, 'world': 2}

When called without any argument, dict() creates a new empty dictionary:

>>> d = dict()
>>> type(d), len(d), d
(<class 'dict'>, 0, {})

float()

The float() function transforms an integer or string into a floating point (decimal) number:

>>> float(27)
27.0

When called without any argument, float() creates a new float with value 0.0:

>>> float()
0.0

Conversion from string to float only works if the string looks like a number:

>>> float('27.0')
27.0
>>> float('27')
27.0
>>> float('27,0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '27,0'

bool()

The bool() function transforms any data type into a boolean value:

>>> bool(1)
True
>>> bool('')
False

When called without any argument, bool() returns False:

>>> bool()
False

See testing truthiness for examples of conversions from other data types.

set()

The set() function creates a new set object from a collection:

>>> set('abracadabra')
{'r', 'b', 'c', 'a', 'd'}
>>> set([1, 5, 10, 50, 10, 5, 1])
{1, 10, 50, 5}
>>> set({'a': 5, 'b': 3, 'c': 1})
{'c', 'a', 'b'}
>>> set(((10, 20), (20, 25), (10, 20)))
{(20, 25), (10, 20)}

When called without any argument, set() creates a new empty set:

>>> set()
set()

tuple()

The tuple() function creates a tuple from a collection:

tuple([1, 2, 3])
>>> (1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple({'a': 5, 'b': 3, 'c': 1})
('a', b', 'c')

When called without any argument, tuple() creates a new empty tuple:

>>> tuple()
()

Collections and loops

len()

The len() function returns the amount of items in a collection:

>>> L = ['A', 'B', [1, 2, 3], 'D']
>>> len(L)
4
>>> len('I will not buy this record, it is scratched.')
44

range()

The range() function returns an iterator which yields a sequence of numbers. It is typically used to repeat an action a number of times:

>>> range(0, 4)
range(0, 4)
>>> for i in range(4):
...     i
0
1
2
3

enumerate()

The enumerate() function returns an iterator which adds a counter to each item in a collection:

>>> L = ['Alpha', 'Bravo', 'Charlie', 'Delta']
>>> enumerate(L)
<enumerate object at 0x1039f6558>
>>> list(enumerate(L))
[(0, 'Alpha'), (1, 'Bravo'), (2, 'Charlie'), (3, 'Delta')]

The enumerate() function is typically used to loop over the items in a collection:

>>> for index, item in enumerate(L):
...     index, item
(0, 'Alpha')
(1, 'Bravo')
(2, 'Charlie')
(3, 'Delta')

sorted()

The sorted() function returns a sorted copy of a given collection. This is useful if we need to do a sorted loop without actually sorting the collection:

>>> L = ['Mike', 'Bravo', 'Charlie', 'Tango', 'Alpha']
>>> for item in sorted(L):
...     item
'Alpha'
'Bravo'
'Charlie'
'Mike'
'Tango'

reversed()

The reversed() function is similar to sorted(): it returns a copy of a given collection with the items in inverse order.

>>> for item in reversed(L):
...     item
'Alpha'
'Tango'
'Charlie'
'Bravo'
'Mike'

zip()

The zip() function takes two separate lists, and produces a new list with pairs of values (one from each list):

>>> L1 = ['A', 'B', 'D', 'E', 'F', 'G', 'H', 'I']
>>> L2 = [1, 2, 3, 4, 5, 6]
>>> zip(L1, L2)
<zip object at 0x1039f8608>
>>> list(zip(L1, L2))
[('A', 1), ('B', 2), ('D', 3), ('E', 4), ('F', 5), ('G', 6)]

The resulting list has the same amount of items as the smallest of the two lists.

The zip() function can be used to create a dictionary from a list of keys and a list of values:

>>> D = dict(zip(L1, L2))
>>> D
{'A': 1, 'B': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6}

map()

The map() function returns an iterator which applies a function to every item of a given collection. Use list() to convert the iterator into a list.

>>> def square(n):
...     return n*n
...
>>> L1 = [13, 27, 4, 19, 22]
>>> L2 = list(map(square, L1))
>>>
>>> print(L2)
[169, 729, 16, 361, 484]

Expressions with map() can be rewritten using list comprehensions:

>>> L2 = [square(n) for n in L1]

The map() function may also take multiple collections, and pass multiple arguments to the function at each iteration.

>>> def calculate(v1, v2, v3):
...     return v1 * v2 - v3
...
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [11, 12, 13, 14, 15, 16]
>>> L3 = [21, 22, 23, 24, 25, 26, 27]
>>> L4 = list(map(calculate, L1, L2, L3))
>>>
>>> print(L4)
[-10, 2, 16, 32, 50]

If the given collections have different lengths, the iterator will stop when the shortest one (L1) reaches its end.

filter()

The filter() function takes a function and a collection as arguments, and returns an iterator which produces a list containing only those items from the original list for which the given function returns True.

>>> def test(n):
...     return n > 10
...
>>> L1 = [3, 21, 7, 9, 14, 33, 11, 8]
>>> L2 = list(filter(test, L1))
>>>
>>> print(L2)
[21, 14, 33, 11]

Numerical

Some built-in functions are useful when working with numbers:

abs()

The abs() function returns the absolute value of a number:

>>> abs(-100)
100

sum()

The sum() function returns the sum of all numbers in a list:

>>> L = [10, 300.7, 50, 33.1]
>>> sum(L)
393.8

min() and max()

The min() function returns the smallest number in a list of numbers:

>>> min(L)
10

The max() function returns the largest number in a list of numbers:

>>> max(L)
300.7

round()

The round() function rounds a number to a given precision.

When called without any argument, round() converts a float to the nearest integer:

>>> round(3.1416)
3

If two multiples are equally close, rounding is done toward the even number:

>>> round(0.5)
0
>>> round(1.5)
2

The round() function can also take a second argument to specify the amount of digits to round after the decimal point:

>>> round(3.141592653589793, 4)
3.1416

Boolean

any()

The built-in function any() evaluates all statements in a collection and returns:

  • True if at least one statement is True
  • False if all statements are False
>>> any([0, 0, 0, 0])
False
>>> any([0, 0, 1, 0])
True

all()

The built-in function all() evaluates all statements in a collection, and returns:

  • True if all statements are True
  • False if at least one statement is False
>>> all([0, 0, 0, 0])
False
>>> all([0, 0, 1, 0])
False
>>> all([1, 1, 1, 1])
True

Attributes

dir()

The dir() function returns a list of names (attributes and methods) in a given object. This is useful to get an idea of how an object is structured and what it can do.

Here’s an example using dir() to view the contents of an imported module:

>>> import math
>>> dir(math)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

When called without any argument, dir() returns a list of names in the current local scope.

If you’re starting a new interactive session in Terminal, dir() will return only private attributes and methods (with names starting with double underscores) which are made available by the Python language:

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

Variable names declared during the session are added to the local scope, and are included in dir() results too:

>>> 'myVariable' in dir()
False
>>> myVariable = 120
>>> 'myVariable' in dir()
True

If you are scripting in RoboFont, you can use dir() to see that all the main fontParts.world objects are available out of the box in the Scripting Window:

print(dir())
['AllFonts', 'CreateCursor', 'CurrentAnchors', 'CurrentComponents', 'CurrentContours', 'CurrentFont', 'CurrentGlyph', 'CurrentGuidelines', 'CurrentLayer', 'CurrentPoints', 'CurrentSegments', 'FontsList', 'NewFont', 'OpenFont', 'OpenWindow', 'RAnchor', 'RComponent', 'RContour', 'RFeatures', 'RFont', 'RGlyph', 'RGroups', 'RInfo', 'RKerning', '__builtins__', '__file__', '__name__', 'help']

getattr()

The getattr() function is used to get an attribute from a given object. Instead of accessing the attribute directly, we pass the object and the attribute name to the getattr() function, and get a value back. This ‘indirect’ approach allows us to write code that is more abstract and more reflexive.

Here’s a simple example using an open font in RoboFont. Let’s imagine that we want to print out some font info attributes. We could access them directly one by one, like this:

font = CurrentFont()
print(font.info.familyName)
print(font.info.styleName)
print(font.info.openTypeNameDesigner)
RoboType
Roman
Frederik Berlaen

Using getattr(), we can separate the definition of the attribute names from the retrieval of the values:

attrs = ['familyName', 'styleName', 'openTypeNameDesigner']
for attr in attrs:
    print(getattr(font.info, attr))

setattr()

The setattr() function is complementary to getattr() – it allows us to set the value of an object’s attribute.

Here’s an example script which sets some font info values in the current font. The font info is defined in a dictionary, but it could be coming from an external file or a dialog.

font = CurrentFont()

fontInfo = {
  'familyName' : 'MyFamily',
  'styleName' : 'Black Italic',
  'styleMapFamilyName' : 'Black',
  'styleMapStyleName' : 'italic',
}

for attr, value in fontInfo.items():
    setattr(font.info, attr, value)

There’s also a delattr() function to delete an attribute from an object.

Character encoding

chr()

The chr() function returns a unicode character for a given unicode value (as a decimal number):

>>> chr(192)
'À'

ord()

The ord() function does the opposite from char() – it returns the unicode number for a given character:

>>> ord('A')
65
Last edited on 18/07/2019