In this post, I will explain how custom python functions are made in QGIS.

Functions in QGIS are listed with the following categories:-

Aggregates Functions Array Functions Color Functions Conditional Functions Conversions Functions Custom Functions Date and Time Functions Fields and Values Files and Paths Functions Form Functions Fuzzy Matching Functions General Functions Geometry Functions Layout Functions Map Layers Maps Functions Mathematical Functions Operators Processing Functions Rasters Functions Record and Attributes Functions Relations String Functions User Expressions Variables Recent Functions

So, if QGIS has all these functions why would one ever need a custom function?

The answer is simple, these are not all the functions in the world. So, most likely there is a function that hasn't been implemented then you can write your custom function.

Lets look at a simple scenario.

Assuming, we have this little python script that generates Hex color codes like these: #40B994, #13E7BC, #3F50EB, #E28326 etc and we want to use it to generate new attribute column with random hex color codes.

from random import choice def color_func(): hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] hex_list = [str(choice(hex)) for x in range(6)] hex_string = '#' + ''.join(hex_list) return hex_string